entities list | max_stars_repo_path stringlengths 4 142 | max_stars_repo_name stringlengths 7 65 | max_stars_count int64 0 14.7k | content stringlengths 40 980k | id stringlengths 1 5 | new_content stringlengths 43 980k | modified bool 1 class | references stringlengths 57 980k |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "C) 2007 Free Software Foundation, Inc.\n\n;; Author: Ralf Angeli <angeli@caeruleus.net>\n;; Maintainer: auctex-deve",
"end": 132,
"score": 0.9998667240142822,
"start": 121,
"tag": "NAME",
"value": "Ralf Angeli"
},
{
"context": "oftware Foundation, Inc.\n\n;; Author: Ralf Angeli <angeli@caeruleus.net>\n;; Maintainer: auctex-devel@gnu.org\n;; Created: ",
"end": 154,
"score": 0.9999372959136963,
"start": 134,
"tag": "EMAIL",
"value": "angeli@caeruleus.net"
},
{
"context": " Ralf Angeli <angeli@caeruleus.net>\n;; Maintainer: auctex-devel@gnu.org\n;; Created: 2007-10-09\n;; Keywords: tex\n\n;; This ",
"end": 191,
"score": 0.9999245405197144,
"start": 171,
"tag": "EMAIL",
"value": "auctex-devel@gnu.org"
}
] | elpa/auctex-12.1.0/style/nomencl.el | hckrtst/emacs-config | 6 | ;;; nomencl.el --- AUCTeX style for the nomencl class.
;; Copyright (C) 2007 Free Software Foundation, Inc.
;; Author: Ralf Angeli <angeli@caeruleus.net>
;; Maintainer: auctex-devel@gnu.org
;; Created: 2007-10-09
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for the nomencl package.
;;; Code:
(defvar LaTeX-nomencl-package-options
'("refeq" "norefeq" "refpage" "norefpage" "prefix" "noprefix" "cfg" "nocfg"
"intoc" "notintoq" "compatible" "noncompatible" "croatian" "danish"
"english" "french" "german" "italian" "polish" "portuguese" "russian"
"spanish" "ukrainian")
"Package options for the nomencl package.")
(TeX-add-style-hook
"nomencl"
(lambda ()
(TeX-add-symbols
'("makenomenclature" 0)
'("printnomenclature" ["Label width"])
'("nomenclature" ["Prefix"] "Symbol" "Description")
"nomrefeq"
"nomrefpage"
"nomrefeqpage"
"nomnorefeq"
"nomnorefpage"
"nomnorefeqpage"
'("nomlabelwidth" 0)
'("nomname" 0)
'("nomgroup" 0)
'("nompreamble" 0)
'("nompostamble" 0)
'("nomitemsep" 0)
'("nomprefix" 0)
'("nomlabel" 0)
'("nomentryend" 0)
'("eqdeclaration" 0)
'("pagedeclaration" 0))
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("nomenclature" "[{{"))
'reference)))
LaTeX-dialect)
;;; nomencl.el ends here
| 34619 | ;;; nomencl.el --- AUCTeX style for the nomencl class.
;; Copyright (C) 2007 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <EMAIL>
;; Created: 2007-10-09
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for the nomencl package.
;;; Code:
(defvar LaTeX-nomencl-package-options
'("refeq" "norefeq" "refpage" "norefpage" "prefix" "noprefix" "cfg" "nocfg"
"intoc" "notintoq" "compatible" "noncompatible" "croatian" "danish"
"english" "french" "german" "italian" "polish" "portuguese" "russian"
"spanish" "ukrainian")
"Package options for the nomencl package.")
(TeX-add-style-hook
"nomencl"
(lambda ()
(TeX-add-symbols
'("makenomenclature" 0)
'("printnomenclature" ["Label width"])
'("nomenclature" ["Prefix"] "Symbol" "Description")
"nomrefeq"
"nomrefpage"
"nomrefeqpage"
"nomnorefeq"
"nomnorefpage"
"nomnorefeqpage"
'("nomlabelwidth" 0)
'("nomname" 0)
'("nomgroup" 0)
'("nompreamble" 0)
'("nompostamble" 0)
'("nomitemsep" 0)
'("nomprefix" 0)
'("nomlabel" 0)
'("nomentryend" 0)
'("eqdeclaration" 0)
'("pagedeclaration" 0))
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("nomenclature" "[{{"))
'reference)))
LaTeX-dialect)
;;; nomencl.el ends here
| true | ;;; nomencl.el --- AUCTeX style for the nomencl class.
;; Copyright (C) 2007 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:EMAIL:<EMAIL>END_PI
;; Created: 2007-10-09
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for the nomencl package.
;;; Code:
(defvar LaTeX-nomencl-package-options
'("refeq" "norefeq" "refpage" "norefpage" "prefix" "noprefix" "cfg" "nocfg"
"intoc" "notintoq" "compatible" "noncompatible" "croatian" "danish"
"english" "french" "german" "italian" "polish" "portuguese" "russian"
"spanish" "ukrainian")
"Package options for the nomencl package.")
(TeX-add-style-hook
"nomencl"
(lambda ()
(TeX-add-symbols
'("makenomenclature" 0)
'("printnomenclature" ["Label width"])
'("nomenclature" ["Prefix"] "Symbol" "Description")
"nomrefeq"
"nomrefpage"
"nomrefeqpage"
"nomnorefeq"
"nomnorefpage"
"nomnorefeqpage"
'("nomlabelwidth" 0)
'("nomname" 0)
'("nomgroup" 0)
'("nompreamble" 0)
'("nompostamble" 0)
'("nomitemsep" 0)
'("nomprefix" 0)
'("nomlabel" 0)
'("nomentryend" 0)
'("eqdeclaration" 0)
'("pagedeclaration" 0))
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("nomenclature" "[{{"))
'reference)))
LaTeX-dialect)
;;; nomencl.el ends here
|
[
{
"context": "cal-binding: t; -*-\n\n;; Copyright (C) 2013-2015 by Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>",
"end": 163,
"score": 0.999871551990509,
"start": 149,
"tag": "NAME",
"value": "Artem Malyshev"
},
{
"context": "yright (C) 2013-2015 by Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>\n;; URL: https://github.com",
"end": 190,
"score": 0.999889075756073,
"start": 176,
"tag": "NAME",
"value": "Artem Malyshev"
},
{
"context": "015 by Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>\n;; URL: https://github.com/proofit404/anaconda-m",
"end": 212,
"score": 0.9999027252197266,
"start": 192,
"tag": "EMAIL",
"value": "proofit404@gmail.com"
},
{
"context": "<proofit404@gmail.com>\n;; URL: https://github.com/proofit404/anaconda-mode\n;; Package-Version: 20150922.537\n;;",
"end": 251,
"score": 0.9922154545783997,
"start": 241,
"tag": "USERNAME",
"value": "proofit404"
},
{
"context": ";; Server.\n\n(defvar anaconda-mode-server-version \"0.1.1\"\n \"Server version needed to run anaconda-mode.\")",
"end": 3008,
"score": 0.9985655546188354,
"start": 3003,
"tag": "IP_ADDRESS",
"value": "0.1.1"
},
{
"context": "e-name\n (pythonic-tramp-connection)))\n \"127.0.0.1\"))\n\n(defun anaconda-mode-start (&optional callbac",
"end": 4705,
"score": 0.9997422695159912,
"start": 4696,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | .emacs.d/elpa/anaconda-mode-20150922.537/anaconda-mode.el | mikhsol/emacs-config | 1 | ;;; anaconda-mode.el --- Code navigation, documentation lookup and completion for Python -*- lexical-binding: t; -*-
;; Copyright (C) 2013-2015 by Artem Malyshev
;; Author: Artem Malyshev <proofit404@gmail.com>
;; URL: https://github.com/proofit404/anaconda-mode
;; Package-Version: 20150922.537
;; Version: 0.1.1
;; Package-Requires: ((emacs "24") (pythonic "0.1.0") (dash "2.6.0") (s "1.9") (f "0.16.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README for more details.
;;; Code:
(eval-when-compile
(defvar url-http-end-of-headers))
(require 'tramp)
(require 'url)
(require 'json)
(require 'pythonic)
(require 'dash)
(require 's)
(require 'f)
(defgroup anaconda-mode nil
"Code navigation, documentation lookup and completion for Python."
:group 'programming)
(defcustom anaconda-mode-installation-directory
"~/.emacs.d/anaconda-mode"
"Installation directory for anaconda-mode server."
:group 'anaconda-mode
:type 'directory)
(defcustom anaconda-mode-complete-callback
'anaconda-mode-complete-callback
"Callback function used to display `anaconda-mode-complete' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-show-doc-callback
'anaconda-mode-show-doc-callback
"Callback function used to display `anaconda-mode-show-doc' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-definitions-callback
'anaconda-mode-find-definitions-callback
"Callback function used to display `anaconda-mode-find-definitions' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-assignments-callback
'anaconda-mode-find-assignments-callback
"Callback function used to display `anaconda-mode-find-assignments' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-references-callback
'anaconda-mode-find-references-callback
"Callback function used to display `anaconda-mode-find-references' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-callback
'anaconda-mode-eldoc-callback
"Callback function used to display `anaconda-mode-eldoc-function' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-as-single-line nil
"If not nil, trim eldoc string to frame width."
:group 'anaconda-mode
:type 'boolean)
;;; Server.
(defvar anaconda-mode-server-version "0.1.1"
"Server version needed to run anaconda-mode.")
(defvar anaconda-mode-server-script "anaconda_mode.py"
"Script file with anaconda-mode server.")
(defvar anaconda-mode-process-name "anaconda-mode"
"Process name for anaconda-mode processes.")
(defvar anaconda-mode-process-buffer "*anaconda-mode*"
"Buffer name for anaconda-mode processes.")
(defvar anaconda-mode-process nil
"Currently running anaconda-mode process.")
(defvar anaconda-mode-port nil
"Port for anaconda-mode connection.")
(defvar anaconda-mode-ensure-directory-command "
import os
import sys
directory = sys.argv[-1]
if not os.path.exists(directory):
os.makedirs(directory)
" "Create `anaconda-mode-server-directory' if necessary.")
(defvar anaconda-mode-check-installation-command "
import sys, os
from pkg_resources import find_distributions
directory = sys.argv[-1]
for dist in find_distributions(directory, only=True):
if dist.project_name == 'anaconda-mode':
break
else:
# IPython patch sys.exit, so we can't use it.
os._exit(1)
" "Check if `anaconda-mode' server is installed or not.")
(defvar anaconda-mode-install-server-command "
import sys
import pip
directory = sys.argv[-2]
version = sys.argv[-1]
pip.main(['install', '-t', directory, 'anaconda_mode==' + version])
" "Install `anaconda_mode' server.")
(defun anaconda-mode-server-directory ()
"Anaconda mode installation directory."
(f-join anaconda-mode-installation-directory anaconda-mode-server-version))
(defun anaconda-mode-host ()
"Target host with anaconda-mode server."
(if (pythonic-remote-p)
(tramp-file-name-host
(tramp-dissect-file-name
(pythonic-tramp-connection)))
"127.0.0.1"))
(defun anaconda-mode-start (&optional callback)
"Start anaconda-mode server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(when (anaconda-mode-need-restart)
(anaconda-mode-stop))
(if (anaconda-mode-running-p)
(when callback
(funcall callback))
(anaconda-mode-ensure-directory callback)))
(defun anaconda-mode-stop ()
"Stop anaconda-mode server."
(when (anaconda-mode-running-p)
(set-process-filter anaconda-mode-process nil)
(set-process-sentinel anaconda-mode-process nil)
(kill-process anaconda-mode-process)
(setq anaconda-mode-process nil
anaconda-mode-port nil)))
(defun anaconda-mode-running-p ()
"Is `anaconda-mode' server running."
(and anaconda-mode-process
(process-live-p anaconda-mode-process)))
(defun anaconda-mode-bound-p ()
"Is `anaconda-mode' port bound."
(numberp anaconda-mode-port))
(defun anaconda-mode-need-restart ()
"Check if we need to restart `anaconda-mode-server'."
(when (and (anaconda-mode-running-p)
(anaconda-mode-bound-p))
(or (not (pythonic-proper-environment-p anaconda-mode-process))
(not (equal (process-get anaconda-mode-process 'server-directory)
(anaconda-mode-server-directory))))))
(defun anaconda-mode-ensure-directory (&optional callback)
"Ensure if `anaconda-mode-server-directory' exists.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-ensure-directory-sentinel process event callback))
:args (list "-c"
anaconda-mode-ensure-directory-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-ensure-directory-sentinel (process _event &optional callback)
"Run `anaconda-mode-check' if `anaconda-mode-server-directory' exists.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-check callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't create %s directory"
(anaconda-mode-server-directory))))
(defun anaconda-mode-check (&optional callback)
"Check `anaconda-mode' server installation.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-check-sentinel process event callback))
:args (list "-c"
anaconda-mode-check-installation-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-check-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation check passed.
Try to install `anaconda-mode' server otherwise. PROCESS and
EVENT are basic sentinel parameters. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(anaconda-mode-install callback)))
(defun anaconda-mode-install (&optional callback)
"Try to install `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-install-sentinel process event callback))
:args (list "-c"
anaconda-mode-install-server-command
(anaconda-mode-server-directory)
anaconda-mode-server-version))))
(defun anaconda-mode-install-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation complete successfully.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't install `anaconda-mode' server")))
(defun anaconda-mode-bootstrap (&optional callback)
"Run `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:cwd (anaconda-mode-server-directory)
:filter (lambda (process output) (anaconda-mode-bootstrap-filter process output callback))
:sentinel 'anaconda-mode-bootstrap-sentinel
:query-on-exit nil
:args (list anaconda-mode-server-script)))
(process-put anaconda-mode-process 'server-directory (anaconda-mode-server-directory)))
(defun anaconda-mode-bootstrap-filter (process output &optional callback)
"Set `anaconda-mode-port' from PROCESS OUTPUT.
Connect to the `anaconda-mode' server. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
;; Mimic default filter.
(when (buffer-live-p (process-buffer process))
(with-current-buffer (process-buffer process)
(save-excursion
(goto-char (process-mark process))
(insert output)
(set-marker (process-mark process) (point)))))
(--when-let (s-match "anaconda_mode port \\([0-9]+\\)" output)
(setq anaconda-mode-port (string-to-number (cadr it)))
(set-process-filter process nil)
(when callback
(funcall callback))))
(defun anaconda-mode-bootstrap-sentinel (process _event)
"Raise error if `anaconda-mode' server exit abnormally.
PROCESS and EVENT are basic sentinel parameters."
(unless (eq 0 (process-exit-status process))
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't start `anaconda-mode' server")))
;;; Interaction.
(defun anaconda-mode-call (command callback)
"Make remote procedure call for COMMAND.
Apply CALLBACK to it result."
(anaconda-mode-start
(lambda () (anaconda-mode-jsonrpc command callback))))
(defun anaconda-mode-jsonrpc (command callback)
"Perform JSONRPC call for COMMAND.
Apply CALLBACK to the call result when retrieve it. Remote
COMMAND must expect four arguments: python buffer content, line
number position, column number position and file path."
(let ((url-request-method "POST")
(url-request-data (anaconda-mode-jsonrpc-request command)))
(url-retrieve
(format "http://%s:%s" (anaconda-mode-host) anaconda-mode-port)
(anaconda-mode-create-response-handler command callback)
nil
t)))
(defun anaconda-mode-jsonrpc-request (command)
"Prepare JSON encoded buffer data for COMMAND call."
(json-encode (anaconda-mode-jsonrpc-request-data command)))
(defun anaconda-mode-jsonrpc-request-data (command)
"Prepare buffer data for COMMAND call."
`((jsonrpc . "2.0")
(id . 1)
(method . ,command)
(params . ((source . ,(buffer-substring-no-properties (point-min) (point-max)))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))
(path . ,(when (buffer-file-name)
(pythonic-file-name (buffer-file-name))))))))
(defun anaconda-mode-create-response-handler (command callback)
"Create server response handler based on COMMAND and CALLBACK function.
COMMAND argument will be used for response skip message.
Response can be skipped if point was moved sense request was
submitted."
(let ((anaconda-mode-request-point (point))
(anaconda-mode-request-buffer (current-buffer))
(anaconda-mode-request-window (selected-window))
(anaconda-mode-request-tick (buffer-chars-modified-tick)))
(lambda (_status)
(let ((http-buffer (current-buffer)))
(unwind-protect
(if (or (not (equal anaconda-mode-request-window (selected-window)))
(with-current-buffer (window-buffer anaconda-mode-request-window)
(or (not (equal anaconda-mode-request-buffer (current-buffer)))
(not (equal anaconda-mode-request-point (point)))
(not (equal anaconda-mode-request-tick (buffer-chars-modified-tick))))))
(message "Skip anaconda-mode %s response" command)
(goto-char url-http-end-of-headers)
(let* ((json-array-type 'list)
(response (condition-case nil
(json-read)
(json-readtable-error
(progn
(let ((response-string (buffer-string)))
(pop-to-buffer
(with-current-buffer (get-buffer-create "*anaconda-response*")
(insert response-string)
(goto-char (point-min))
(current-buffer))))
(error "Can't read anaconda-mode server response"))))))
(if (assoc 'error response)
(error (cdr (assoc 'error response)))
(with-current-buffer anaconda-mode-request-buffer
;; Terminate `apply' call with empty list so response
;; will be treated as single argument.
(apply callback (cdr (assoc 'result response)) nil)))))
(kill-buffer http-buffer))))))
;;; Code completion.
(defun anaconda-mode-complete ()
"Request completion candidates."
(interactive)
(unless (python-syntax-comment-or-string-p)
(anaconda-mode-call "complete" anaconda-mode-complete-callback)))
(defun anaconda-mode-complete-callback (result)
"Start interactive completion on RESULT receiving."
(let* ((bounds (bounds-of-thing-at-point 'symbol))
(start (or (car bounds) (point)))
(stop (or (cdr bounds) (point)))
(collection (anaconda-mode-complete-extract-names result))
(completion-extra-properties '(:annotation-function anaconda-mode-complete-annotation)))
(completion-in-region start stop collection)))
(defun anaconda-mode-complete-extract-names (result)
"Extract completion names from anaconda-mode RESULT."
(--map (let* ((name (cdr (assoc 'name it)))
(type (cdr (assoc 'type it)))
(module-path (cdr (assoc 'module-path it)))
(line (cdr (assoc 'line it)))
(docstring (cdr (assoc 'docstring it)))
(description (if (equal type "statement")
"statement"
(cdr (assoc 'description it)))))
(put-text-property 0 1 'description description name)
(put-text-property 0 1 'module-path module-path name)
(put-text-property 0 1 'line line name)
(put-text-property 0 1 'docstring docstring name)
name)
result))
(defun anaconda-mode-complete-annotation (candidate)
"Get annotation for CANDIDATE."
(--when-let (get-text-property 0 'description candidate)
(concat " <" it ">")))
;;; View documentation.
(defun anaconda-mode-show-doc ()
"Show documentation for context at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-show-doc-callback))
(defun anaconda-mode-show-doc-callback (result)
"Process view doc RESULT."
(if result
(anaconda-mode-documentation-view result)
(message "No documentation available")))
;;; Find definitions.
(defun anaconda-mode-find-definitions ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-find-definitions-callback))
(defun anaconda-mode-find-definitions-callback (result)
"Process find definitions RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No definitions found")))
;;; Find assignments.
(defun anaconda-mode-find-assignments ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call "goto_assignments" anaconda-mode-find-assignments-callback))
(defun anaconda-mode-find-assignments-callback (result)
"Process find assignments RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No assignments found")))
;;; Find references.
(defun anaconda-mode-find-references ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call "usages" anaconda-mode-find-references-callback))
(defun anaconda-mode-find-references-callback (result)
"Process find references RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No references found")))
;;; Eldoc.
(defun anaconda-mode-eldoc-function ()
"Show eldoc for context at point."
(anaconda-mode-call "eldoc" anaconda-mode-eldoc-callback))
(defun anaconda-mode-eldoc-callback (result)
"Display eldoc from server RESULT."
(eldoc-message (anaconda-mode-eldoc-format result)))
(defun anaconda-mode-eldoc-format (result)
"Format eldoc string from RESULT."
(when result
(let* ((name (cdr (assoc 'name result)))
(index (or (cdr (assoc 'index result)) 0))
(params (cdr (assoc 'params result)))
(doc (anaconda-mode-eldoc-format-definition name index params)))
(if anaconda-mode-eldoc-as-single-line
(substring doc 0 (min (frame-width) (length doc)))
doc))))
(defun anaconda-mode-eldoc-format-definition (name index params)
"Format function definition from NAME, INDEX and PARAMS."
(concat
(propertize name 'face 'font-lock-function-name-face)
"("
(anaconda-mode-eldoc-format-params params index)
")"))
(defun anaconda-mode-eldoc-format-params (args index)
"Build colorized ARGS string with current arg pointed to INDEX."
(->>
args
(--map-indexed
(if (= index it-index)
(propertize it 'face 'eldoc-highlight-function-argument)
it))
(-interpose ", ")
(apply 'concat)))
;;; Result view.
(defmacro anaconda-mode-with-view-buffer (&rest body)
"Create view buffer and execute BODY in it."
`(let ((buf (get-buffer-create "*Anaconda*")))
(with-current-buffer buf
(setq buffer-read-only nil)
(erase-buffer)
,@body
(goto-char (point-min))
(anaconda-mode-view-mode)
buf)))
(defun anaconda-mode-definitions-view (result)
"Show definitions view for rpc RESULT."
(if (eq 1 (length result))
(anaconda-mode-find-file (car result))
(anaconda-mode-view result 'anaconda-mode-view-definitions-presenter)))
(defun anaconda-mode-documentation-view (result)
"Show documentation view for rpc RESULT."
(anaconda-mode-view result 'anaconda-mode-view-documentation-presenter))
(defun anaconda-mode-view (result presenter)
"Show RESULT to user for future selection.
RESULT must be an RESULT field from json-rpc response.
PRESENTER is the function used to format buffer content."
(pop-to-buffer
(anaconda-mode-with-view-buffer
(funcall presenter result))))
(defun anaconda-mode-view-make-bold (string)
"Make passed STRING look bold."
(propertize string 'face 'bold))
(defun anaconda-mode-view-make-source (string)
"Make passed STRING look like python source."
(with-temp-buffer
(insert string)
(let ((delay-mode-hooks t))
(python-mode))
(run-hooks 'font-lock-mode-hook)
(font-lock-fontify-buffer)
(buffer-string)))
(define-button-type 'anaconda-mode-definition-button
'action #'anaconda-mode-view-jump
'face nil)
(defun anaconda-mode-view-jump (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file definition)))
(defun anaconda-mode-view-jump-other-window (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file-other-window definition)))
(defun anaconda-mode-find-file (definition)
"Find DEFINITION file, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file))
(defun anaconda-mode-find-file-other-window (definition)
"Find DEFINITION file other window, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file-other-window))
(defvar-local anaconda-mode-go-back-definition nil
"Previous definition from which current buffer was navigated.")
(defun anaconda-mode-find-file-generic (definition find-function)
"Find DEFINITION with FIND-FUNCTION."
(let ((backward-navigation (when (buffer-file-name)
`((module-path . ,(buffer-file-name))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))))))
(--if-let (cdr (assoc 'module-path definition))
(progn
(funcall find-function it)
(goto-char 0)
(forward-line (1- (cdr (assoc 'line definition))))
(forward-char (cdr (assoc 'column definition)))
(setq anaconda-mode-go-back-definition backward-navigation))
(message "Can't open %s module" (cdr (assoc 'module-name definition))))))
(defun anaconda-mode-view-insert-button (name definition)
"Insert text button with NAME opening the DEFINITION."
(insert-text-button name
'type 'anaconda-mode-definition-button
'definition definition))
(defun anaconda-mode-view-definitions-presenter (result)
"Insert definitions from RESULT."
(->>
(--group-by (cdr (assoc 'module-name it)) result)
(--map (anaconda-mode-view-insert-module-definition it))))
(defun anaconda-mode-view-insert-module-definition (module)
"Insert MODULE definition into current buffer."
(insert (concat (anaconda-mode-view-make-bold (car module)) "\n"))
(--map
(progn
(insert " ")
(anaconda-mode-view-insert-button
(anaconda-mode-view-make-source (cdr (assoc 'description it)))
it)
(insert "\n"))
(cdr module)))
(defun anaconda-mode-view-documentation-presenter (result)
"Insert documentation from RESULT."
(--map
(progn
(insert (anaconda-mode-view-make-bold (cdr (assoc 'module-name it))))
(insert "\n")
(insert (s-trim-right (cdr (assoc 'docstring it))))
(insert "\n\n"))
result))
(defvar anaconda-mode-view-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "n") 'next-error-no-select)
(define-key map (kbd "p") 'previous-error-no-select)
(define-key map (kbd "q") 'quit-window)
map))
(define-derived-mode anaconda-mode-view-mode special-mode "Anaconda-View"
"Major mode for definitions view and navigation for `anaconda-mode'.
\\{anaconda-mode-view-mode-map}"
(setq next-error-function #'anaconda-mode-next-definition))
(defun anaconda-mode-next-definition (num _reset)
"Navigate tot the next definition in the view buffer.
NUM is the number of definitions to move forward. RESET mean go
to the beginning of buffer before definitions navigation."
(forward-button num)
(anaconda-mode-view-jump-other-window (button-at (point))))
(defun anaconda-mode-go-back ()
"Jump backward if buffer was navigated from `anaconda-mode' command."
(interactive)
(if anaconda-mode-go-back-definition
(anaconda-mode-find-file anaconda-mode-go-back-definition)
(error "No previous buffer")))
;;; Anaconda minor mode.
(defvar anaconda-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-M-i") 'anaconda-mode-complete)
(define-key map (kbd "M-.") 'anaconda-mode-find-definitions)
(define-key map (kbd "M-,") 'anaconda-mode-find-assignments)
(define-key map (kbd "M-r") 'anaconda-mode-find-references)
(define-key map (kbd "M-*") 'anaconda-mode-go-back)
(define-key map (kbd "M-?") 'anaconda-mode-show-doc)
map)
"Keymap for `anaconda-mode'.")
;;;###autoload
(define-minor-mode anaconda-mode
"Code navigation, documentation lookup and completion for Python.
\\{anaconda-mode-map}"
:lighter " Anaconda"
:keymap anaconda-mode-map
(if anaconda-mode
(turn-on-anaconda-mode)
(turn-off-anaconda-mode)))
(defun turn-on-anaconda-mode ()
"Turn on `anaconda-mode'."
(make-local-variable 'eldoc-documentation-function)
(setq-local eldoc-documentation-function 'anaconda-mode-eldoc-function))
(defun turn-off-anaconda-mode ()
"Turn off `anaconda-mode'."
(kill-local-variable 'eldoc-documentation-function))
(provide 'anaconda-mode)
;;; anaconda-mode.el ends here
| 37761 | ;;; anaconda-mode.el --- Code navigation, documentation lookup and completion for Python -*- lexical-binding: t; -*-
;; Copyright (C) 2013-2015 by <NAME>
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/proofit404/anaconda-mode
;; Package-Version: 20150922.537
;; Version: 0.1.1
;; Package-Requires: ((emacs "24") (pythonic "0.1.0") (dash "2.6.0") (s "1.9") (f "0.16.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README for more details.
;;; Code:
(eval-when-compile
(defvar url-http-end-of-headers))
(require 'tramp)
(require 'url)
(require 'json)
(require 'pythonic)
(require 'dash)
(require 's)
(require 'f)
(defgroup anaconda-mode nil
"Code navigation, documentation lookup and completion for Python."
:group 'programming)
(defcustom anaconda-mode-installation-directory
"~/.emacs.d/anaconda-mode"
"Installation directory for anaconda-mode server."
:group 'anaconda-mode
:type 'directory)
(defcustom anaconda-mode-complete-callback
'anaconda-mode-complete-callback
"Callback function used to display `anaconda-mode-complete' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-show-doc-callback
'anaconda-mode-show-doc-callback
"Callback function used to display `anaconda-mode-show-doc' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-definitions-callback
'anaconda-mode-find-definitions-callback
"Callback function used to display `anaconda-mode-find-definitions' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-assignments-callback
'anaconda-mode-find-assignments-callback
"Callback function used to display `anaconda-mode-find-assignments' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-references-callback
'anaconda-mode-find-references-callback
"Callback function used to display `anaconda-mode-find-references' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-callback
'anaconda-mode-eldoc-callback
"Callback function used to display `anaconda-mode-eldoc-function' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-as-single-line nil
"If not nil, trim eldoc string to frame width."
:group 'anaconda-mode
:type 'boolean)
;;; Server.
(defvar anaconda-mode-server-version "0.1.1"
"Server version needed to run anaconda-mode.")
(defvar anaconda-mode-server-script "anaconda_mode.py"
"Script file with anaconda-mode server.")
(defvar anaconda-mode-process-name "anaconda-mode"
"Process name for anaconda-mode processes.")
(defvar anaconda-mode-process-buffer "*anaconda-mode*"
"Buffer name for anaconda-mode processes.")
(defvar anaconda-mode-process nil
"Currently running anaconda-mode process.")
(defvar anaconda-mode-port nil
"Port for anaconda-mode connection.")
(defvar anaconda-mode-ensure-directory-command "
import os
import sys
directory = sys.argv[-1]
if not os.path.exists(directory):
os.makedirs(directory)
" "Create `anaconda-mode-server-directory' if necessary.")
(defvar anaconda-mode-check-installation-command "
import sys, os
from pkg_resources import find_distributions
directory = sys.argv[-1]
for dist in find_distributions(directory, only=True):
if dist.project_name == 'anaconda-mode':
break
else:
# IPython patch sys.exit, so we can't use it.
os._exit(1)
" "Check if `anaconda-mode' server is installed or not.")
(defvar anaconda-mode-install-server-command "
import sys
import pip
directory = sys.argv[-2]
version = sys.argv[-1]
pip.main(['install', '-t', directory, 'anaconda_mode==' + version])
" "Install `anaconda_mode' server.")
(defun anaconda-mode-server-directory ()
"Anaconda mode installation directory."
(f-join anaconda-mode-installation-directory anaconda-mode-server-version))
(defun anaconda-mode-host ()
"Target host with anaconda-mode server."
(if (pythonic-remote-p)
(tramp-file-name-host
(tramp-dissect-file-name
(pythonic-tramp-connection)))
"127.0.0.1"))
(defun anaconda-mode-start (&optional callback)
"Start anaconda-mode server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(when (anaconda-mode-need-restart)
(anaconda-mode-stop))
(if (anaconda-mode-running-p)
(when callback
(funcall callback))
(anaconda-mode-ensure-directory callback)))
(defun anaconda-mode-stop ()
"Stop anaconda-mode server."
(when (anaconda-mode-running-p)
(set-process-filter anaconda-mode-process nil)
(set-process-sentinel anaconda-mode-process nil)
(kill-process anaconda-mode-process)
(setq anaconda-mode-process nil
anaconda-mode-port nil)))
(defun anaconda-mode-running-p ()
"Is `anaconda-mode' server running."
(and anaconda-mode-process
(process-live-p anaconda-mode-process)))
(defun anaconda-mode-bound-p ()
"Is `anaconda-mode' port bound."
(numberp anaconda-mode-port))
(defun anaconda-mode-need-restart ()
"Check if we need to restart `anaconda-mode-server'."
(when (and (anaconda-mode-running-p)
(anaconda-mode-bound-p))
(or (not (pythonic-proper-environment-p anaconda-mode-process))
(not (equal (process-get anaconda-mode-process 'server-directory)
(anaconda-mode-server-directory))))))
(defun anaconda-mode-ensure-directory (&optional callback)
"Ensure if `anaconda-mode-server-directory' exists.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-ensure-directory-sentinel process event callback))
:args (list "-c"
anaconda-mode-ensure-directory-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-ensure-directory-sentinel (process _event &optional callback)
"Run `anaconda-mode-check' if `anaconda-mode-server-directory' exists.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-check callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't create %s directory"
(anaconda-mode-server-directory))))
(defun anaconda-mode-check (&optional callback)
"Check `anaconda-mode' server installation.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-check-sentinel process event callback))
:args (list "-c"
anaconda-mode-check-installation-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-check-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation check passed.
Try to install `anaconda-mode' server otherwise. PROCESS and
EVENT are basic sentinel parameters. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(anaconda-mode-install callback)))
(defun anaconda-mode-install (&optional callback)
"Try to install `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-install-sentinel process event callback))
:args (list "-c"
anaconda-mode-install-server-command
(anaconda-mode-server-directory)
anaconda-mode-server-version))))
(defun anaconda-mode-install-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation complete successfully.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't install `anaconda-mode' server")))
(defun anaconda-mode-bootstrap (&optional callback)
"Run `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:cwd (anaconda-mode-server-directory)
:filter (lambda (process output) (anaconda-mode-bootstrap-filter process output callback))
:sentinel 'anaconda-mode-bootstrap-sentinel
:query-on-exit nil
:args (list anaconda-mode-server-script)))
(process-put anaconda-mode-process 'server-directory (anaconda-mode-server-directory)))
(defun anaconda-mode-bootstrap-filter (process output &optional callback)
"Set `anaconda-mode-port' from PROCESS OUTPUT.
Connect to the `anaconda-mode' server. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
;; Mimic default filter.
(when (buffer-live-p (process-buffer process))
(with-current-buffer (process-buffer process)
(save-excursion
(goto-char (process-mark process))
(insert output)
(set-marker (process-mark process) (point)))))
(--when-let (s-match "anaconda_mode port \\([0-9]+\\)" output)
(setq anaconda-mode-port (string-to-number (cadr it)))
(set-process-filter process nil)
(when callback
(funcall callback))))
(defun anaconda-mode-bootstrap-sentinel (process _event)
"Raise error if `anaconda-mode' server exit abnormally.
PROCESS and EVENT are basic sentinel parameters."
(unless (eq 0 (process-exit-status process))
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't start `anaconda-mode' server")))
;;; Interaction.
(defun anaconda-mode-call (command callback)
"Make remote procedure call for COMMAND.
Apply CALLBACK to it result."
(anaconda-mode-start
(lambda () (anaconda-mode-jsonrpc command callback))))
(defun anaconda-mode-jsonrpc (command callback)
"Perform JSONRPC call for COMMAND.
Apply CALLBACK to the call result when retrieve it. Remote
COMMAND must expect four arguments: python buffer content, line
number position, column number position and file path."
(let ((url-request-method "POST")
(url-request-data (anaconda-mode-jsonrpc-request command)))
(url-retrieve
(format "http://%s:%s" (anaconda-mode-host) anaconda-mode-port)
(anaconda-mode-create-response-handler command callback)
nil
t)))
(defun anaconda-mode-jsonrpc-request (command)
"Prepare JSON encoded buffer data for COMMAND call."
(json-encode (anaconda-mode-jsonrpc-request-data command)))
(defun anaconda-mode-jsonrpc-request-data (command)
"Prepare buffer data for COMMAND call."
`((jsonrpc . "2.0")
(id . 1)
(method . ,command)
(params . ((source . ,(buffer-substring-no-properties (point-min) (point-max)))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))
(path . ,(when (buffer-file-name)
(pythonic-file-name (buffer-file-name))))))))
(defun anaconda-mode-create-response-handler (command callback)
"Create server response handler based on COMMAND and CALLBACK function.
COMMAND argument will be used for response skip message.
Response can be skipped if point was moved sense request was
submitted."
(let ((anaconda-mode-request-point (point))
(anaconda-mode-request-buffer (current-buffer))
(anaconda-mode-request-window (selected-window))
(anaconda-mode-request-tick (buffer-chars-modified-tick)))
(lambda (_status)
(let ((http-buffer (current-buffer)))
(unwind-protect
(if (or (not (equal anaconda-mode-request-window (selected-window)))
(with-current-buffer (window-buffer anaconda-mode-request-window)
(or (not (equal anaconda-mode-request-buffer (current-buffer)))
(not (equal anaconda-mode-request-point (point)))
(not (equal anaconda-mode-request-tick (buffer-chars-modified-tick))))))
(message "Skip anaconda-mode %s response" command)
(goto-char url-http-end-of-headers)
(let* ((json-array-type 'list)
(response (condition-case nil
(json-read)
(json-readtable-error
(progn
(let ((response-string (buffer-string)))
(pop-to-buffer
(with-current-buffer (get-buffer-create "*anaconda-response*")
(insert response-string)
(goto-char (point-min))
(current-buffer))))
(error "Can't read anaconda-mode server response"))))))
(if (assoc 'error response)
(error (cdr (assoc 'error response)))
(with-current-buffer anaconda-mode-request-buffer
;; Terminate `apply' call with empty list so response
;; will be treated as single argument.
(apply callback (cdr (assoc 'result response)) nil)))))
(kill-buffer http-buffer))))))
;;; Code completion.
(defun anaconda-mode-complete ()
"Request completion candidates."
(interactive)
(unless (python-syntax-comment-or-string-p)
(anaconda-mode-call "complete" anaconda-mode-complete-callback)))
(defun anaconda-mode-complete-callback (result)
"Start interactive completion on RESULT receiving."
(let* ((bounds (bounds-of-thing-at-point 'symbol))
(start (or (car bounds) (point)))
(stop (or (cdr bounds) (point)))
(collection (anaconda-mode-complete-extract-names result))
(completion-extra-properties '(:annotation-function anaconda-mode-complete-annotation)))
(completion-in-region start stop collection)))
(defun anaconda-mode-complete-extract-names (result)
"Extract completion names from anaconda-mode RESULT."
(--map (let* ((name (cdr (assoc 'name it)))
(type (cdr (assoc 'type it)))
(module-path (cdr (assoc 'module-path it)))
(line (cdr (assoc 'line it)))
(docstring (cdr (assoc 'docstring it)))
(description (if (equal type "statement")
"statement"
(cdr (assoc 'description it)))))
(put-text-property 0 1 'description description name)
(put-text-property 0 1 'module-path module-path name)
(put-text-property 0 1 'line line name)
(put-text-property 0 1 'docstring docstring name)
name)
result))
(defun anaconda-mode-complete-annotation (candidate)
"Get annotation for CANDIDATE."
(--when-let (get-text-property 0 'description candidate)
(concat " <" it ">")))
;;; View documentation.
(defun anaconda-mode-show-doc ()
"Show documentation for context at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-show-doc-callback))
(defun anaconda-mode-show-doc-callback (result)
"Process view doc RESULT."
(if result
(anaconda-mode-documentation-view result)
(message "No documentation available")))
;;; Find definitions.
(defun anaconda-mode-find-definitions ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-find-definitions-callback))
(defun anaconda-mode-find-definitions-callback (result)
"Process find definitions RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No definitions found")))
;;; Find assignments.
(defun anaconda-mode-find-assignments ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call "goto_assignments" anaconda-mode-find-assignments-callback))
(defun anaconda-mode-find-assignments-callback (result)
"Process find assignments RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No assignments found")))
;;; Find references.
(defun anaconda-mode-find-references ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call "usages" anaconda-mode-find-references-callback))
(defun anaconda-mode-find-references-callback (result)
"Process find references RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No references found")))
;;; Eldoc.
(defun anaconda-mode-eldoc-function ()
"Show eldoc for context at point."
(anaconda-mode-call "eldoc" anaconda-mode-eldoc-callback))
(defun anaconda-mode-eldoc-callback (result)
"Display eldoc from server RESULT."
(eldoc-message (anaconda-mode-eldoc-format result)))
(defun anaconda-mode-eldoc-format (result)
"Format eldoc string from RESULT."
(when result
(let* ((name (cdr (assoc 'name result)))
(index (or (cdr (assoc 'index result)) 0))
(params (cdr (assoc 'params result)))
(doc (anaconda-mode-eldoc-format-definition name index params)))
(if anaconda-mode-eldoc-as-single-line
(substring doc 0 (min (frame-width) (length doc)))
doc))))
(defun anaconda-mode-eldoc-format-definition (name index params)
"Format function definition from NAME, INDEX and PARAMS."
(concat
(propertize name 'face 'font-lock-function-name-face)
"("
(anaconda-mode-eldoc-format-params params index)
")"))
(defun anaconda-mode-eldoc-format-params (args index)
"Build colorized ARGS string with current arg pointed to INDEX."
(->>
args
(--map-indexed
(if (= index it-index)
(propertize it 'face 'eldoc-highlight-function-argument)
it))
(-interpose ", ")
(apply 'concat)))
;;; Result view.
(defmacro anaconda-mode-with-view-buffer (&rest body)
"Create view buffer and execute BODY in it."
`(let ((buf (get-buffer-create "*Anaconda*")))
(with-current-buffer buf
(setq buffer-read-only nil)
(erase-buffer)
,@body
(goto-char (point-min))
(anaconda-mode-view-mode)
buf)))
(defun anaconda-mode-definitions-view (result)
"Show definitions view for rpc RESULT."
(if (eq 1 (length result))
(anaconda-mode-find-file (car result))
(anaconda-mode-view result 'anaconda-mode-view-definitions-presenter)))
(defun anaconda-mode-documentation-view (result)
"Show documentation view for rpc RESULT."
(anaconda-mode-view result 'anaconda-mode-view-documentation-presenter))
(defun anaconda-mode-view (result presenter)
"Show RESULT to user for future selection.
RESULT must be an RESULT field from json-rpc response.
PRESENTER is the function used to format buffer content."
(pop-to-buffer
(anaconda-mode-with-view-buffer
(funcall presenter result))))
(defun anaconda-mode-view-make-bold (string)
"Make passed STRING look bold."
(propertize string 'face 'bold))
(defun anaconda-mode-view-make-source (string)
"Make passed STRING look like python source."
(with-temp-buffer
(insert string)
(let ((delay-mode-hooks t))
(python-mode))
(run-hooks 'font-lock-mode-hook)
(font-lock-fontify-buffer)
(buffer-string)))
(define-button-type 'anaconda-mode-definition-button
'action #'anaconda-mode-view-jump
'face nil)
(defun anaconda-mode-view-jump (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file definition)))
(defun anaconda-mode-view-jump-other-window (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file-other-window definition)))
(defun anaconda-mode-find-file (definition)
"Find DEFINITION file, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file))
(defun anaconda-mode-find-file-other-window (definition)
"Find DEFINITION file other window, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file-other-window))
(defvar-local anaconda-mode-go-back-definition nil
"Previous definition from which current buffer was navigated.")
(defun anaconda-mode-find-file-generic (definition find-function)
"Find DEFINITION with FIND-FUNCTION."
(let ((backward-navigation (when (buffer-file-name)
`((module-path . ,(buffer-file-name))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))))))
(--if-let (cdr (assoc 'module-path definition))
(progn
(funcall find-function it)
(goto-char 0)
(forward-line (1- (cdr (assoc 'line definition))))
(forward-char (cdr (assoc 'column definition)))
(setq anaconda-mode-go-back-definition backward-navigation))
(message "Can't open %s module" (cdr (assoc 'module-name definition))))))
(defun anaconda-mode-view-insert-button (name definition)
"Insert text button with NAME opening the DEFINITION."
(insert-text-button name
'type 'anaconda-mode-definition-button
'definition definition))
(defun anaconda-mode-view-definitions-presenter (result)
"Insert definitions from RESULT."
(->>
(--group-by (cdr (assoc 'module-name it)) result)
(--map (anaconda-mode-view-insert-module-definition it))))
(defun anaconda-mode-view-insert-module-definition (module)
"Insert MODULE definition into current buffer."
(insert (concat (anaconda-mode-view-make-bold (car module)) "\n"))
(--map
(progn
(insert " ")
(anaconda-mode-view-insert-button
(anaconda-mode-view-make-source (cdr (assoc 'description it)))
it)
(insert "\n"))
(cdr module)))
(defun anaconda-mode-view-documentation-presenter (result)
"Insert documentation from RESULT."
(--map
(progn
(insert (anaconda-mode-view-make-bold (cdr (assoc 'module-name it))))
(insert "\n")
(insert (s-trim-right (cdr (assoc 'docstring it))))
(insert "\n\n"))
result))
(defvar anaconda-mode-view-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "n") 'next-error-no-select)
(define-key map (kbd "p") 'previous-error-no-select)
(define-key map (kbd "q") 'quit-window)
map))
(define-derived-mode anaconda-mode-view-mode special-mode "Anaconda-View"
"Major mode for definitions view and navigation for `anaconda-mode'.
\\{anaconda-mode-view-mode-map}"
(setq next-error-function #'anaconda-mode-next-definition))
(defun anaconda-mode-next-definition (num _reset)
"Navigate tot the next definition in the view buffer.
NUM is the number of definitions to move forward. RESET mean go
to the beginning of buffer before definitions navigation."
(forward-button num)
(anaconda-mode-view-jump-other-window (button-at (point))))
(defun anaconda-mode-go-back ()
"Jump backward if buffer was navigated from `anaconda-mode' command."
(interactive)
(if anaconda-mode-go-back-definition
(anaconda-mode-find-file anaconda-mode-go-back-definition)
(error "No previous buffer")))
;;; Anaconda minor mode.
(defvar anaconda-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-M-i") 'anaconda-mode-complete)
(define-key map (kbd "M-.") 'anaconda-mode-find-definitions)
(define-key map (kbd "M-,") 'anaconda-mode-find-assignments)
(define-key map (kbd "M-r") 'anaconda-mode-find-references)
(define-key map (kbd "M-*") 'anaconda-mode-go-back)
(define-key map (kbd "M-?") 'anaconda-mode-show-doc)
map)
"Keymap for `anaconda-mode'.")
;;;###autoload
(define-minor-mode anaconda-mode
"Code navigation, documentation lookup and completion for Python.
\\{anaconda-mode-map}"
:lighter " Anaconda"
:keymap anaconda-mode-map
(if anaconda-mode
(turn-on-anaconda-mode)
(turn-off-anaconda-mode)))
(defun turn-on-anaconda-mode ()
"Turn on `anaconda-mode'."
(make-local-variable 'eldoc-documentation-function)
(setq-local eldoc-documentation-function 'anaconda-mode-eldoc-function))
(defun turn-off-anaconda-mode ()
"Turn off `anaconda-mode'."
(kill-local-variable 'eldoc-documentation-function))
(provide 'anaconda-mode)
;;; anaconda-mode.el ends here
| true | ;;; anaconda-mode.el --- Code navigation, documentation lookup and completion for Python -*- lexical-binding: t; -*-
;; Copyright (C) 2013-2015 by PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/proofit404/anaconda-mode
;; Package-Version: 20150922.537
;; Version: 0.1.1
;; Package-Requires: ((emacs "24") (pythonic "0.1.0") (dash "2.6.0") (s "1.9") (f "0.16.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README for more details.
;;; Code:
(eval-when-compile
(defvar url-http-end-of-headers))
(require 'tramp)
(require 'url)
(require 'json)
(require 'pythonic)
(require 'dash)
(require 's)
(require 'f)
(defgroup anaconda-mode nil
"Code navigation, documentation lookup and completion for Python."
:group 'programming)
(defcustom anaconda-mode-installation-directory
"~/.emacs.d/anaconda-mode"
"Installation directory for anaconda-mode server."
:group 'anaconda-mode
:type 'directory)
(defcustom anaconda-mode-complete-callback
'anaconda-mode-complete-callback
"Callback function used to display `anaconda-mode-complete' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-show-doc-callback
'anaconda-mode-show-doc-callback
"Callback function used to display `anaconda-mode-show-doc' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-definitions-callback
'anaconda-mode-find-definitions-callback
"Callback function used to display `anaconda-mode-find-definitions' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-assignments-callback
'anaconda-mode-find-assignments-callback
"Callback function used to display `anaconda-mode-find-assignments' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-find-references-callback
'anaconda-mode-find-references-callback
"Callback function used to display `anaconda-mode-find-references' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-callback
'anaconda-mode-eldoc-callback
"Callback function used to display `anaconda-mode-eldoc-function' result."
:group 'anaconda-mode
:type 'function)
(defcustom anaconda-mode-eldoc-as-single-line nil
"If not nil, trim eldoc string to frame width."
:group 'anaconda-mode
:type 'boolean)
;;; Server.
(defvar anaconda-mode-server-version "0.1.1"
"Server version needed to run anaconda-mode.")
(defvar anaconda-mode-server-script "anaconda_mode.py"
"Script file with anaconda-mode server.")
(defvar anaconda-mode-process-name "anaconda-mode"
"Process name for anaconda-mode processes.")
(defvar anaconda-mode-process-buffer "*anaconda-mode*"
"Buffer name for anaconda-mode processes.")
(defvar anaconda-mode-process nil
"Currently running anaconda-mode process.")
(defvar anaconda-mode-port nil
"Port for anaconda-mode connection.")
(defvar anaconda-mode-ensure-directory-command "
import os
import sys
directory = sys.argv[-1]
if not os.path.exists(directory):
os.makedirs(directory)
" "Create `anaconda-mode-server-directory' if necessary.")
(defvar anaconda-mode-check-installation-command "
import sys, os
from pkg_resources import find_distributions
directory = sys.argv[-1]
for dist in find_distributions(directory, only=True):
if dist.project_name == 'anaconda-mode':
break
else:
# IPython patch sys.exit, so we can't use it.
os._exit(1)
" "Check if `anaconda-mode' server is installed or not.")
(defvar anaconda-mode-install-server-command "
import sys
import pip
directory = sys.argv[-2]
version = sys.argv[-1]
pip.main(['install', '-t', directory, 'anaconda_mode==' + version])
" "Install `anaconda_mode' server.")
(defun anaconda-mode-server-directory ()
"Anaconda mode installation directory."
(f-join anaconda-mode-installation-directory anaconda-mode-server-version))
(defun anaconda-mode-host ()
"Target host with anaconda-mode server."
(if (pythonic-remote-p)
(tramp-file-name-host
(tramp-dissect-file-name
(pythonic-tramp-connection)))
"127.0.0.1"))
(defun anaconda-mode-start (&optional callback)
"Start anaconda-mode server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(when (anaconda-mode-need-restart)
(anaconda-mode-stop))
(if (anaconda-mode-running-p)
(when callback
(funcall callback))
(anaconda-mode-ensure-directory callback)))
(defun anaconda-mode-stop ()
"Stop anaconda-mode server."
(when (anaconda-mode-running-p)
(set-process-filter anaconda-mode-process nil)
(set-process-sentinel anaconda-mode-process nil)
(kill-process anaconda-mode-process)
(setq anaconda-mode-process nil
anaconda-mode-port nil)))
(defun anaconda-mode-running-p ()
"Is `anaconda-mode' server running."
(and anaconda-mode-process
(process-live-p anaconda-mode-process)))
(defun anaconda-mode-bound-p ()
"Is `anaconda-mode' port bound."
(numberp anaconda-mode-port))
(defun anaconda-mode-need-restart ()
"Check if we need to restart `anaconda-mode-server'."
(when (and (anaconda-mode-running-p)
(anaconda-mode-bound-p))
(or (not (pythonic-proper-environment-p anaconda-mode-process))
(not (equal (process-get anaconda-mode-process 'server-directory)
(anaconda-mode-server-directory))))))
(defun anaconda-mode-ensure-directory (&optional callback)
"Ensure if `anaconda-mode-server-directory' exists.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-ensure-directory-sentinel process event callback))
:args (list "-c"
anaconda-mode-ensure-directory-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-ensure-directory-sentinel (process _event &optional callback)
"Run `anaconda-mode-check' if `anaconda-mode-server-directory' exists.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-check callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't create %s directory"
(anaconda-mode-server-directory))))
(defun anaconda-mode-check (&optional callback)
"Check `anaconda-mode' server installation.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-check-sentinel process event callback))
:args (list "-c"
anaconda-mode-check-installation-command
(anaconda-mode-server-directory)))))
(defun anaconda-mode-check-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation check passed.
Try to install `anaconda-mode' server otherwise. PROCESS and
EVENT are basic sentinel parameters. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(anaconda-mode-install callback)))
(defun anaconda-mode-install (&optional callback)
"Try to install `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:sentinel (lambda (process event) (anaconda-mode-install-sentinel process event callback))
:args (list "-c"
anaconda-mode-install-server-command
(anaconda-mode-server-directory)
anaconda-mode-server-version))))
(defun anaconda-mode-install-sentinel (process _event &optional callback)
"Run `anaconda-mode-bootstrap' if server installation complete successfully.
Raise error otherwise. PROCESS and EVENT are basic sentinel
parameters. CALLBACK function will be called when
`anaconda-mode-port' will be bound."
(if (eq 0 (process-exit-status process))
(anaconda-mode-bootstrap callback)
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't install `anaconda-mode' server")))
(defun anaconda-mode-bootstrap (&optional callback)
"Run `anaconda-mode' server.
CALLBACK function will be called when `anaconda-mode-port' will
be bound."
(setq anaconda-mode-process
(start-pythonic :process anaconda-mode-process-name
:buffer anaconda-mode-process-buffer
:cwd (anaconda-mode-server-directory)
:filter (lambda (process output) (anaconda-mode-bootstrap-filter process output callback))
:sentinel 'anaconda-mode-bootstrap-sentinel
:query-on-exit nil
:args (list anaconda-mode-server-script)))
(process-put anaconda-mode-process 'server-directory (anaconda-mode-server-directory)))
(defun anaconda-mode-bootstrap-filter (process output &optional callback)
"Set `anaconda-mode-port' from PROCESS OUTPUT.
Connect to the `anaconda-mode' server. CALLBACK function will be
called when `anaconda-mode-port' will be bound."
;; Mimic default filter.
(when (buffer-live-p (process-buffer process))
(with-current-buffer (process-buffer process)
(save-excursion
(goto-char (process-mark process))
(insert output)
(set-marker (process-mark process) (point)))))
(--when-let (s-match "anaconda_mode port \\([0-9]+\\)" output)
(setq anaconda-mode-port (string-to-number (cadr it)))
(set-process-filter process nil)
(when callback
(funcall callback))))
(defun anaconda-mode-bootstrap-sentinel (process _event)
"Raise error if `anaconda-mode' server exit abnormally.
PROCESS and EVENT are basic sentinel parameters."
(unless (eq 0 (process-exit-status process))
(pop-to-buffer anaconda-mode-process-buffer)
(error "Can't start `anaconda-mode' server")))
;;; Interaction.
(defun anaconda-mode-call (command callback)
"Make remote procedure call for COMMAND.
Apply CALLBACK to it result."
(anaconda-mode-start
(lambda () (anaconda-mode-jsonrpc command callback))))
(defun anaconda-mode-jsonrpc (command callback)
"Perform JSONRPC call for COMMAND.
Apply CALLBACK to the call result when retrieve it. Remote
COMMAND must expect four arguments: python buffer content, line
number position, column number position and file path."
(let ((url-request-method "POST")
(url-request-data (anaconda-mode-jsonrpc-request command)))
(url-retrieve
(format "http://%s:%s" (anaconda-mode-host) anaconda-mode-port)
(anaconda-mode-create-response-handler command callback)
nil
t)))
(defun anaconda-mode-jsonrpc-request (command)
"Prepare JSON encoded buffer data for COMMAND call."
(json-encode (anaconda-mode-jsonrpc-request-data command)))
(defun anaconda-mode-jsonrpc-request-data (command)
"Prepare buffer data for COMMAND call."
`((jsonrpc . "2.0")
(id . 1)
(method . ,command)
(params . ((source . ,(buffer-substring-no-properties (point-min) (point-max)))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))
(path . ,(when (buffer-file-name)
(pythonic-file-name (buffer-file-name))))))))
(defun anaconda-mode-create-response-handler (command callback)
"Create server response handler based on COMMAND and CALLBACK function.
COMMAND argument will be used for response skip message.
Response can be skipped if point was moved sense request was
submitted."
(let ((anaconda-mode-request-point (point))
(anaconda-mode-request-buffer (current-buffer))
(anaconda-mode-request-window (selected-window))
(anaconda-mode-request-tick (buffer-chars-modified-tick)))
(lambda (_status)
(let ((http-buffer (current-buffer)))
(unwind-protect
(if (or (not (equal anaconda-mode-request-window (selected-window)))
(with-current-buffer (window-buffer anaconda-mode-request-window)
(or (not (equal anaconda-mode-request-buffer (current-buffer)))
(not (equal anaconda-mode-request-point (point)))
(not (equal anaconda-mode-request-tick (buffer-chars-modified-tick))))))
(message "Skip anaconda-mode %s response" command)
(goto-char url-http-end-of-headers)
(let* ((json-array-type 'list)
(response (condition-case nil
(json-read)
(json-readtable-error
(progn
(let ((response-string (buffer-string)))
(pop-to-buffer
(with-current-buffer (get-buffer-create "*anaconda-response*")
(insert response-string)
(goto-char (point-min))
(current-buffer))))
(error "Can't read anaconda-mode server response"))))))
(if (assoc 'error response)
(error (cdr (assoc 'error response)))
(with-current-buffer anaconda-mode-request-buffer
;; Terminate `apply' call with empty list so response
;; will be treated as single argument.
(apply callback (cdr (assoc 'result response)) nil)))))
(kill-buffer http-buffer))))))
;;; Code completion.
(defun anaconda-mode-complete ()
"Request completion candidates."
(interactive)
(unless (python-syntax-comment-or-string-p)
(anaconda-mode-call "complete" anaconda-mode-complete-callback)))
(defun anaconda-mode-complete-callback (result)
"Start interactive completion on RESULT receiving."
(let* ((bounds (bounds-of-thing-at-point 'symbol))
(start (or (car bounds) (point)))
(stop (or (cdr bounds) (point)))
(collection (anaconda-mode-complete-extract-names result))
(completion-extra-properties '(:annotation-function anaconda-mode-complete-annotation)))
(completion-in-region start stop collection)))
(defun anaconda-mode-complete-extract-names (result)
"Extract completion names from anaconda-mode RESULT."
(--map (let* ((name (cdr (assoc 'name it)))
(type (cdr (assoc 'type it)))
(module-path (cdr (assoc 'module-path it)))
(line (cdr (assoc 'line it)))
(docstring (cdr (assoc 'docstring it)))
(description (if (equal type "statement")
"statement"
(cdr (assoc 'description it)))))
(put-text-property 0 1 'description description name)
(put-text-property 0 1 'module-path module-path name)
(put-text-property 0 1 'line line name)
(put-text-property 0 1 'docstring docstring name)
name)
result))
(defun anaconda-mode-complete-annotation (candidate)
"Get annotation for CANDIDATE."
(--when-let (get-text-property 0 'description candidate)
(concat " <" it ">")))
;;; View documentation.
(defun anaconda-mode-show-doc ()
"Show documentation for context at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-show-doc-callback))
(defun anaconda-mode-show-doc-callback (result)
"Process view doc RESULT."
(if result
(anaconda-mode-documentation-view result)
(message "No documentation available")))
;;; Find definitions.
(defun anaconda-mode-find-definitions ()
"Find definitions for thing at point."
(interactive)
(anaconda-mode-call "goto_definitions" anaconda-mode-find-definitions-callback))
(defun anaconda-mode-find-definitions-callback (result)
"Process find definitions RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No definitions found")))
;;; Find assignments.
(defun anaconda-mode-find-assignments ()
"Find assignments for thing at point."
(interactive)
(anaconda-mode-call "goto_assignments" anaconda-mode-find-assignments-callback))
(defun anaconda-mode-find-assignments-callback (result)
"Process find assignments RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No assignments found")))
;;; Find references.
(defun anaconda-mode-find-references ()
"Find references for thing at point."
(interactive)
(anaconda-mode-call "usages" anaconda-mode-find-references-callback))
(defun anaconda-mode-find-references-callback (result)
"Process find references RESULT."
(if result
(anaconda-mode-definitions-view result)
(message "No references found")))
;;; Eldoc.
(defun anaconda-mode-eldoc-function ()
"Show eldoc for context at point."
(anaconda-mode-call "eldoc" anaconda-mode-eldoc-callback))
(defun anaconda-mode-eldoc-callback (result)
"Display eldoc from server RESULT."
(eldoc-message (anaconda-mode-eldoc-format result)))
(defun anaconda-mode-eldoc-format (result)
"Format eldoc string from RESULT."
(when result
(let* ((name (cdr (assoc 'name result)))
(index (or (cdr (assoc 'index result)) 0))
(params (cdr (assoc 'params result)))
(doc (anaconda-mode-eldoc-format-definition name index params)))
(if anaconda-mode-eldoc-as-single-line
(substring doc 0 (min (frame-width) (length doc)))
doc))))
(defun anaconda-mode-eldoc-format-definition (name index params)
"Format function definition from NAME, INDEX and PARAMS."
(concat
(propertize name 'face 'font-lock-function-name-face)
"("
(anaconda-mode-eldoc-format-params params index)
")"))
(defun anaconda-mode-eldoc-format-params (args index)
"Build colorized ARGS string with current arg pointed to INDEX."
(->>
args
(--map-indexed
(if (= index it-index)
(propertize it 'face 'eldoc-highlight-function-argument)
it))
(-interpose ", ")
(apply 'concat)))
;;; Result view.
(defmacro anaconda-mode-with-view-buffer (&rest body)
"Create view buffer and execute BODY in it."
`(let ((buf (get-buffer-create "*Anaconda*")))
(with-current-buffer buf
(setq buffer-read-only nil)
(erase-buffer)
,@body
(goto-char (point-min))
(anaconda-mode-view-mode)
buf)))
(defun anaconda-mode-definitions-view (result)
"Show definitions view for rpc RESULT."
(if (eq 1 (length result))
(anaconda-mode-find-file (car result))
(anaconda-mode-view result 'anaconda-mode-view-definitions-presenter)))
(defun anaconda-mode-documentation-view (result)
"Show documentation view for rpc RESULT."
(anaconda-mode-view result 'anaconda-mode-view-documentation-presenter))
(defun anaconda-mode-view (result presenter)
"Show RESULT to user for future selection.
RESULT must be an RESULT field from json-rpc response.
PRESENTER is the function used to format buffer content."
(pop-to-buffer
(anaconda-mode-with-view-buffer
(funcall presenter result))))
(defun anaconda-mode-view-make-bold (string)
"Make passed STRING look bold."
(propertize string 'face 'bold))
(defun anaconda-mode-view-make-source (string)
"Make passed STRING look like python source."
(with-temp-buffer
(insert string)
(let ((delay-mode-hooks t))
(python-mode))
(run-hooks 'font-lock-mode-hook)
(font-lock-fontify-buffer)
(buffer-string)))
(define-button-type 'anaconda-mode-definition-button
'action #'anaconda-mode-view-jump
'face nil)
(defun anaconda-mode-view-jump (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file definition)))
(defun anaconda-mode-view-jump-other-window (button)
"Jump to definition file saved in BUTTON."
(let ((definition (button-get button 'definition)))
(anaconda-mode-find-file-other-window definition)))
(defun anaconda-mode-find-file (definition)
"Find DEFINITION file, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file))
(defun anaconda-mode-find-file-other-window (definition)
"Find DEFINITION file other window, go to DEFINITION point."
(anaconda-mode-find-file-generic definition 'find-file-other-window))
(defvar-local anaconda-mode-go-back-definition nil
"Previous definition from which current buffer was navigated.")
(defun anaconda-mode-find-file-generic (definition find-function)
"Find DEFINITION with FIND-FUNCTION."
(let ((backward-navigation (when (buffer-file-name)
`((module-path . ,(buffer-file-name))
(line . ,(line-number-at-pos (point)))
(column . ,(- (point) (line-beginning-position)))))))
(--if-let (cdr (assoc 'module-path definition))
(progn
(funcall find-function it)
(goto-char 0)
(forward-line (1- (cdr (assoc 'line definition))))
(forward-char (cdr (assoc 'column definition)))
(setq anaconda-mode-go-back-definition backward-navigation))
(message "Can't open %s module" (cdr (assoc 'module-name definition))))))
(defun anaconda-mode-view-insert-button (name definition)
"Insert text button with NAME opening the DEFINITION."
(insert-text-button name
'type 'anaconda-mode-definition-button
'definition definition))
(defun anaconda-mode-view-definitions-presenter (result)
"Insert definitions from RESULT."
(->>
(--group-by (cdr (assoc 'module-name it)) result)
(--map (anaconda-mode-view-insert-module-definition it))))
(defun anaconda-mode-view-insert-module-definition (module)
"Insert MODULE definition into current buffer."
(insert (concat (anaconda-mode-view-make-bold (car module)) "\n"))
(--map
(progn
(insert " ")
(anaconda-mode-view-insert-button
(anaconda-mode-view-make-source (cdr (assoc 'description it)))
it)
(insert "\n"))
(cdr module)))
(defun anaconda-mode-view-documentation-presenter (result)
"Insert documentation from RESULT."
(--map
(progn
(insert (anaconda-mode-view-make-bold (cdr (assoc 'module-name it))))
(insert "\n")
(insert (s-trim-right (cdr (assoc 'docstring it))))
(insert "\n\n"))
result))
(defvar anaconda-mode-view-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "n") 'next-error-no-select)
(define-key map (kbd "p") 'previous-error-no-select)
(define-key map (kbd "q") 'quit-window)
map))
(define-derived-mode anaconda-mode-view-mode special-mode "Anaconda-View"
"Major mode for definitions view and navigation for `anaconda-mode'.
\\{anaconda-mode-view-mode-map}"
(setq next-error-function #'anaconda-mode-next-definition))
(defun anaconda-mode-next-definition (num _reset)
"Navigate tot the next definition in the view buffer.
NUM is the number of definitions to move forward. RESET mean go
to the beginning of buffer before definitions navigation."
(forward-button num)
(anaconda-mode-view-jump-other-window (button-at (point))))
(defun anaconda-mode-go-back ()
"Jump backward if buffer was navigated from `anaconda-mode' command."
(interactive)
(if anaconda-mode-go-back-definition
(anaconda-mode-find-file anaconda-mode-go-back-definition)
(error "No previous buffer")))
;;; Anaconda minor mode.
(defvar anaconda-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-M-i") 'anaconda-mode-complete)
(define-key map (kbd "M-.") 'anaconda-mode-find-definitions)
(define-key map (kbd "M-,") 'anaconda-mode-find-assignments)
(define-key map (kbd "M-r") 'anaconda-mode-find-references)
(define-key map (kbd "M-*") 'anaconda-mode-go-back)
(define-key map (kbd "M-?") 'anaconda-mode-show-doc)
map)
"Keymap for `anaconda-mode'.")
;;;###autoload
(define-minor-mode anaconda-mode
"Code navigation, documentation lookup and completion for Python.
\\{anaconda-mode-map}"
:lighter " Anaconda"
:keymap anaconda-mode-map
(if anaconda-mode
(turn-on-anaconda-mode)
(turn-off-anaconda-mode)))
(defun turn-on-anaconda-mode ()
"Turn on `anaconda-mode'."
(make-local-variable 'eldoc-documentation-function)
(setq-local eldoc-documentation-function 'anaconda-mode-eldoc-function))
(defun turn-off-anaconda-mode ()
"Turn off `anaconda-mode'."
(kill-local-variable 'eldoc-documentation-function))
(provide 'anaconda-mode)
;;; anaconda-mode.el ends here
|
[
{
"context": "ub.com/Groovy-Emacs-Modes/groovy-emacs-modes\n;;\n;; Paolo de Dios <paolodedios@gmail.com>\n;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 130,
"score": 0.999899685382843,
"start": 117,
"tag": "NAME",
"value": "Paolo de Dios"
},
{
"context": "acs-Modes/groovy-emacs-modes\n;;\n;; Paolo de Dios <paolodedios@gmail.com>\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 153,
"score": 0.9999245405197144,
"start": 132,
"tag": "EMAIL",
"value": "paolodedios@gmail.com"
}
] | .emacs.d/modules/config-groovy-mode.el | paolodedios/dot-files | 0 | ;; -*- mode: emacs-lisp -*-
;;
;; Groovy mode
;; @see https://github.com/Groovy-Emacs-Modes/groovy-emacs-modes
;;
;; Paolo de Dios <paolodedios@gmail.com>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'groovy-electric)
(autoload 'groovy-mode "groovy-mode" "Groovy Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Groovy hook section, called on entry of Groovy mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook
'(lambda ()
(groovy-electric-mode 1)
(c-add-style "sourcery" my-java-mode-programming-style t)
(c-set-style "sourcery" )
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.groovy$" . groovy-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.gradle$" . groovy-mode )) auto-mode-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreter binding
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq interpreter-mode-alist (append '(("groovy" . groovy-mode )) interpreter-mode-alist))
(setq interpreter-mode-alist (append '(("gradle" . groovy-mode )) interpreter-mode-alist))
| 3748 | ;; -*- mode: emacs-lisp -*-
;;
;; Groovy mode
;; @see https://github.com/Groovy-Emacs-Modes/groovy-emacs-modes
;;
;; <NAME> <<EMAIL>>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'groovy-electric)
(autoload 'groovy-mode "groovy-mode" "Groovy Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Groovy hook section, called on entry of Groovy mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook
'(lambda ()
(groovy-electric-mode 1)
(c-add-style "sourcery" my-java-mode-programming-style t)
(c-set-style "sourcery" )
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.groovy$" . groovy-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.gradle$" . groovy-mode )) auto-mode-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreter binding
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq interpreter-mode-alist (append '(("groovy" . groovy-mode )) interpreter-mode-alist))
(setq interpreter-mode-alist (append '(("gradle" . groovy-mode )) interpreter-mode-alist))
| true | ;; -*- mode: emacs-lisp -*-
;;
;; Groovy mode
;; @see https://github.com/Groovy-Emacs-Modes/groovy-emacs-modes
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'groovy-electric)
(autoload 'groovy-mode "groovy-mode" "Groovy Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Groovy hook section, called on entry of Groovy mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook
'(lambda ()
(groovy-electric-mode 1)
(c-add-style "sourcery" my-java-mode-programming-style t)
(c-set-style "sourcery" )
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'groovy-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.groovy$" . groovy-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.gradle$" . groovy-mode )) auto-mode-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interpreter binding
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq interpreter-mode-alist (append '(("groovy" . groovy-mode )) interpreter-mode-alist))
(setq interpreter-mode-alist (append '(("gradle" . groovy-mode )) interpreter-mode-alist))
|
[
{
"context": "figuration for es-mode\n;;; Commentary:\n;;; Author: Vedang Manerikar\n;;; Created on: 9 Jul 2016\n;;; Copyright (c) 2016",
"end": 94,
"score": 0.9998958110809326,
"start": 78,
"tag": "NAME",
"value": "Vedang Manerikar"
},
{
"context": "\n;;; Created on: 9 Jul 2016\n;;; Copyright (c) 2016 Vedang Manerikar <vedang.manerikar@gmail.com>\n\n;; This file is not",
"end": 161,
"score": 0.9998972415924072,
"start": 145,
"tag": "NAME",
"value": "Vedang Manerikar"
},
{
"context": "Jul 2016\n;;; Copyright (c) 2016 Vedang Manerikar <vedang.manerikar@gmail.com>\n\n;; This file is not part of GNU Emacs.\n\n;;; Lic",
"end": 189,
"score": 0.9999362230300903,
"start": 163,
"tag": "EMAIL",
"value": "vedang.manerikar@gmail.com"
}
] | el-get-init-files/init-es-mode.el | vedang/emacs-up | 13 | ;;; init-es-mode.el --- Configuration for es-mode
;;; Commentary:
;;; Author: Vedang Manerikar
;;; Created on: 9 Jul 2016
;;; Copyright (c) 2016 Vedang Manerikar <vedang.manerikar@gmail.com>
;; This file is not part of GNU Emacs.
;;; License:
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the Do What The Fuck You Want to
;; Public License, Version 2, which is included with this distribution.
;; See the file LICENSE.txt
;;; Code:
(add-to-list 'auto-mode-alist '("\\.es$" . es-mode))
(setq es-always-pretty-print t)
(eval-after-load 'es-cc
'(progn (setq es-cc-endpoint "http://shiva.local:9202")))
(provide 'init-es-mode)
;;; init-es-mode.el ends here
| 23230 | ;;; init-es-mode.el --- Configuration for es-mode
;;; Commentary:
;;; Author: <NAME>
;;; Created on: 9 Jul 2016
;;; Copyright (c) 2016 <NAME> <<EMAIL>>
;; This file is not part of GNU Emacs.
;;; License:
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the Do What The Fuck You Want to
;; Public License, Version 2, which is included with this distribution.
;; See the file LICENSE.txt
;;; Code:
(add-to-list 'auto-mode-alist '("\\.es$" . es-mode))
(setq es-always-pretty-print t)
(eval-after-load 'es-cc
'(progn (setq es-cc-endpoint "http://shiva.local:9202")))
(provide 'init-es-mode)
;;; init-es-mode.el ends here
| true | ;;; init-es-mode.el --- Configuration for es-mode
;;; Commentary:
;;; Author: PI:NAME:<NAME>END_PI
;;; Created on: 9 Jul 2016
;;; Copyright (c) 2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; This file is not part of GNU Emacs.
;;; License:
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the Do What The Fuck You Want to
;; Public License, Version 2, which is included with this distribution.
;; See the file LICENSE.txt
;;; Code:
(add-to-list 'auto-mode-alist '("\\.es$" . es-mode))
(setq es-always-pretty-print t)
(eval-after-load 'es-cc
'(progn (setq es-cc-endpoint "http://shiva.local:9202")))
(provide 'init-es-mode)
;;; init-es-mode.el ends here
|
[
{
"context": "97,1998 Free Software Foundation, Inc.\n\n;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>\n;; Keywords: invisible, tex",
"end": 161,
"score": 0.9998050928115845,
"start": 145,
"tag": "NAME",
"value": "MORIOKA Tomohiko"
},
{
"context": "re Foundation, Inc.\n\n;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>\n;; Keywords: invisible, text-property, region, E",
"end": 182,
"score": 0.9999324083328247,
"start": 163,
"tag": "EMAIL",
"value": "morioka@jaist.ac.jp"
}
] | .emacs.d/lib/apel-10.8/inv-18.el | thayamizu/dotfiles | 0 | ;;; inv-18.el --- invisible feature implementation for Emacs 18
;; Copyright (C) 1995,1996,1997,1998 Free Software Foundation, Inc.
;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>
;; Keywords: invisible, text-property, region, Emacs 18
;; This file is part of APEL (A Portable Emacs Library).
;; 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 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.
;;; Code:
(require 'poe)
(defun enable-invisible ()
(make-local-variable 'original-selective-display)
(setq original-selective-display selective-display)
(setq selective-display t))
(defun disable-invisible ()
(setq selective-display
(and (boundp 'original-selective-display)
original-selective-display)))
(defalias 'end-of-invisible 'disable-invisible)
(make-obsolete 'end-of-invisible 'disable-invisible)
(defun invisible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(if (save-excursion
(goto-char (1- end))
(eq (following-char) ?\n))
(setq end (1- end)))
(unwind-protect
(subst-char-in-region start end ?\n ?\r t)
(set-buffer-modified-p modp))))
(defun visible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(unwind-protect
(subst-char-in-region start end ?\r ?\n t)
(set-buffer-modified-p modp))))
(defun invisible-p (pos)
(save-excursion
(goto-char pos)
(eq (following-char) ?\r)))
(defun next-visible-point (pos)
(save-excursion
(goto-char pos)
(end-of-line)
(if (eq (following-char) ?\n)
(forward-char))
(point)))
;;; @ end
;;;
(require 'product)
(product-provide (provide 'inv-18) (require 'apel-ver))
;;; inv-18.el ends here
| 46007 | ;;; inv-18.el --- invisible feature implementation for Emacs 18
;; Copyright (C) 1995,1996,1997,1998 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; Keywords: invisible, text-property, region, Emacs 18
;; This file is part of APEL (A Portable Emacs Library).
;; 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 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.
;;; Code:
(require 'poe)
(defun enable-invisible ()
(make-local-variable 'original-selective-display)
(setq original-selective-display selective-display)
(setq selective-display t))
(defun disable-invisible ()
(setq selective-display
(and (boundp 'original-selective-display)
original-selective-display)))
(defalias 'end-of-invisible 'disable-invisible)
(make-obsolete 'end-of-invisible 'disable-invisible)
(defun invisible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(if (save-excursion
(goto-char (1- end))
(eq (following-char) ?\n))
(setq end (1- end)))
(unwind-protect
(subst-char-in-region start end ?\n ?\r t)
(set-buffer-modified-p modp))))
(defun visible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(unwind-protect
(subst-char-in-region start end ?\r ?\n t)
(set-buffer-modified-p modp))))
(defun invisible-p (pos)
(save-excursion
(goto-char pos)
(eq (following-char) ?\r)))
(defun next-visible-point (pos)
(save-excursion
(goto-char pos)
(end-of-line)
(if (eq (following-char) ?\n)
(forward-char))
(point)))
;;; @ end
;;;
(require 'product)
(product-provide (provide 'inv-18) (require 'apel-ver))
;;; inv-18.el ends here
| true | ;;; inv-18.el --- invisible feature implementation for Emacs 18
;; Copyright (C) 1995,1996,1997,1998 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: invisible, text-property, region, Emacs 18
;; This file is part of APEL (A Portable Emacs Library).
;; 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 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.
;;; Code:
(require 'poe)
(defun enable-invisible ()
(make-local-variable 'original-selective-display)
(setq original-selective-display selective-display)
(setq selective-display t))
(defun disable-invisible ()
(setq selective-display
(and (boundp 'original-selective-display)
original-selective-display)))
(defalias 'end-of-invisible 'disable-invisible)
(make-obsolete 'end-of-invisible 'disable-invisible)
(defun invisible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(if (save-excursion
(goto-char (1- end))
(eq (following-char) ?\n))
(setq end (1- end)))
(unwind-protect
(subst-char-in-region start end ?\n ?\r t)
(set-buffer-modified-p modp))))
(defun visible-region (start end)
(let ((buffer-read-only nil)
(modp (buffer-modified-p)))
(unwind-protect
(subst-char-in-region start end ?\r ?\n t)
(set-buffer-modified-p modp))))
(defun invisible-p (pos)
(save-excursion
(goto-char pos)
(eq (following-char) ?\r)))
(defun next-visible-point (pos)
(save-excursion
(goto-char pos)
(end-of-line)
(if (eq (following-char) ?\n)
(forward-char))
(point)))
;;; @ end
;;;
(require 'product)
(product-provide (provide 'inv-18) (require 'apel-ver))
;;; inv-18.el ends here
|
[
{
"context": "5--2021 Free Software Foundation, Inc.\n\n;; Author: Arash Esbati <arash@gnu.org>\n;; Maintainer: auctex-devel@gnu.o",
"end": 172,
"score": 0.9998809099197388,
"start": 160,
"tag": "NAME",
"value": "Arash Esbati"
},
{
"context": "ftware Foundation, Inc.\n\n;; Author: Arash Esbati <arash@gnu.org>\n;; Maintainer: auctex-devel@gnu.org\n;; Created: ",
"end": 187,
"score": 0.9999334216117859,
"start": 174,
"tag": "EMAIL",
"value": "arash@gnu.org"
},
{
"context": "uthor: Arash Esbati <arash@gnu.org>\n;; Maintainer: auctex-devel@gnu.org\n;; Created: 2014-10-20\n;; Keywords: tex\n\n;; This ",
"end": 224,
"score": 0.9999287128448486,
"start": 204,
"tag": "EMAIL",
"value": "auctex-devel@gnu.org"
},
{
"context": "eX-enumitem-SetLabelAlign-list)\n (let* ((key \"align\")\n (vals (mapcar #'car (LaTeX-enumitem",
"end": 6166,
"score": 0.8160274028778076,
"start": 6161,
"tag": "KEY",
"value": "align"
}
] | elpa/auctex-13.1.1/style/enumitem.el | timmli/emacs-settings | 0 | ;;; enumitem.el --- AUCTeX style for `enumitem.sty' (v3.9) -*- lexical-binding: t; -*-
;; Copyright (C) 2015--2021 Free Software Foundation, Inc.
;; Author: Arash Esbati <arash@gnu.org>
;; Maintainer: auctex-devel@gnu.org
;; Created: 2014-10-20
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for `enumitem.sty' (v3.9) from 2019/06/20.
;; `enumitem.sty' is part of TeXLive.
;; Tassilo Horn's `minted.el' was a major source of inspiration for
;; this style, many thanks to him (also for patiently answering my
;; many other questions, incl. the stupid ones.)
;; If things do not work or when in doubt, press `C-c C-n'. Comments
;; for improvement are welcome.
;;; Code:
(require 'tex)
(require 'latex)
(eval-when-compile
(require 'cl-lib))
;; Silence the compiler:
(declare-function font-latex-add-keywords
"font-latex"
(keywords class))
(defvar LaTeX-enumitem-key-val-options
`(;; 3.1 Label and cross references format
("label" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("label*" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("ref" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("font" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("format" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("align" ("left" "right" "parleft"))
;; 3.2 Horizontal spacing of labels
("labelindent" ("*" "!"))
("left")
("leftmargin" ("*" "!"))
("itemindent" ("*" "!"))
("labelsep" ("*" "!"))
("labelwidth" ("*" "!"))
("widest")
("widest*")
("labelsep*")
("labelindent*")
("rightmargin")
;; Vertical Spacing
("topsep")
("partopsep")
("parsep")
("itemsep")
;; 3.3 Numbering, stopping, and resuming
("start")
("resume")
("resume*")
;; 3.4 Series
("series")
;; 3.5 Penalties
("beginpenalty")
("midpenalty")
("endpenalty")
;; 3.6 Injecting code
("before")
("before*")
("after")
("after*")
("first")
("first*")
;; 3.7 Description styles
("style" ("standard" "unboxed" "nextline" "sameline" "multiline"))
;; 3.8 Compact lists
("noitemsep")
("nosep")
;; 3.9 Wide lists
("wide")
;; 4 Inline lists
("itemjoin")
("itemjoin*")
("afterlabel")
("mode" ("boxed" "unboxed")))
"Key=value options for enumitem macros and environments.")
(defun LaTeX-enumitem-key-val-options ()
"Return an updated list of key=vals from enumitem package."
(append
;; New keys are valueless, so take them as is:
(when (LaTeX-enumitem-SetEnumitemKey-list)
(LaTeX-enumitem-SetEnumitemKey-list))
;; New values defined available keys: We have to collect predefined
;; values (if any) from `LaTeX-enumitem-key-val-options' (stored in
;; `vals-predefined') and user-defined values (stored in
;; `vals-parsed') which were parsed and added to `result' in the
;; previous run of `dolist' and then combine them as value to a
;; key.
(when (LaTeX-enumitem-SetEnumitemValue-list)
(let (result)
(dolist (keyvals (LaTeX-enumitem-SetEnumitemValue-list) result)
(let* ((key (nth 1 keyvals))
(val (nth 2 keyvals))
(vals-predefined
(cadr (assoc key LaTeX-enumitem-key-val-options)))
(vals-parsed (cadr (assoc key result))))
;; Remove entry in `result' if there is one for the `key':
(when (assoc key result)
(setq result (assq-delete-all (car (assoc key result))
result)))
;; Add the entry to `result'; also remove any duplicates
(cl-pushnew (list key (TeX-delete-duplicate-strings
(append vals-parsed
vals-predefined
(list val))))
result :test #'equal)))))
;; New values to `align' key: We collect the predefined ones from
;; `LaTeX-enumitem-key-val-options' in `vals-predefined' and
;; prepend them to newly parsed ones:
(when (LaTeX-enumitem-SetLabelAlign-list)
(let* ((key "align")
(vals (mapcar #'car (LaTeX-enumitem-SetLabelAlign-list)))
(vals-predefined (cadr
(assoc key LaTeX-enumitem-key-val-options))))
`(("align" ,(TeX-delete-duplicate-strings
(append vals-predefined vals))))))
;; Predefined key=vals:
LaTeX-enumitem-key-val-options))
;; Setup for \newlist:
(TeX-auto-add-type "enumitem-newlist" "LaTeX")
(defvar LaTeX-enumitem-newlist-regexp
'("\\\\newlist{\\([^}]+\\)}{\\([^}]+\\)}"
(1 2) LaTeX-auto-enumitem-newlist)
"Matches the arguments of `\\newlist' from `enumitem' package.")
;; Setup for \SetLabelAlign:
(TeX-auto-add-type "enumitem-SetLabelAlign" "LaTeX")
(defvar LaTeX-enumitem-SetLabelAlign-regexp
'("\\\\SetLabelAlign{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetLabelAlign)
"Matches the argument of `\\SetLabelAlign' from `enumitem' package.")
;; Setup for \SetEnumitemKey:
(TeX-auto-add-type "enumitem-SetEnumitemKey" "LaTeX")
(defvar LaTeX-enumitem-SetEnumitemKey-regexp
'("\\\\SetEnumitemKey{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetEnumitemKey)
"Matches the arguments of `\\SetEnumitemKey' from `enumitem' package.")
;; Setup for \SetEnumitemValue:
(TeX-auto-add-type "enumitem-SetEnumitemValue" "LaTeX")
;; Upon Tassilo's recommendation, we include also `0' so that we can
;; use the function `LaTeX-enumitem-SetEnumitemValue-list' while we
;; make sure that `TeX-auto-list-information' doesn't remove multiple
;; defined values to a specific key. For this reason, we also ignore
;; the 3. argument to the `\SetEnumitemValue' macro (i.e., a third
;; {\\([^}]+\\)} in regex) so that we don't pollute the generated
;; `docname.el' with unnecessary (La)TeX code.
(defvar LaTeX-enumitem-SetEnumitemValue-regexp
'("\\\\SetEnumitemValue{\\([^}]+\\)}{\\([^}]+\\)}"
(0 1 2) LaTeX-auto-enumitem-SetEnumitemValue)
"Matches the arguments of `\\SetEnumitemValue' from `enumitem' package.")
;; Plug them into the machinery.
(defun LaTeX-enumitem-auto-prepare ()
"Clear various `LaTeX-enumitem-*' before parsing."
(setq LaTeX-auto-enumitem-newlist nil
LaTeX-auto-enumitem-SetLabelAlign nil
LaTeX-auto-enumitem-SetEnumitemKey nil
LaTeX-auto-enumitem-SetEnumitemValue nil))
(defun LaTeX-enumitem-auto-cleanup ()
"Move parsing results into right places for further usage."
;; \newlist{<name>}{<type>}{<max-depth>}
;; env=<name>, type=<type>, ignored=<max-depth>
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let* ((env (car env-type))
(type (cadr env-type)))
(LaTeX-add-environments (list env 'LaTeX-enumitem-env-with-opts))
;; Tell AUCTeX about parsed description like environments.
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,env . LaTeX-item-argument)))
;; Add new env's to `ispell-tex-skip-alist': skip the opt. arg:
(TeX-ispell-skip-setcdr `((,env ispell-tex-arg-end 0))))))
(add-hook 'TeX-auto-prepare-hook #'LaTeX-enumitem-auto-prepare t)
(add-hook 'TeX-auto-cleanup-hook #'LaTeX-enumitem-auto-cleanup t)
(add-hook 'TeX-update-style-hook #'TeX-auto-parse t)
(defun LaTeX-enumitem-env-with-opts (env)
"Insert ENV provided by `enumitem' package."
(LaTeX-insert-environment
env
(let ((opts (TeX-read-key-val t (LaTeX-enumitem-key-val-options))))
(when (and opts (not (string-equal opts "")))
(format "[%s]" opts))))
(if (TeX-active-mark)
(progn
(LaTeX-find-matching-begin)
(end-of-line 1))
(end-of-line 0))
(delete-char 1)
(when (looking-at (concat "^[ \t]+$\\|"
"^[ \t]*" TeX-comment-start-regexp "+[ \t]*$"))
(delete-region (point) (line-end-position)))
(delete-horizontal-space)
;; Deactivate the mark here in order to prevent `TeX-parse-macro'
;; from swapping point and mark and the \item ending up right after
;; \begin{...}.
(deactivate-mark)
(LaTeX-insert-item)
;; The inserted \item may have outdented the first line to the
;; right. Fill it, if appropriate.
(when (and auto-fill-function
(not (looking-at "$"))
(not (assoc env LaTeX-indent-environment-list))
(> (- (line-end-position) (line-beginning-position))
(current-fill-column)))
(LaTeX-fill-paragraph nil)))
(defun LaTeX-arg-enumitem-SetLabelAlign (optional)
"Ask and insert a new type (value) for the \"align\" key.
Insert value in brackets if OPTIONAL is non-nil."
(let ((val (TeX-read-string "Alignment: ")))
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetLabelAligns val)))
(defun LaTeX-arg-enumitem-SetEnumitemKey (optional)
"Ask and insert a new key and its replacement.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (TeX-read-string "New Key: "))
(replace (TeX-read-key-val optional
(LaTeX-enumitem-key-val-options)
"Replacement")))
(TeX-argument-insert key optional)
(TeX-argument-insert replace optional)
(LaTeX-add-enumitem-SetEnumitemKeys key)))
;; In `LaTeX-enumitem-SetEnumitemValue-regexp', we match (0 1 2).
;; When adding a new `key=val', we need something unique for `0'-match
;; until the next `C-c C-n'. We mimic that regex-match bei concat'ing
;; the elements and pass the result to
;; `LaTeX-add-enumitem-SetEnumitemValues'. It will vanish upon next
;; invocation of `C-c C-n'.
(defun LaTeX-arg-enumitem-SetEnumitemValue (optional)
"Ask and insert for a new value added to an existing key.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (completing-read "Key: " LaTeX-enumitem-key-val-options))
(val (TeX-read-string "String value: ")))
(TeX-argument-insert key optional)
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetEnumitemValues
(list (concat "\\SetEnumitemValue{" key "}{" val "}")
key val))))
(defun LaTeX-arg-enumitem-setlist (_optional)
"Insert the arguments of `\\setlist' macro from `enumitem' package.
This function inserts three arguments. The first optional
argument is only available when the package option `sizes' is
provided. OPTIONAL is ignored."
;; First opt. argument:
(when (LaTeX-provided-package-options-member "enumitem" "sizes")
(let* ((TeX-arg-opening-brace "<")
(TeX-arg-closing-brace ">")
(sizes '("script" "tiny" "footnote" "small" "normal"
"large" "Large" "LARGE" "huge" "Huge"))
(size (completing-read
(TeX-argument-prompt t nil "Size")
(append
(mapcar (lambda (x) (concat "-" x)) sizes)
(mapcar (lambda (x) (concat x "-")) sizes)
sizes))))
(TeX-argument-insert size t)))
;; Second opt. argument:
(TeX-argument-insert
(mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member
"enumitem" "includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
",")
t)
;; Mandatory argument:
(TeX-argument-insert
(TeX-read-key-val nil (LaTeX-enumitem-key-val-options))
nil))
(TeX-add-style-hook
"enumitem"
(lambda ()
;; Add enumitem to the parser.
(TeX-auto-add-regexp LaTeX-enumitem-newlist-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemKey-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemValue-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetLabelAlign-regexp)
;; Add the standard environments:
(LaTeX-add-enumitem-newlists '("itemize" "itemize")
'("enumerate" "enumerate")
'("description" "description"))
;; Add the starred versions with the 'inline' package option:
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-enumitem-newlists '("itemize*" "itemize*")
'("enumerate*" "enumerate*")
'("description*" "description*")))
;; Standard env's take key-val as optional argument.
(LaTeX-add-environments
'("itemize" LaTeX-enumitem-env-with-opts)
'("enumerate" LaTeX-enumitem-env-with-opts)
'("description" LaTeX-enumitem-env-with-opts))
;; Make inline env's available with package option "inline"
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-environments
'("itemize*" LaTeX-enumitem-env-with-opts)
'("enumerate*" LaTeX-enumitem-env-with-opts)
'("description*" LaTeX-enumitem-env-with-opts))
(add-to-list 'LaTeX-item-list '("description*" . LaTeX-item-argument)))
(TeX-add-symbols
;; 6 Size dependent settings
'("SetEnumitemSize" 2)
;; 7 Cloning the basic lists
;; The easy way would be:
;; '("newlist"
;; "Name" (TeX-arg-eval
;; completing-read "Type: "
;; '(("itemize") ("enumerate") ("description")
;; ("itemize*") ("enumerate*") ("description*")))
;; "Max-depth")
;; But we go the extra mile to improve the user experience and add
;; the arguments directly to appropriate lists.
;; \newlist{<name>}{<type>}{<max-depth>}
'("newlist"
(TeX-arg-eval
(lambda ()
(let ((name (TeX-read-string "Name: "))
(type (completing-read
"Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list))))
(depth (TeX-read-string "Max-depth: ")))
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,name . LaTeX-item-argument)))
(LaTeX-add-environments `(,name LaTeX-enumitem-env-with-opts))
(LaTeX-add-enumitem-newlists (list name type))
(TeX-ispell-skip-setcdr `((,name ispell-tex-arg-end 0)))
(TeX-argument-insert name nil)
(TeX-argument-insert type nil)
(format "%s" depth)))))
;; \renewlist{<name>}{<type>}{<max-depth>}
'("renewlist"
(TeX-arg-eval completing-read "Name: "
(mapcar #'car (LaTeX-enumitem-newlist-list)))
(TeX-arg-eval completing-read "Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list)))
"Max-depth")
;; \setlist<size>[<names,levels>]{<key-vals>}
'("setlist" LaTeX-arg-enumitem-setlist)
;; \setlist*[<names,levels>]{<key-vals>}
'("setlist*"
[TeX-arg-eval mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member "enumitem"
"includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
","]
(TeX-arg-key-val (LaTeX-enumitem-key-val-options))) )
;; General commands:
(TeX-add-symbols
;; Ask for an Integer and insert it.
'("setlistdepth" "Integer")
;; Just add the braces and let the user do the rest.
'("AddEnumerateCounter" 3)
'("AddEnumerateCounter*" 3)
;; "\restartlist" only works for lists defined with "resume" key.
;; We will not extract that information and leave that to users.
;; For completion, extract enumerated environments from
;; `LaTeX-enumitem-newlist-list' and add "enumerate" to them.
'("restartlist"
(TeX-arg-eval
(lambda ()
(let ((enums '("enumerate")))
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(cl-pushnew "enumerate*" enums :test #'equal))
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let ((env (car env-type))
(type (cadr env-type)))
(when (or (string-equal type "enumerate")
(string-equal type "enumerate*"))
(cl-pushnew env enums :test #'equal))))
(completing-read "List name: " enums)))))
;; "Align" is added as new value to "align" key in key-val list.
'("SetLabelAlign" LaTeX-arg-enumitem-SetLabelAlign t)
;; "Key" will be parsed and added to key-val list.
'("SetEnumitemKey" LaTeX-arg-enumitem-SetEnumitemKey)
;; "Key" and "Value" are added to our key-val list.
'("SetEnumitemValue" LaTeX-arg-enumitem-SetEnumitemValue "Replacement")
;; v3.6 has a macro for visual debugging.
'("DrawEnumitemLabel" 0))
;; Setting enumerate short label
(when (LaTeX-provided-package-options-member "enumitem" "shortlabels")
(TeX-add-symbols
'("SetEnumerateShortLabel"
(TeX-arg-eval completing-read "Key: "
'("A" "a" "I" "i" "1"))
"Replacement")))
;; Add \labelindent to list of known lengths:
(LaTeX-add-lengths "labelindent")
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("newlist" "{{{")
("renewlist" "{{{")
("SetEnumitemSize" "{{")
("AddEnumerateCounter" "*{{{")
("SetLabelAlign" "{{")
("SetEnumitemKey" "{{" )
("SetEnumitemValue" "{{{"))
'function)
;; Cater for additional optionals arg <size> based on package
;; option 'sizes':
(font-latex-add-keywords
(if (LaTeX-provided-package-options-member "enumitem" "sizes")
'(("setlist" "*<[{"))
'(("setlist" "*[{")))
'function)
(font-latex-add-keywords '(("restartlist" "{" )
("setlistdepth" "{" )
("SetEnumerateShortLabel" "{{"))
'variable)))
TeX-dialect)
(defvar LaTeX-enumitem-package-options
'("inline" "shortlabels" "loadonly" "sizes"
"ignoredisplayed" "includedisplayed")
"Package options for the enumitem package.")
;;; enumitem.el ends here
| 43755 | ;;; enumitem.el --- AUCTeX style for `enumitem.sty' (v3.9) -*- lexical-binding: t; -*-
;; Copyright (C) 2015--2021 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <EMAIL>
;; Created: 2014-10-20
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for `enumitem.sty' (v3.9) from 2019/06/20.
;; `enumitem.sty' is part of TeXLive.
;; Tassilo Horn's `minted.el' was a major source of inspiration for
;; this style, many thanks to him (also for patiently answering my
;; many other questions, incl. the stupid ones.)
;; If things do not work or when in doubt, press `C-c C-n'. Comments
;; for improvement are welcome.
;;; Code:
(require 'tex)
(require 'latex)
(eval-when-compile
(require 'cl-lib))
;; Silence the compiler:
(declare-function font-latex-add-keywords
"font-latex"
(keywords class))
(defvar LaTeX-enumitem-key-val-options
`(;; 3.1 Label and cross references format
("label" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("label*" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("ref" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("font" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("format" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("align" ("left" "right" "parleft"))
;; 3.2 Horizontal spacing of labels
("labelindent" ("*" "!"))
("left")
("leftmargin" ("*" "!"))
("itemindent" ("*" "!"))
("labelsep" ("*" "!"))
("labelwidth" ("*" "!"))
("widest")
("widest*")
("labelsep*")
("labelindent*")
("rightmargin")
;; Vertical Spacing
("topsep")
("partopsep")
("parsep")
("itemsep")
;; 3.3 Numbering, stopping, and resuming
("start")
("resume")
("resume*")
;; 3.4 Series
("series")
;; 3.5 Penalties
("beginpenalty")
("midpenalty")
("endpenalty")
;; 3.6 Injecting code
("before")
("before*")
("after")
("after*")
("first")
("first*")
;; 3.7 Description styles
("style" ("standard" "unboxed" "nextline" "sameline" "multiline"))
;; 3.8 Compact lists
("noitemsep")
("nosep")
;; 3.9 Wide lists
("wide")
;; 4 Inline lists
("itemjoin")
("itemjoin*")
("afterlabel")
("mode" ("boxed" "unboxed")))
"Key=value options for enumitem macros and environments.")
(defun LaTeX-enumitem-key-val-options ()
"Return an updated list of key=vals from enumitem package."
(append
;; New keys are valueless, so take them as is:
(when (LaTeX-enumitem-SetEnumitemKey-list)
(LaTeX-enumitem-SetEnumitemKey-list))
;; New values defined available keys: We have to collect predefined
;; values (if any) from `LaTeX-enumitem-key-val-options' (stored in
;; `vals-predefined') and user-defined values (stored in
;; `vals-parsed') which were parsed and added to `result' in the
;; previous run of `dolist' and then combine them as value to a
;; key.
(when (LaTeX-enumitem-SetEnumitemValue-list)
(let (result)
(dolist (keyvals (LaTeX-enumitem-SetEnumitemValue-list) result)
(let* ((key (nth 1 keyvals))
(val (nth 2 keyvals))
(vals-predefined
(cadr (assoc key LaTeX-enumitem-key-val-options)))
(vals-parsed (cadr (assoc key result))))
;; Remove entry in `result' if there is one for the `key':
(when (assoc key result)
(setq result (assq-delete-all (car (assoc key result))
result)))
;; Add the entry to `result'; also remove any duplicates
(cl-pushnew (list key (TeX-delete-duplicate-strings
(append vals-parsed
vals-predefined
(list val))))
result :test #'equal)))))
;; New values to `align' key: We collect the predefined ones from
;; `LaTeX-enumitem-key-val-options' in `vals-predefined' and
;; prepend them to newly parsed ones:
(when (LaTeX-enumitem-SetLabelAlign-list)
(let* ((key "<KEY>")
(vals (mapcar #'car (LaTeX-enumitem-SetLabelAlign-list)))
(vals-predefined (cadr
(assoc key LaTeX-enumitem-key-val-options))))
`(("align" ,(TeX-delete-duplicate-strings
(append vals-predefined vals))))))
;; Predefined key=vals:
LaTeX-enumitem-key-val-options))
;; Setup for \newlist:
(TeX-auto-add-type "enumitem-newlist" "LaTeX")
(defvar LaTeX-enumitem-newlist-regexp
'("\\\\newlist{\\([^}]+\\)}{\\([^}]+\\)}"
(1 2) LaTeX-auto-enumitem-newlist)
"Matches the arguments of `\\newlist' from `enumitem' package.")
;; Setup for \SetLabelAlign:
(TeX-auto-add-type "enumitem-SetLabelAlign" "LaTeX")
(defvar LaTeX-enumitem-SetLabelAlign-regexp
'("\\\\SetLabelAlign{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetLabelAlign)
"Matches the argument of `\\SetLabelAlign' from `enumitem' package.")
;; Setup for \SetEnumitemKey:
(TeX-auto-add-type "enumitem-SetEnumitemKey" "LaTeX")
(defvar LaTeX-enumitem-SetEnumitemKey-regexp
'("\\\\SetEnumitemKey{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetEnumitemKey)
"Matches the arguments of `\\SetEnumitemKey' from `enumitem' package.")
;; Setup for \SetEnumitemValue:
(TeX-auto-add-type "enumitem-SetEnumitemValue" "LaTeX")
;; Upon Tassilo's recommendation, we include also `0' so that we can
;; use the function `LaTeX-enumitem-SetEnumitemValue-list' while we
;; make sure that `TeX-auto-list-information' doesn't remove multiple
;; defined values to a specific key. For this reason, we also ignore
;; the 3. argument to the `\SetEnumitemValue' macro (i.e., a third
;; {\\([^}]+\\)} in regex) so that we don't pollute the generated
;; `docname.el' with unnecessary (La)TeX code.
(defvar LaTeX-enumitem-SetEnumitemValue-regexp
'("\\\\SetEnumitemValue{\\([^}]+\\)}{\\([^}]+\\)}"
(0 1 2) LaTeX-auto-enumitem-SetEnumitemValue)
"Matches the arguments of `\\SetEnumitemValue' from `enumitem' package.")
;; Plug them into the machinery.
(defun LaTeX-enumitem-auto-prepare ()
"Clear various `LaTeX-enumitem-*' before parsing."
(setq LaTeX-auto-enumitem-newlist nil
LaTeX-auto-enumitem-SetLabelAlign nil
LaTeX-auto-enumitem-SetEnumitemKey nil
LaTeX-auto-enumitem-SetEnumitemValue nil))
(defun LaTeX-enumitem-auto-cleanup ()
"Move parsing results into right places for further usage."
;; \newlist{<name>}{<type>}{<max-depth>}
;; env=<name>, type=<type>, ignored=<max-depth>
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let* ((env (car env-type))
(type (cadr env-type)))
(LaTeX-add-environments (list env 'LaTeX-enumitem-env-with-opts))
;; Tell AUCTeX about parsed description like environments.
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,env . LaTeX-item-argument)))
;; Add new env's to `ispell-tex-skip-alist': skip the opt. arg:
(TeX-ispell-skip-setcdr `((,env ispell-tex-arg-end 0))))))
(add-hook 'TeX-auto-prepare-hook #'LaTeX-enumitem-auto-prepare t)
(add-hook 'TeX-auto-cleanup-hook #'LaTeX-enumitem-auto-cleanup t)
(add-hook 'TeX-update-style-hook #'TeX-auto-parse t)
(defun LaTeX-enumitem-env-with-opts (env)
"Insert ENV provided by `enumitem' package."
(LaTeX-insert-environment
env
(let ((opts (TeX-read-key-val t (LaTeX-enumitem-key-val-options))))
(when (and opts (not (string-equal opts "")))
(format "[%s]" opts))))
(if (TeX-active-mark)
(progn
(LaTeX-find-matching-begin)
(end-of-line 1))
(end-of-line 0))
(delete-char 1)
(when (looking-at (concat "^[ \t]+$\\|"
"^[ \t]*" TeX-comment-start-regexp "+[ \t]*$"))
(delete-region (point) (line-end-position)))
(delete-horizontal-space)
;; Deactivate the mark here in order to prevent `TeX-parse-macro'
;; from swapping point and mark and the \item ending up right after
;; \begin{...}.
(deactivate-mark)
(LaTeX-insert-item)
;; The inserted \item may have outdented the first line to the
;; right. Fill it, if appropriate.
(when (and auto-fill-function
(not (looking-at "$"))
(not (assoc env LaTeX-indent-environment-list))
(> (- (line-end-position) (line-beginning-position))
(current-fill-column)))
(LaTeX-fill-paragraph nil)))
(defun LaTeX-arg-enumitem-SetLabelAlign (optional)
"Ask and insert a new type (value) for the \"align\" key.
Insert value in brackets if OPTIONAL is non-nil."
(let ((val (TeX-read-string "Alignment: ")))
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetLabelAligns val)))
(defun LaTeX-arg-enumitem-SetEnumitemKey (optional)
"Ask and insert a new key and its replacement.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (TeX-read-string "New Key: "))
(replace (TeX-read-key-val optional
(LaTeX-enumitem-key-val-options)
"Replacement")))
(TeX-argument-insert key optional)
(TeX-argument-insert replace optional)
(LaTeX-add-enumitem-SetEnumitemKeys key)))
;; In `LaTeX-enumitem-SetEnumitemValue-regexp', we match (0 1 2).
;; When adding a new `key=val', we need something unique for `0'-match
;; until the next `C-c C-n'. We mimic that regex-match bei concat'ing
;; the elements and pass the result to
;; `LaTeX-add-enumitem-SetEnumitemValues'. It will vanish upon next
;; invocation of `C-c C-n'.
(defun LaTeX-arg-enumitem-SetEnumitemValue (optional)
"Ask and insert for a new value added to an existing key.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (completing-read "Key: " LaTeX-enumitem-key-val-options))
(val (TeX-read-string "String value: ")))
(TeX-argument-insert key optional)
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetEnumitemValues
(list (concat "\\SetEnumitemValue{" key "}{" val "}")
key val))))
(defun LaTeX-arg-enumitem-setlist (_optional)
"Insert the arguments of `\\setlist' macro from `enumitem' package.
This function inserts three arguments. The first optional
argument is only available when the package option `sizes' is
provided. OPTIONAL is ignored."
;; First opt. argument:
(when (LaTeX-provided-package-options-member "enumitem" "sizes")
(let* ((TeX-arg-opening-brace "<")
(TeX-arg-closing-brace ">")
(sizes '("script" "tiny" "footnote" "small" "normal"
"large" "Large" "LARGE" "huge" "Huge"))
(size (completing-read
(TeX-argument-prompt t nil "Size")
(append
(mapcar (lambda (x) (concat "-" x)) sizes)
(mapcar (lambda (x) (concat x "-")) sizes)
sizes))))
(TeX-argument-insert size t)))
;; Second opt. argument:
(TeX-argument-insert
(mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member
"enumitem" "includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
",")
t)
;; Mandatory argument:
(TeX-argument-insert
(TeX-read-key-val nil (LaTeX-enumitem-key-val-options))
nil))
(TeX-add-style-hook
"enumitem"
(lambda ()
;; Add enumitem to the parser.
(TeX-auto-add-regexp LaTeX-enumitem-newlist-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemKey-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemValue-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetLabelAlign-regexp)
;; Add the standard environments:
(LaTeX-add-enumitem-newlists '("itemize" "itemize")
'("enumerate" "enumerate")
'("description" "description"))
;; Add the starred versions with the 'inline' package option:
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-enumitem-newlists '("itemize*" "itemize*")
'("enumerate*" "enumerate*")
'("description*" "description*")))
;; Standard env's take key-val as optional argument.
(LaTeX-add-environments
'("itemize" LaTeX-enumitem-env-with-opts)
'("enumerate" LaTeX-enumitem-env-with-opts)
'("description" LaTeX-enumitem-env-with-opts))
;; Make inline env's available with package option "inline"
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-environments
'("itemize*" LaTeX-enumitem-env-with-opts)
'("enumerate*" LaTeX-enumitem-env-with-opts)
'("description*" LaTeX-enumitem-env-with-opts))
(add-to-list 'LaTeX-item-list '("description*" . LaTeX-item-argument)))
(TeX-add-symbols
;; 6 Size dependent settings
'("SetEnumitemSize" 2)
;; 7 Cloning the basic lists
;; The easy way would be:
;; '("newlist"
;; "Name" (TeX-arg-eval
;; completing-read "Type: "
;; '(("itemize") ("enumerate") ("description")
;; ("itemize*") ("enumerate*") ("description*")))
;; "Max-depth")
;; But we go the extra mile to improve the user experience and add
;; the arguments directly to appropriate lists.
;; \newlist{<name>}{<type>}{<max-depth>}
'("newlist"
(TeX-arg-eval
(lambda ()
(let ((name (TeX-read-string "Name: "))
(type (completing-read
"Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list))))
(depth (TeX-read-string "Max-depth: ")))
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,name . LaTeX-item-argument)))
(LaTeX-add-environments `(,name LaTeX-enumitem-env-with-opts))
(LaTeX-add-enumitem-newlists (list name type))
(TeX-ispell-skip-setcdr `((,name ispell-tex-arg-end 0)))
(TeX-argument-insert name nil)
(TeX-argument-insert type nil)
(format "%s" depth)))))
;; \renewlist{<name>}{<type>}{<max-depth>}
'("renewlist"
(TeX-arg-eval completing-read "Name: "
(mapcar #'car (LaTeX-enumitem-newlist-list)))
(TeX-arg-eval completing-read "Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list)))
"Max-depth")
;; \setlist<size>[<names,levels>]{<key-vals>}
'("setlist" LaTeX-arg-enumitem-setlist)
;; \setlist*[<names,levels>]{<key-vals>}
'("setlist*"
[TeX-arg-eval mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member "enumitem"
"includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
","]
(TeX-arg-key-val (LaTeX-enumitem-key-val-options))) )
;; General commands:
(TeX-add-symbols
;; Ask for an Integer and insert it.
'("setlistdepth" "Integer")
;; Just add the braces and let the user do the rest.
'("AddEnumerateCounter" 3)
'("AddEnumerateCounter*" 3)
;; "\restartlist" only works for lists defined with "resume" key.
;; We will not extract that information and leave that to users.
;; For completion, extract enumerated environments from
;; `LaTeX-enumitem-newlist-list' and add "enumerate" to them.
'("restartlist"
(TeX-arg-eval
(lambda ()
(let ((enums '("enumerate")))
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(cl-pushnew "enumerate*" enums :test #'equal))
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let ((env (car env-type))
(type (cadr env-type)))
(when (or (string-equal type "enumerate")
(string-equal type "enumerate*"))
(cl-pushnew env enums :test #'equal))))
(completing-read "List name: " enums)))))
;; "Align" is added as new value to "align" key in key-val list.
'("SetLabelAlign" LaTeX-arg-enumitem-SetLabelAlign t)
;; "Key" will be parsed and added to key-val list.
'("SetEnumitemKey" LaTeX-arg-enumitem-SetEnumitemKey)
;; "Key" and "Value" are added to our key-val list.
'("SetEnumitemValue" LaTeX-arg-enumitem-SetEnumitemValue "Replacement")
;; v3.6 has a macro for visual debugging.
'("DrawEnumitemLabel" 0))
;; Setting enumerate short label
(when (LaTeX-provided-package-options-member "enumitem" "shortlabels")
(TeX-add-symbols
'("SetEnumerateShortLabel"
(TeX-arg-eval completing-read "Key: "
'("A" "a" "I" "i" "1"))
"Replacement")))
;; Add \labelindent to list of known lengths:
(LaTeX-add-lengths "labelindent")
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("newlist" "{{{")
("renewlist" "{{{")
("SetEnumitemSize" "{{")
("AddEnumerateCounter" "*{{{")
("SetLabelAlign" "{{")
("SetEnumitemKey" "{{" )
("SetEnumitemValue" "{{{"))
'function)
;; Cater for additional optionals arg <size> based on package
;; option 'sizes':
(font-latex-add-keywords
(if (LaTeX-provided-package-options-member "enumitem" "sizes")
'(("setlist" "*<[{"))
'(("setlist" "*[{")))
'function)
(font-latex-add-keywords '(("restartlist" "{" )
("setlistdepth" "{" )
("SetEnumerateShortLabel" "{{"))
'variable)))
TeX-dialect)
(defvar LaTeX-enumitem-package-options
'("inline" "shortlabels" "loadonly" "sizes"
"ignoredisplayed" "includedisplayed")
"Package options for the enumitem package.")
;;; enumitem.el ends here
| true | ;;; enumitem.el --- AUCTeX style for `enumitem.sty' (v3.9) -*- lexical-binding: t; -*-
;; Copyright (C) 2015--2021 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:EMAIL:<EMAIL>END_PI
;; Created: 2014-10-20
;; Keywords: tex
;; This file is part of AUCTeX.
;; AUCTeX is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; AUCTeX 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 AUCTeX; see the file COPYING. If not, write to the Free
;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;; This file adds support for `enumitem.sty' (v3.9) from 2019/06/20.
;; `enumitem.sty' is part of TeXLive.
;; Tassilo Horn's `minted.el' was a major source of inspiration for
;; this style, many thanks to him (also for patiently answering my
;; many other questions, incl. the stupid ones.)
;; If things do not work or when in doubt, press `C-c C-n'. Comments
;; for improvement are welcome.
;;; Code:
(require 'tex)
(require 'latex)
(eval-when-compile
(require 'cl-lib))
;; Silence the compiler:
(declare-function font-latex-add-keywords
"font-latex"
(keywords class))
(defvar LaTeX-enumitem-key-val-options
`(;; 3.1 Label and cross references format
("label" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("label*" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("ref" ("\\alph*" "\\Alph*" "\\arabic*"
"\\roman*" "\\Roman*" "\\value*"))
("font" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("format" ,(mapcar (lambda (mac)
(concat TeX-esc mac))
'(;; family
"rmfamily" "sffamily" "ttfamily"
;; series
"mdseries" "bfseries"
;; shape
"upshape" "itshape" "slshape" "scshape"
;; size
"tiny" "scriptsize" "footnotesize"
"small" "normalsize" "large"
"Large" "LARGE" "huge" "Huge"
;; reset macro
"normalfont")))
("align" ("left" "right" "parleft"))
;; 3.2 Horizontal spacing of labels
("labelindent" ("*" "!"))
("left")
("leftmargin" ("*" "!"))
("itemindent" ("*" "!"))
("labelsep" ("*" "!"))
("labelwidth" ("*" "!"))
("widest")
("widest*")
("labelsep*")
("labelindent*")
("rightmargin")
;; Vertical Spacing
("topsep")
("partopsep")
("parsep")
("itemsep")
;; 3.3 Numbering, stopping, and resuming
("start")
("resume")
("resume*")
;; 3.4 Series
("series")
;; 3.5 Penalties
("beginpenalty")
("midpenalty")
("endpenalty")
;; 3.6 Injecting code
("before")
("before*")
("after")
("after*")
("first")
("first*")
;; 3.7 Description styles
("style" ("standard" "unboxed" "nextline" "sameline" "multiline"))
;; 3.8 Compact lists
("noitemsep")
("nosep")
;; 3.9 Wide lists
("wide")
;; 4 Inline lists
("itemjoin")
("itemjoin*")
("afterlabel")
("mode" ("boxed" "unboxed")))
"Key=value options for enumitem macros and environments.")
(defun LaTeX-enumitem-key-val-options ()
"Return an updated list of key=vals from enumitem package."
(append
;; New keys are valueless, so take them as is:
(when (LaTeX-enumitem-SetEnumitemKey-list)
(LaTeX-enumitem-SetEnumitemKey-list))
;; New values defined available keys: We have to collect predefined
;; values (if any) from `LaTeX-enumitem-key-val-options' (stored in
;; `vals-predefined') and user-defined values (stored in
;; `vals-parsed') which were parsed and added to `result' in the
;; previous run of `dolist' and then combine them as value to a
;; key.
(when (LaTeX-enumitem-SetEnumitemValue-list)
(let (result)
(dolist (keyvals (LaTeX-enumitem-SetEnumitemValue-list) result)
(let* ((key (nth 1 keyvals))
(val (nth 2 keyvals))
(vals-predefined
(cadr (assoc key LaTeX-enumitem-key-val-options)))
(vals-parsed (cadr (assoc key result))))
;; Remove entry in `result' if there is one for the `key':
(when (assoc key result)
(setq result (assq-delete-all (car (assoc key result))
result)))
;; Add the entry to `result'; also remove any duplicates
(cl-pushnew (list key (TeX-delete-duplicate-strings
(append vals-parsed
vals-predefined
(list val))))
result :test #'equal)))))
;; New values to `align' key: We collect the predefined ones from
;; `LaTeX-enumitem-key-val-options' in `vals-predefined' and
;; prepend them to newly parsed ones:
(when (LaTeX-enumitem-SetLabelAlign-list)
(let* ((key "PI:KEY:<KEY>END_PI")
(vals (mapcar #'car (LaTeX-enumitem-SetLabelAlign-list)))
(vals-predefined (cadr
(assoc key LaTeX-enumitem-key-val-options))))
`(("align" ,(TeX-delete-duplicate-strings
(append vals-predefined vals))))))
;; Predefined key=vals:
LaTeX-enumitem-key-val-options))
;; Setup for \newlist:
(TeX-auto-add-type "enumitem-newlist" "LaTeX")
(defvar LaTeX-enumitem-newlist-regexp
'("\\\\newlist{\\([^}]+\\)}{\\([^}]+\\)}"
(1 2) LaTeX-auto-enumitem-newlist)
"Matches the arguments of `\\newlist' from `enumitem' package.")
;; Setup for \SetLabelAlign:
(TeX-auto-add-type "enumitem-SetLabelAlign" "LaTeX")
(defvar LaTeX-enumitem-SetLabelAlign-regexp
'("\\\\SetLabelAlign{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetLabelAlign)
"Matches the argument of `\\SetLabelAlign' from `enumitem' package.")
;; Setup for \SetEnumitemKey:
(TeX-auto-add-type "enumitem-SetEnumitemKey" "LaTeX")
(defvar LaTeX-enumitem-SetEnumitemKey-regexp
'("\\\\SetEnumitemKey{\\([^}]+\\)}"
1 LaTeX-auto-enumitem-SetEnumitemKey)
"Matches the arguments of `\\SetEnumitemKey' from `enumitem' package.")
;; Setup for \SetEnumitemValue:
(TeX-auto-add-type "enumitem-SetEnumitemValue" "LaTeX")
;; Upon Tassilo's recommendation, we include also `0' so that we can
;; use the function `LaTeX-enumitem-SetEnumitemValue-list' while we
;; make sure that `TeX-auto-list-information' doesn't remove multiple
;; defined values to a specific key. For this reason, we also ignore
;; the 3. argument to the `\SetEnumitemValue' macro (i.e., a third
;; {\\([^}]+\\)} in regex) so that we don't pollute the generated
;; `docname.el' with unnecessary (La)TeX code.
(defvar LaTeX-enumitem-SetEnumitemValue-regexp
'("\\\\SetEnumitemValue{\\([^}]+\\)}{\\([^}]+\\)}"
(0 1 2) LaTeX-auto-enumitem-SetEnumitemValue)
"Matches the arguments of `\\SetEnumitemValue' from `enumitem' package.")
;; Plug them into the machinery.
(defun LaTeX-enumitem-auto-prepare ()
"Clear various `LaTeX-enumitem-*' before parsing."
(setq LaTeX-auto-enumitem-newlist nil
LaTeX-auto-enumitem-SetLabelAlign nil
LaTeX-auto-enumitem-SetEnumitemKey nil
LaTeX-auto-enumitem-SetEnumitemValue nil))
(defun LaTeX-enumitem-auto-cleanup ()
"Move parsing results into right places for further usage."
;; \newlist{<name>}{<type>}{<max-depth>}
;; env=<name>, type=<type>, ignored=<max-depth>
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let* ((env (car env-type))
(type (cadr env-type)))
(LaTeX-add-environments (list env 'LaTeX-enumitem-env-with-opts))
;; Tell AUCTeX about parsed description like environments.
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,env . LaTeX-item-argument)))
;; Add new env's to `ispell-tex-skip-alist': skip the opt. arg:
(TeX-ispell-skip-setcdr `((,env ispell-tex-arg-end 0))))))
(add-hook 'TeX-auto-prepare-hook #'LaTeX-enumitem-auto-prepare t)
(add-hook 'TeX-auto-cleanup-hook #'LaTeX-enumitem-auto-cleanup t)
(add-hook 'TeX-update-style-hook #'TeX-auto-parse t)
(defun LaTeX-enumitem-env-with-opts (env)
"Insert ENV provided by `enumitem' package."
(LaTeX-insert-environment
env
(let ((opts (TeX-read-key-val t (LaTeX-enumitem-key-val-options))))
(when (and opts (not (string-equal opts "")))
(format "[%s]" opts))))
(if (TeX-active-mark)
(progn
(LaTeX-find-matching-begin)
(end-of-line 1))
(end-of-line 0))
(delete-char 1)
(when (looking-at (concat "^[ \t]+$\\|"
"^[ \t]*" TeX-comment-start-regexp "+[ \t]*$"))
(delete-region (point) (line-end-position)))
(delete-horizontal-space)
;; Deactivate the mark here in order to prevent `TeX-parse-macro'
;; from swapping point and mark and the \item ending up right after
;; \begin{...}.
(deactivate-mark)
(LaTeX-insert-item)
;; The inserted \item may have outdented the first line to the
;; right. Fill it, if appropriate.
(when (and auto-fill-function
(not (looking-at "$"))
(not (assoc env LaTeX-indent-environment-list))
(> (- (line-end-position) (line-beginning-position))
(current-fill-column)))
(LaTeX-fill-paragraph nil)))
(defun LaTeX-arg-enumitem-SetLabelAlign (optional)
"Ask and insert a new type (value) for the \"align\" key.
Insert value in brackets if OPTIONAL is non-nil."
(let ((val (TeX-read-string "Alignment: ")))
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetLabelAligns val)))
(defun LaTeX-arg-enumitem-SetEnumitemKey (optional)
"Ask and insert a new key and its replacement.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (TeX-read-string "New Key: "))
(replace (TeX-read-key-val optional
(LaTeX-enumitem-key-val-options)
"Replacement")))
(TeX-argument-insert key optional)
(TeX-argument-insert replace optional)
(LaTeX-add-enumitem-SetEnumitemKeys key)))
;; In `LaTeX-enumitem-SetEnumitemValue-regexp', we match (0 1 2).
;; When adding a new `key=val', we need something unique for `0'-match
;; until the next `C-c C-n'. We mimic that regex-match bei concat'ing
;; the elements and pass the result to
;; `LaTeX-add-enumitem-SetEnumitemValues'. It will vanish upon next
;; invocation of `C-c C-n'.
(defun LaTeX-arg-enumitem-SetEnumitemValue (optional)
"Ask and insert for a new value added to an existing key.
Insert key and value in brackets if OPTIONAL is non-nil."
(let ((key (completing-read "Key: " LaTeX-enumitem-key-val-options))
(val (TeX-read-string "String value: ")))
(TeX-argument-insert key optional)
(TeX-argument-insert val optional)
(LaTeX-add-enumitem-SetEnumitemValues
(list (concat "\\SetEnumitemValue{" key "}{" val "}")
key val))))
(defun LaTeX-arg-enumitem-setlist (_optional)
"Insert the arguments of `\\setlist' macro from `enumitem' package.
This function inserts three arguments. The first optional
argument is only available when the package option `sizes' is
provided. OPTIONAL is ignored."
;; First opt. argument:
(when (LaTeX-provided-package-options-member "enumitem" "sizes")
(let* ((TeX-arg-opening-brace "<")
(TeX-arg-closing-brace ">")
(sizes '("script" "tiny" "footnote" "small" "normal"
"large" "Large" "LARGE" "huge" "Huge"))
(size (completing-read
(TeX-argument-prompt t nil "Size")
(append
(mapcar (lambda (x) (concat "-" x)) sizes)
(mapcar (lambda (x) (concat x "-")) sizes)
sizes))))
(TeX-argument-insert size t)))
;; Second opt. argument:
(TeX-argument-insert
(mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member
"enumitem" "includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
",")
t)
;; Mandatory argument:
(TeX-argument-insert
(TeX-read-key-val nil (LaTeX-enumitem-key-val-options))
nil))
(TeX-add-style-hook
"enumitem"
(lambda ()
;; Add enumitem to the parser.
(TeX-auto-add-regexp LaTeX-enumitem-newlist-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemKey-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetEnumitemValue-regexp)
(TeX-auto-add-regexp LaTeX-enumitem-SetLabelAlign-regexp)
;; Add the standard environments:
(LaTeX-add-enumitem-newlists '("itemize" "itemize")
'("enumerate" "enumerate")
'("description" "description"))
;; Add the starred versions with the 'inline' package option:
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-enumitem-newlists '("itemize*" "itemize*")
'("enumerate*" "enumerate*")
'("description*" "description*")))
;; Standard env's take key-val as optional argument.
(LaTeX-add-environments
'("itemize" LaTeX-enumitem-env-with-opts)
'("enumerate" LaTeX-enumitem-env-with-opts)
'("description" LaTeX-enumitem-env-with-opts))
;; Make inline env's available with package option "inline"
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(LaTeX-add-environments
'("itemize*" LaTeX-enumitem-env-with-opts)
'("enumerate*" LaTeX-enumitem-env-with-opts)
'("description*" LaTeX-enumitem-env-with-opts))
(add-to-list 'LaTeX-item-list '("description*" . LaTeX-item-argument)))
(TeX-add-symbols
;; 6 Size dependent settings
'("SetEnumitemSize" 2)
;; 7 Cloning the basic lists
;; The easy way would be:
;; '("newlist"
;; "Name" (TeX-arg-eval
;; completing-read "Type: "
;; '(("itemize") ("enumerate") ("description")
;; ("itemize*") ("enumerate*") ("description*")))
;; "Max-depth")
;; But we go the extra mile to improve the user experience and add
;; the arguments directly to appropriate lists.
;; \newlist{<name>}{<type>}{<max-depth>}
'("newlist"
(TeX-arg-eval
(lambda ()
(let ((name (TeX-read-string "Name: "))
(type (completing-read
"Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list))))
(depth (TeX-read-string "Max-depth: ")))
(when (or (string-equal type "description")
(string-equal type "description*"))
(add-to-list 'LaTeX-item-list `(,name . LaTeX-item-argument)))
(LaTeX-add-environments `(,name LaTeX-enumitem-env-with-opts))
(LaTeX-add-enumitem-newlists (list name type))
(TeX-ispell-skip-setcdr `((,name ispell-tex-arg-end 0)))
(TeX-argument-insert name nil)
(TeX-argument-insert type nil)
(format "%s" depth)))))
;; \renewlist{<name>}{<type>}{<max-depth>}
'("renewlist"
(TeX-arg-eval completing-read "Name: "
(mapcar #'car (LaTeX-enumitem-newlist-list)))
(TeX-arg-eval completing-read "Type: "
(mapcar #'cadr (LaTeX-enumitem-newlist-list)))
"Max-depth")
;; \setlist<size>[<names,levels>]{<key-vals>}
'("setlist" LaTeX-arg-enumitem-setlist)
;; \setlist*[<names,levels>]{<key-vals>}
'("setlist*"
[TeX-arg-eval mapconcat #'identity
(TeX-completing-read-multiple
(TeX-argument-prompt t nil "Environment(s), level(s)")
(append
(when (LaTeX-provided-package-options-member "enumitem"
"includedisplayed")
'("trivlist"))
(mapcar #'car (LaTeX-enumitem-newlist-list))
'("1" "2" "3" "4")))
","]
(TeX-arg-key-val (LaTeX-enumitem-key-val-options))) )
;; General commands:
(TeX-add-symbols
;; Ask for an Integer and insert it.
'("setlistdepth" "Integer")
;; Just add the braces and let the user do the rest.
'("AddEnumerateCounter" 3)
'("AddEnumerateCounter*" 3)
;; "\restartlist" only works for lists defined with "resume" key.
;; We will not extract that information and leave that to users.
;; For completion, extract enumerated environments from
;; `LaTeX-enumitem-newlist-list' and add "enumerate" to them.
'("restartlist"
(TeX-arg-eval
(lambda ()
(let ((enums '("enumerate")))
(when (LaTeX-provided-package-options-member "enumitem" "inline")
(cl-pushnew "enumerate*" enums :test #'equal))
(dolist (env-type (LaTeX-enumitem-newlist-list))
(let ((env (car env-type))
(type (cadr env-type)))
(when (or (string-equal type "enumerate")
(string-equal type "enumerate*"))
(cl-pushnew env enums :test #'equal))))
(completing-read "List name: " enums)))))
;; "Align" is added as new value to "align" key in key-val list.
'("SetLabelAlign" LaTeX-arg-enumitem-SetLabelAlign t)
;; "Key" will be parsed and added to key-val list.
'("SetEnumitemKey" LaTeX-arg-enumitem-SetEnumitemKey)
;; "Key" and "Value" are added to our key-val list.
'("SetEnumitemValue" LaTeX-arg-enumitem-SetEnumitemValue "Replacement")
;; v3.6 has a macro for visual debugging.
'("DrawEnumitemLabel" 0))
;; Setting enumerate short label
(when (LaTeX-provided-package-options-member "enumitem" "shortlabels")
(TeX-add-symbols
'("SetEnumerateShortLabel"
(TeX-arg-eval completing-read "Key: "
'("A" "a" "I" "i" "1"))
"Replacement")))
;; Add \labelindent to list of known lengths:
(LaTeX-add-lengths "labelindent")
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("newlist" "{{{")
("renewlist" "{{{")
("SetEnumitemSize" "{{")
("AddEnumerateCounter" "*{{{")
("SetLabelAlign" "{{")
("SetEnumitemKey" "{{" )
("SetEnumitemValue" "{{{"))
'function)
;; Cater for additional optionals arg <size> based on package
;; option 'sizes':
(font-latex-add-keywords
(if (LaTeX-provided-package-options-member "enumitem" "sizes")
'(("setlist" "*<[{"))
'(("setlist" "*[{")))
'function)
(font-latex-add-keywords '(("restartlist" "{" )
("setlistdepth" "{" )
("SetEnumerateShortLabel" "{{"))
'variable)))
TeX-dialect)
(defvar LaTeX-enumitem-package-options
'("inline" "shortlabels" "loadonly" "sizes"
"ignoredisplayed" "includedisplayed")
"Package options for the enumitem package.")
;;; enumitem.el ends here
|
[
{
"context": "exical-binding: t; -*-\n\n;; Copyright (C) 2015-2016 Ivan Malison\n\n;; This program is free software; you can redist",
"end": 122,
"score": 0.9998424649238586,
"start": 110,
"tag": "NAME",
"value": "Ivan Malison"
}
] | .emacs.d/plugins/multi-line/multi-line-decorator.el | articuluxe/harmsway | 2 | ;;; multi-line-decorator.el --- multi-line statements -*- lexical-binding: t; -*-
;; Copyright (C) 2015-2016 Ivan Malison
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; multi-line-decorator defines a collection of decorator respacers
;; that can be used to add behavior to existing respacers.
;;; Code:
(require 'eieio)
(require 'shut-up)
(require 'multi-line-candidate)
(require 'multi-line-respace)
(require 'multi-line-shared)
(put 'multi-line-pre-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-all-decorator 'lisp-indent-function 'defun)
(defmacro multi-line-compose (name &rest funcs)
"Build a new function with NAME that is the composition of FUNCS."
`(defun ,name (arg)
(multi-line-compose-helper ,funcs)))
(defmacro multi-line-compose-helper (funcs)
"Builds funcalls of FUNCS applied to the arg."
(if (equal (length funcs) 0)
(quote arg)
`(funcall ,(car funcs) (multi-line-compose-helper ,(cdr funcs)))))
;; TODO: Get rid of inheritance here
(defclass multi-line-each-decorator (multi-line-respacer)
((respacer :initarg :respacer)
(decorator :initarg :decorator)))
(defmethod multi-line-respace-one ((decorator multi-line-each-decorator)
index candidates)
(funcall (oref decorator decorator) (oref decorator respacer) index
candidates))
(defmacro multi-line-pre-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS before each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (decorated-respacer)
(make-instance 'multi-line-each-decorator
:respacer decorated-respacer
:decorator (lambda (respacer index candidates)
,@forms
(multi-line-respace-one respacer index candidates)))))
(defmacro multi-line-post-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (respacer)
(make-instance 'multi-line-each-decorator
:respacer respacer
:decorator (lambda (respacer index candidates)
(multi-line-respace-one respacer index candidates)
,@forms))))
(defmacro multi-line-post-all-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after all respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(multi-line-post-decorator
,name (when (equal index (- (length candidates) 1))
(goto-char (multi-line-candidate-position (car (last candidates))))
,@forms)))
(multi-line-pre-decorator multi-line-space-clearing-respacer
(multi-line-clear-whitespace-at-point))
(multi-line-post-all-decorator multi-line-trailing-comma-respacer
(multi-line-add-remove-or-leave-final-comma))
(multi-line-post-decorator
multi-line-reindenting-respacer
(shut-up
(indent-region (multi-line-candidate-position (car candidates))
(multi-line-candidate-position (car (last candidates))))))
(multi-line-compose multi-line-clearing-reindenting-respacer
'multi-line-reindenting-respacer
'multi-line-space-clearing-respacer)
(defclass multi-line-space-restoring-respacer ()
((respacer :initarg :respacer)))
(defmethod multi-line-respace-one ((respacer multi-line-space-restoring-respacer)
index candidates)
(cl-destructuring-bind (startm . endm) (multi-line-space-markers)
(let* ((start (marker-position startm))
(end (marker-position endm))
(spanning-start (progn
(goto-char (- start 1))
(point-marker)))
(spanning-end (progn
(goto-char (+ end 1))
(point-marker)))
(space-to-restore (buffer-substring start end)))
(delete-region start end)
(let ((spanning-string (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))))
(multi-line-respace-one (oref respacer respacer) index candidates)
(when (equal (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))
spanning-string)
(goto-char (marker-position startm))
(insert space-to-restore))))))
(defun multi-line-restoring-reindenting-respacer (respacer)
(multi-line-reindenting-respacer
(multi-line-space-restoring-respacer :respacer respacer)))
(provide 'multi-line-decorator)
;;; multi-line-decorator.el ends here
| 36373 | ;;; multi-line-decorator.el --- multi-line statements -*- lexical-binding: t; -*-
;; Copyright (C) 2015-2016 <NAME>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; multi-line-decorator defines a collection of decorator respacers
;; that can be used to add behavior to existing respacers.
;;; Code:
(require 'eieio)
(require 'shut-up)
(require 'multi-line-candidate)
(require 'multi-line-respace)
(require 'multi-line-shared)
(put 'multi-line-pre-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-all-decorator 'lisp-indent-function 'defun)
(defmacro multi-line-compose (name &rest funcs)
"Build a new function with NAME that is the composition of FUNCS."
`(defun ,name (arg)
(multi-line-compose-helper ,funcs)))
(defmacro multi-line-compose-helper (funcs)
"Builds funcalls of FUNCS applied to the arg."
(if (equal (length funcs) 0)
(quote arg)
`(funcall ,(car funcs) (multi-line-compose-helper ,(cdr funcs)))))
;; TODO: Get rid of inheritance here
(defclass multi-line-each-decorator (multi-line-respacer)
((respacer :initarg :respacer)
(decorator :initarg :decorator)))
(defmethod multi-line-respace-one ((decorator multi-line-each-decorator)
index candidates)
(funcall (oref decorator decorator) (oref decorator respacer) index
candidates))
(defmacro multi-line-pre-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS before each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (decorated-respacer)
(make-instance 'multi-line-each-decorator
:respacer decorated-respacer
:decorator (lambda (respacer index candidates)
,@forms
(multi-line-respace-one respacer index candidates)))))
(defmacro multi-line-post-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (respacer)
(make-instance 'multi-line-each-decorator
:respacer respacer
:decorator (lambda (respacer index candidates)
(multi-line-respace-one respacer index candidates)
,@forms))))
(defmacro multi-line-post-all-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after all respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(multi-line-post-decorator
,name (when (equal index (- (length candidates) 1))
(goto-char (multi-line-candidate-position (car (last candidates))))
,@forms)))
(multi-line-pre-decorator multi-line-space-clearing-respacer
(multi-line-clear-whitespace-at-point))
(multi-line-post-all-decorator multi-line-trailing-comma-respacer
(multi-line-add-remove-or-leave-final-comma))
(multi-line-post-decorator
multi-line-reindenting-respacer
(shut-up
(indent-region (multi-line-candidate-position (car candidates))
(multi-line-candidate-position (car (last candidates))))))
(multi-line-compose multi-line-clearing-reindenting-respacer
'multi-line-reindenting-respacer
'multi-line-space-clearing-respacer)
(defclass multi-line-space-restoring-respacer ()
((respacer :initarg :respacer)))
(defmethod multi-line-respace-one ((respacer multi-line-space-restoring-respacer)
index candidates)
(cl-destructuring-bind (startm . endm) (multi-line-space-markers)
(let* ((start (marker-position startm))
(end (marker-position endm))
(spanning-start (progn
(goto-char (- start 1))
(point-marker)))
(spanning-end (progn
(goto-char (+ end 1))
(point-marker)))
(space-to-restore (buffer-substring start end)))
(delete-region start end)
(let ((spanning-string (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))))
(multi-line-respace-one (oref respacer respacer) index candidates)
(when (equal (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))
spanning-string)
(goto-char (marker-position startm))
(insert space-to-restore))))))
(defun multi-line-restoring-reindenting-respacer (respacer)
(multi-line-reindenting-respacer
(multi-line-space-restoring-respacer :respacer respacer)))
(provide 'multi-line-decorator)
;;; multi-line-decorator.el ends here
| true | ;;; multi-line-decorator.el --- multi-line statements -*- lexical-binding: t; -*-
;; Copyright (C) 2015-2016 PI:NAME:<NAME>END_PI
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; multi-line-decorator defines a collection of decorator respacers
;; that can be used to add behavior to existing respacers.
;;; Code:
(require 'eieio)
(require 'shut-up)
(require 'multi-line-candidate)
(require 'multi-line-respace)
(require 'multi-line-shared)
(put 'multi-line-pre-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-decorator 'lisp-indent-function 'defun)
(put 'multi-line-post-all-decorator 'lisp-indent-function 'defun)
(defmacro multi-line-compose (name &rest funcs)
"Build a new function with NAME that is the composition of FUNCS."
`(defun ,name (arg)
(multi-line-compose-helper ,funcs)))
(defmacro multi-line-compose-helper (funcs)
"Builds funcalls of FUNCS applied to the arg."
(if (equal (length funcs) 0)
(quote arg)
`(funcall ,(car funcs) (multi-line-compose-helper ,(cdr funcs)))))
;; TODO: Get rid of inheritance here
(defclass multi-line-each-decorator (multi-line-respacer)
((respacer :initarg :respacer)
(decorator :initarg :decorator)))
(defmethod multi-line-respace-one ((decorator multi-line-each-decorator)
index candidates)
(funcall (oref decorator decorator) (oref decorator respacer) index
candidates))
(defmacro multi-line-pre-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS before each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (decorated-respacer)
(make-instance 'multi-line-each-decorator
:respacer decorated-respacer
:decorator (lambda (respacer index candidates)
,@forms
(multi-line-respace-one respacer index candidates)))))
(defmacro multi-line-post-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after each respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(defun ,name (respacer)
(make-instance 'multi-line-each-decorator
:respacer respacer
:decorator (lambda (respacer index candidates)
(multi-line-respace-one respacer index candidates)
,@forms))))
(defmacro multi-line-post-all-decorator (name &rest forms)
"Build respacer decorator NAME that execute FORMS after all respacing.
FORMS can use the variables index and candidates which will be
appropriately populated by the executor."
`(multi-line-post-decorator
,name (when (equal index (- (length candidates) 1))
(goto-char (multi-line-candidate-position (car (last candidates))))
,@forms)))
(multi-line-pre-decorator multi-line-space-clearing-respacer
(multi-line-clear-whitespace-at-point))
(multi-line-post-all-decorator multi-line-trailing-comma-respacer
(multi-line-add-remove-or-leave-final-comma))
(multi-line-post-decorator
multi-line-reindenting-respacer
(shut-up
(indent-region (multi-line-candidate-position (car candidates))
(multi-line-candidate-position (car (last candidates))))))
(multi-line-compose multi-line-clearing-reindenting-respacer
'multi-line-reindenting-respacer
'multi-line-space-clearing-respacer)
(defclass multi-line-space-restoring-respacer ()
((respacer :initarg :respacer)))
(defmethod multi-line-respace-one ((respacer multi-line-space-restoring-respacer)
index candidates)
(cl-destructuring-bind (startm . endm) (multi-line-space-markers)
(let* ((start (marker-position startm))
(end (marker-position endm))
(spanning-start (progn
(goto-char (- start 1))
(point-marker)))
(spanning-end (progn
(goto-char (+ end 1))
(point-marker)))
(space-to-restore (buffer-substring start end)))
(delete-region start end)
(let ((spanning-string (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))))
(multi-line-respace-one (oref respacer respacer) index candidates)
(when (equal (buffer-substring (marker-position spanning-start)
(marker-position spanning-end))
spanning-string)
(goto-char (marker-position startm))
(insert space-to-restore))))))
(defun multi-line-restoring-reindenting-respacer (respacer)
(multi-line-reindenting-respacer
(multi-line-space-restoring-respacer :respacer respacer)))
(provide 'multi-line-decorator)
;;; multi-line-decorator.el ends here
|
[
{
"context": " -*- lexical-binding: t -*-\n\n;; Copyright (C) 2016 Radon Rosborough\n\n;; Author: Radon Rosborough <radon.neon@gmail.co",
"end": 110,
"score": 0.9998987317085266,
"start": 94,
"tag": "NAME",
"value": "Radon Rosborough"
},
{
"context": ";; Copyright (C) 2016 Radon Rosborough\n\n;; Author: Radon Rosborough <radon.neon@gmail.com>\n;; Created: 31 Dec 2016\n;;",
"end": 139,
"score": 0.9999032020568848,
"start": 123,
"tag": "NAME",
"value": "Radon Rosborough"
},
{
"context": "16 Radon Rosborough\n\n;; Author: Radon Rosborough <radon.neon@gmail.com>\n;; Created: 31 Dec 2016\n;; Homepage: https://git",
"end": 161,
"score": 0.999925434589386,
"start": 141,
"tag": "EMAIL",
"value": "radon.neon@gmail.com"
},
{
"context": "ated: 31 Dec 2016\n;; Homepage: https://github.com/raxod502/el-patch\n;; Keywords: extensions\n;; Package-Requi",
"end": 227,
"score": 0.9978021383285522,
"start": 219,
"tag": "USERNAME",
"value": "raxod502"
},
{
"context": "the definition.\n\n;; Please see https://github.com/raxod502/el-patch for more\n;; information.\n\n;;; Code:\n\n;; ",
"end": 1679,
"score": 0.9811722636222839,
"start": 1671,
"tag": "USERNAME",
"value": "raxod502"
},
{
"context": "link '(url-link :tag \"GitHub\" \"https://github.com/raxod502/el-patch\")\n :link '(emacs-commentary-link :tag \"",
"end": 2393,
"score": 0.9993468523025513,
"start": 2385,
"tag": "USERNAME",
"value": "raxod502"
}
] | el-patch.el | jellelicht/el-patch | 0 | ;;; el-patch.el --- Future-proof your Elisp -*- lexical-binding: t -*-
;; Copyright (C) 2016 Radon Rosborough
;; Author: Radon Rosborough <radon.neon@gmail.com>
;; Created: 31 Dec 2016
;; Homepage: https://github.com/raxod502/el-patch
;; Keywords: extensions
;; Package-Requires: ((emacs "25"))
;; SPDX-License-Identifier: MIT
;; Version: 2.3.1
;;; Commentary:
;; el-patch allows you to override Emacs Lisp functions in a
;; future-proof way. Specifically, you can override a function by
;; providing an s-expression-based "patch", from which the "original"
;; and "modified" definitions can both be computed -- just like a Git
;; patch.
;; The "modified" definition is what is actually evaluated in your
;; init-file, but at any time you can ask el-patch to look up the
;; actual definition of the function and compare it to the patch's
;; "original" definition. If there is a difference -- meaning that the
;; original function definition was updated since you created the
;; patch -- el-patch will show you with Ediff. This means you know
;; when you might need to update your customizations (this is the
;; future-proof part).
;; el-patch also provides a powerful mechanism to help you lazy-load
;; packages. If you want to use a function from a package without
;; triggering its autoload (for instance, activating a minor mode or
;; defining keybindings), you can just copy its definition to your
;; init-file and declare it as a patch. Then you can freely use the
;; function, but you will still be notified of updates to the original
;; definition by el-patch so you will know when to update your copy of
;; the definition.
;; Please see https://github.com/raxod502/el-patch for more
;; information.
;;; Code:
;; To see the outline of this file, run M-x outline-minor-mode and
;; then press C-c @ C-t. To also show the top-level functions and
;; variable declarations in each section, run M-x occur with the
;; following query: ^;;;;* \|^(
;;;; Libraries
(require 'seq)
(require 'subr-x)
(require 'cl-lib)
(defvar use-package-keywords)
(declare-function use-package-normalize-forms "use-package")
(declare-function use-package-process-keywords "use-package")
;;;; User-facing variables
;;;###autoload
(defgroup el-patch nil
"Future-proof your Emacs Lisp customizations!"
:prefix "el-patch-"
:group 'lisp
:link '(url-link :tag "GitHub" "https://github.com/raxod502/el-patch")
:link '(emacs-commentary-link :tag "Commentary" "el-patch"))
(defcustom el-patch-use-aggressive-defvar nil
"When patching `defvar' or similar, override existing values.
This means that `el-patch-defvar', `el-patch-defconst', and
`el-patch-defcustom' will unbind the old variable definition
before evaluating the new one."
:type 'boolean)
(defcustom el-patch-require-function #'require
"Function to `require' a feature in `el-patch-pre-validate-hook'.
This is passed all of the arguments of `el-patch-feature' as
quoted literals, and it should load the feature. This function
might be useful if, for example, some of your features are
provided by lazy-installed packages, and those packages need to
be installed before the features can be loaded."
:type 'function)
(defcustom el-patch-deftype-alist nil
"Alist of types of definitions that can be patched with `el-patch'.
The keys are definition types, like `defun', `define-minor-mode',
etc. The values are plists; the following keywords are accepted:
`:classify' - a function which may be called with a full
definition form (a list starting with e.g. `defun') and which
returns an alist detailing what it defines. In this alist, the
keys are symbols; only the values `function' and `variable' are
allowed. The values are names of functions and variables,
respectively, that are defined by the definition form. This
argument is mandatory.
`:locate' - a function which may be called with a full definition
form (a list starting with e.g. `defun') and which returns the
actual source code of the definition, as a list. If the patch
correct and up to date, then this will actually be the same as
the definition which was passed in. This argument is optional,
but required if you want patch validation to work.
`:declare' - a list to be put in a `declare' form of the
resulting `el-patch' macro, like:
((doc-string 2) (indent defun))
This argument is optional.
`:macro-name' - normally the name of the macro generated for
patching a `defun' is called `el-patch-defun', but you can
override that by providing this argument. This argument is
optional."
:type '(alist
:key-type symbol
:value-type (plist
:key-type (choice
(const :classify)
(const :locate)
(const :declare)
(const :macro-name))
:value-type sexp)))
(defcustom el-patch-enable-use-package-integration t
"Non-nil means to automatically enable `use-package' integration.
This variable has an effect only when the `el-patch' library is
loaded. You can toggle the `use-package' integration later using
\\[el-patch-use-package-mode]."
:type 'boolean)
;;;; Internal variables
(defvar el-patch--patches (make-hash-table :test 'equal)
"Hash table of patches that have been defined.
The keys are symbols naming the objects that have been patched.
The values are hash tables mapping definition types (symbols
`defun', `defmacro', etc.) to patch definitions, which are lists
beginning with `defun', `defmacro', etc.
Note that the symbols are from the versions of patches that have
been resolved in favor of the modified version, when a patch
renames a symbol.")
(defvar el-patch--not-present (make-symbol "el-patch--not-present")
"Value used as a default argument to `gethash'.")
;;;; Resolving patches
(defmacro el-patch--with-puthash (table kvs &rest body)
"Bind variables in hash TABLE according to KVS then eval BODY.
Each of the KVS is a list whose first element is the key and
whose second element is the value. After BODY is evaluated, the
original state of TABLE is restored. Return value is the result
of evaluating the last form in BODY."
(declare (indent 2))
`(let* ((table ,table)
(kvs ,kvs)
(original-kvs (mapcar (lambda (kv)
(list (car kv)
(gethash (cadr kv) table
el-patch--not-present)))
kvs)))
(prog2
(dolist (kv kvs)
(puthash (car kv) (cadr kv) table))
(progn ,@body)
(dolist (kv original-kvs)
;; Note that we can't distinguish between a missing value and
;; a value that is coincidentally equal to
;; `el-patch--not-present', due to limitations in the Emacs
;; Lisp hash table API.
(if (eq (car kv) el-patch--not-present)
(remhash (car kv) table)
(puthash (car kv) (cadr kv) table))))))
(defun el-patch--copy-semitree (tree)
"Copy the list TREE, and return the copy. The list may be improper.
This function lives halfway between `copy-sequence' and
`copy-tree', since it only recurses into cdrs."
(if (consp tree)
(cons (car tree) (el-patch--copy-semitree (cdr tree)))
tree))
(defun el-patch--resolve (form new &optional table)
"Resolve a patch FORM.
Return a list of forms to be spliced into the surrounding
s-expression. Resolve in favor of the original version if NEW is
nil; otherwise resolve in favor of the new version. TABLE is a
hash table of `el-patch-let' bindings, which maps symbols to
their bindings."
(let ((table (or table (make-hash-table :test 'equal))))
(cond
((consp form)
(let* ((directive (car form))
(this-directive (pcase directive
('el-patch-remove 'el-patch-add)
('el-patch-splice 'el-patch-wrap)
(_ directive)))
(inverted (not (equal this-directive directive)))
(this-new (if inverted (not new) new))
(resolve (lambda (form) (el-patch--resolve form new table))))
(pcase this-directive
((quote el-patch-add)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
(when this-new
(cl-mapcan resolve (cdr form))))
((quote el-patch-swap)
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-swap'"
(1- (length form))))
((>= (length form) 4)
(error "Too many arguments (%d) in for `el-patch-swap'"
(1- (length form)))))
(funcall resolve
(if this-new
(cl-caddr form)
(cadr form))))
((quote el-patch-wrap)
(let ((triml (if (>= (length form) 3)
(nth 1 form)
0))
(trimr (if (>= (length form) 4)
(nth 2 form)
0))
(body (car (last form))))
(cond
((<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
((>= (length form) 5)
(error "Too many arguments (%d) for `%s'"
(1- (length form)) directive))
((not (listp body))
(error "Non-list (%s) as last argument for `%s'"
(car (last form)) directive))
((and (>= (length form) 3)
(not (integerp triml)))
(error "Non-integer (%s) as first argument for `%s'"
(nth 1 form) directive))
((and (>= (length form) 4)
(not (integerp trimr)))
(error "Non-integer (%s) as second argument for `%s'"
(nth 2 form) directive))
((< triml 0)
(error "Left trim less than zero (%d) for `%s'"
triml directive))
((< trimr 0)
(error "Right trim less than zero (%d) for `%s'"
trimr directive))
((> (+ triml trimr) (length body))
(error (concat "Combined trim (%d + %d) greater "
"than body length (%d) for `%s'")
triml trimr (length body) directive)))
(if this-new
(list (cl-mapcan resolve body))
(cl-mapcan resolve (nthcdr triml (butlast body trimr))))))
((quote el-patch-let)
(let ((bindings (nth 1 form))
(body (nthcdr 2 form)))
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-let'"
(1- (length form))))
((not (listp bindings))
(error "Non-list (%s) as first argument for `el-patch-let'"
bindings)))
(el-patch--with-puthash table
(mapcar
(lambda (kv)
(unless (symbolp (car kv))
(error "Non-symbol (%s) as binding for `el-patch-let'"
(car kv)))
(list (car kv)
(funcall resolve (cadr kv))))
bindings)
(cl-mapcan resolve body))))
((quote el-patch-literal)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-literal'"
(1- (length form))))
(cdr form))
((quote el-patch-concat)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-concat'"
(1- (length form))))
(list (apply #'concat (cl-mapcan resolve (cdr form)))))
(_
(let ((car-forms (funcall resolve (car form)))
(cdr-forms (funcall resolve (cdr form))))
(cond
((null car-forms) cdr-forms)
((null cdr-forms) car-forms)
(t
(let ((forms (nconc car-forms (butlast cdr-forms))))
(setf (nthcdr (length forms) forms)
(car (last cdr-forms)))
(list forms)))))))))
((vectorp form)
(list
(seq-mapcat
(lambda (subform)
(el-patch--resolve subform new table))
form
'vector)))
(t
(or
;; Copy since otherwise we may end up with the same list object
;; returned multiple times, which is not okay since lists
;; returned by this function may be modified destructively.
(el-patch--copy-semitree (gethash form table))
(list form))))))
(defun el-patch--resolve-definition (patch-definition new)
"Resolve a PATCH-DEFINITION.
PATCH-DEFINITION is a list starting with `defun', `defmacro',
etc. Return a list of the same format. Resolve in favor of the
original version if NEW is nil; otherwise resolve in favor of the
new version."
(cons (car patch-definition)
(cl-mapcan (lambda (form)
(el-patch--resolve form new))
(cdr patch-definition))))
;;;; Patch directives
;;;###autoload
(defmacro el-patch-add (&rest args)
"Patch directive for inserting forms.
In the original definition, the ARGS and their containing form
are removed. In the new definition, the ARGS are spliced into the
containing s-expression."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-add' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-remove (&rest args)
"Patch directive for removing forms.
In the original definition, the ARGS are spliced into the
containing s-expression. In the new definition, the ARGS and
their containing form are removed."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-remove' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-swap (old new)
"Patch directive for swapping forms.
In the original definition, OLD is spliced into the containing
s-expression. In the new definition, NEW is spliced instead."
(declare (indent 0))
(ignore old new)
`(error "Can't use `el-patch-swap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-wrap (&optional triml trimr args)
"Patch directive for wrapping forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS are spliced into the
containing s-expression. If TRIML is provided, the first TRIML of
the ARGS are removed first. If TRIMR is provided, the last TRIMR
are also removed. In the new definition, the ARGS and their
containing list are spliced into the containing s-expression."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-wrap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-splice (&optional triml trimr args)
"Patch directive for splicing forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS and their containing list
are spliced into the containing s-expression. In the new
definition, the ARGS are spliced into the containing
s-expression. If TRIML is provided, the first TRIML of the ARGS
are removed first. If TRIMR is provided, the last TRIMR are also
removed."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-splice' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-let (varlist &rest args)
"Patch directive for creating local el-patch bindings.
Creates local bindings according to VARLIST, then splices ARGS
into both the original and new definitions. You may bind symbols
that are also patch directives, but the bindings will not have
effect if the symbols are used at the beginning of a list (they
will act as patch directives)."
(declare (indent 1))
(ignore varlist args)
`(error "Can't use `el-patch-let' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-literal (&rest args)
"Patch directive for treating patch directives literally.
ARGS are spliced into the containing s-expression, but are not
processed further by el-patch."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-literal' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-concat (&rest args)
"Patch directive for modifying string literals.
ARGS should resolve to strings; those strings are passed to
`concat' and spliced into the containing s-expression in both the
original and new definitions."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-concat' outside of an `el-patch'"))
;;;; Applying patches
(defmacro el-patch--stealthy-eval (definition &optional docstring-note)
"Evaluate DEFINITION without updating `load-history'.
DEFINITION should be an unquoted list beginning with `defun',
`defmacro', `define-minor-mode', etc. DOCSTRING-NOTE, if given,
is a sentence to put in brackets at the end of the docstring."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist)))
(unless props
(error "Unregistered definition type `%S'" type))
(let* ((classify (plist-get props :classify))
(docstring-idx
(nth 1 (assq 'doc-string (plist-get props :declare)))))
(unless classify
(error
"Definition type `%S' has no `:classify' in `el-patch-deftype-alist'"
type))
(when (and docstring-note docstring-idx)
(let ((old-docstring (nth docstring-idx definition)))
(if (stringp old-docstring)
(let ((new-docstring
(concat
old-docstring
(format "\n\n[%s]" docstring-note))))
(setq definition (cl-copy-list definition))
(setf (nth docstring-idx definition)
new-docstring))
(setq definition (append
(butlast definition
(- (length definition) docstring-idx))
(cons (format "[%s]" docstring-note)
(nthcdr docstring-idx definition)))))))
(let* ((classification
(funcall classify definition))
(items
(cl-remove-if
(lambda (item)
(member item current-load-list))
(mapcar
(lambda (entry)
(pcase (car entry)
(`function (cons 'defun (cdr entry)))
(`variable (cdr entry))
(_ (error
"Unexpected classification type `%S'" (car entry)))))
classification))))
`(prog2
;; Using a `progn' here so that the `prog2' above will
;; correctly cause the evaluated definition to be
;; returned, even if `el-patch-use-aggressive-defvar' is
;; nil.
(progn
,@(when el-patch-use-aggressive-defvar
(cl-mapcan
(lambda (entry)
(when (eq (car entry) 'variable)
`((makunbound ',(cdr entry)))))
classification)))
,definition
,@(mapcar (lambda (item)
`(setq current-load-list
(remove ',item current-load-list)))
items))))))
;;;###autoload
(defmacro el-patch--definition (patch-definition)
"Activate a PATCH-DEFINITION and update `el-patch--patches'.
PATCH-DEFINITION is an unquoted list starting with `defun',
`defmacro', etc., which may contain patch directives."
;; First we resolve the patch definition in favor of the modified
;; version, because that is the version we need to activate (no
;; validation happens here).
(let ((definition (el-patch--resolve-definition patch-definition t)))
;; Then we parse out the definition type and symbol name.
(cl-destructuring-bind (type name . body) definition
`(progn
;; Register the patch in our hash. We want to do this right
;; away so that if there is an error then at least the user
;; can undo the patch (as long as it is not too terribly
;; wrong).
(let ((patches (or (bound-and-true-p el-patch--patches)
(make-hash-table :test #'equal))))
(puthash ',type
',patch-definition
(or (gethash ',name patches)
(puthash ',name
(make-hash-table :test #'equal)
patches))))
;; Now we actually overwrite the current definition.
(el-patch--stealthy-eval
,definition
"This function was patched by `el-patch'.")))))
;;;;; Removing patches
;;;###autoload
(defun el-patch-unpatch (name type)
"Remove the patch given by the PATCH-DEFINITION.
This restores the original functionality of the object being
patched. NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(eval `(el-patch--stealthy-eval
,(el-patch--resolve-definition
patch-definition nil)
"This function was patched and then unpatched by `el-patch'."))
(error "There is no patch for %S %S" type name)))
;;;; Defining patch types
;;;###autoload
(cl-defmacro el-patch-deftype
(type &rest kwargs &key classify locate declare macro-name)
"Allow `el-patch' to patch definitions of the given TYPE.
TYPE is a symbol like `defun', `define-minor-mode', etc. This
updates `el-patch-deftype-alist' (which see for explanations of
CLASSIFY, LOCATE, and DECLARE) with the provided KWARGS and
defines a macro named like `el-patch-defun',
`el-patch-define-minor-mode', etc. (which can be overridden by
MACRO-NAME)."
(declare (indent defun))
(ignore locate)
(unless classify
(error "You must specify `:classify' in calls to `el-patch-deftype'"))
`(progn
(unless (bound-and-true-p el-patch-deftype-alist)
(setq el-patch-deftype-alist nil))
(setf (alist-get ',type el-patch-deftype-alist)
;; Make sure we don't accidentally create self-modifying
;; code if somebody decides to mutate
;; `el-patch-deftype-alist'.
(copy-tree ',kwargs))
(defmacro ,(or macro-name (intern (format "el-patch-%S" type)))
(name &rest args)
,(format "Use `el-patch' to override a `%S' form.
The ARGS are the same as for `%S'."
type type)
,@(when declare
`((declare ,@declare)))
(list #'el-patch--definition (cl-list* ',type name args)))))
(put 'el-patch-deftype 'el-patch-defined-properly t)
;;;;; Classification functions
(defun el-patch-classify-variable (definition)
"Classify the items defined by a variable DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(list (cons 'variable (nth 1 definition))))
(defun el-patch-classify-function (definition)
"Classify the items defined by a function DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(list (cons 'function (nth 1 definition))))
(defun el-patch-classify-define-minor-mode (definition)
"Classify the items defined by a minor mode DEFINITION.
DEFINITION is a list starting with `define-minor-mode' or
similar."
(let* ((function-name (nth 1 definition))
(variable-name (nth 1 definition))
(kw-args (nthcdr 3 definition)))
(dotimes (_ 3)
(unless (keywordp (car kw-args))
(setq kw-args (cdr kw-args))))
(while (keywordp (car kw-args))
(when (eq (car kw-args) :variable)
(setq variable-name (car kw-args)))
(setq kw-args (nthcdr 2 kw-args)))
(list (cons 'function function-name)
(cons 'variable variable-name))))
;;;;; Location functions
(defmacro el-patch-wrap-locator (&rest body)
"Wrap the operation of `find-function-noselect' or similar.
This disables local variables and messaging, saves the current
buffer and point, etc. BODY is executed within this context. It
is assumed that BODY finds the appropriate file in a buffer using
`get-file-buffer', and then returns a cons cell with the buffer
and point for the beginning of some Lisp form. The return value
is the Lisp form, read from the buffer at point."
(declare (indent 0))
`(let* (;; Since Emacs actually opens the source file in a (hidden)
;; buffer, it can try to apply local variables, which might
;; result in an annoying interactive prompt. Let's disable
;; that.
(enable-local-variables nil)
(enable-dir-local-variables nil)
;; This is supposed to be noninteractive so we also suppress
;; all the messages. This has the side effect of masking all
;; debugging messages (you can use `insert' instead, or
;; temporarily remove these bindings), but there are just so
;; many different messages that can happen for various
;; reasons and I haven't found any other standard way to
;; suppress them.
(inhibit-message t)
(message-log-max nil)
;; Now we actually execute BODY to move point to the right
;; file and location.
(buffer-point (save-excursion
;; This horrifying bit of hackery on
;; `get-file-buffer' prevents
;; `find-function-noselect' from returning
;; an existing buffer, so that later on when
;; we jump to the definition, we don't
;; temporarily scroll the window if the
;; definition happens to be in the *current*
;; buffer.
(cl-letf (((symbol-function #'get-file-buffer)
#'ignore))
;; Because we get an error if the function
;; doesn't have a definition anywhere.
(ignore-errors
,@body))))
(defun-buffer (car buffer-point))
(defun-point (cdr buffer-point)))
(prog1 (and defun-buffer
defun-point
(with-current-buffer defun-buffer
(save-excursion
(goto-char defun-point)
(read (current-buffer)))))
(when defun-buffer
(kill-buffer defun-buffer)))))
(defun el-patch-locate-variable (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(el-patch-wrap-locator
(find-variable-noselect (nth 1 definition))))
(defun el-patch-locate-function (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(el-patch-wrap-locator
(find-function-noselect (nth 1 definition) 'lisp-only)))
;;;;; Predefined patch types
;;;###autoload(require 'el-patch-stub)
;;;###autoload(el-patch--deftype-stub-setup)
;; These are alphabetized.
;;;###autoload
(el-patch-deftype cl-defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defconst
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defcustom
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype define-minor-mode
:classify el-patch-classify-define-minor-mode
:locate el-patch-locate-function
:declare ((doc-string 2)
(indent defun)))
;;;###autoload
(el-patch-deftype defmacro
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defsubst
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defvar
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;; Validating patches
(defcustom el-patch-pre-validate-hook nil
"Hook run before `el-patch-validate-all'.
Also run before `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that make sure all
of your patches are defined (for example, you might need to load
some features if your patches are lazily defined)."
:type 'hook)
(defcustom el-patch-post-validate-hook nil
"Hook run after `el-patch-validate-all'.
Also run after `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that undo any
patching that might have taken place in
`el-patch-pre-validate-hook', if you do not want the patches to
be defined permanently."
:type 'hook)
(defun el-patch--locate (definition)
"Return the Lisp form corresponding to the given DEFINITION.
Return nil if such a definition cannot be found. (That would
happen if the definition were generated dynamically.) TYPE is a
symbol `defun', `defmacro', etc. which is used to determine
whether the symbol is a function or variable."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist))
(locator (plist-get props :locate)))
(unless locator
(error
"Definition type `%S' has no `:locate' in `el-patch-deftype-alist'"
type))
(funcall locator definition)))
;;;###autoload
(defun el-patch-validate (name type &optional nomsg run-hooks)
"Validate the patch with given NAME and TYPE.
This means el-patch will attempt to find the original definition
for the function, and verify that it is the same as the original
function assumed by the patch. A warning will be signaled if the
original definition for a patched function cannot be found, or if
there is a difference between the actual and expected original
definitions.
Interactively, use `completing-read' to select a function to
inspect the patch of.
NAME is a symbol naming the object being patched; TYPE is a
symbol `defun', `defmacro', etc.
Returns nil if the patch is not valid, and otherwise returns t.
If NOMSG is non-nil, does not signal a message when the patch is
valid.
If RUN-HOOKS is non-nil, runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'. Interactively, this happens unless
a prefix argument is provided.
See also `el-patch-validate-all'."
(interactive (progn
(unless current-prefix-arg
(run-hooks 'el-patch-pre-validate-hook))
(append (el-patch--select-patch)
(list nil (unless current-prefix-arg
'post-only)))))
(unless (member run-hooks '(nil post-only))
(run-hooks 'el-patch-pre-validate-hook))
(unwind-protect
(progn
(let* ((patch-definition (el-patch-get name type))
(type (car patch-definition))
(expected-definition (el-patch--resolve-definition
patch-definition nil))
(name (cadr expected-definition))
(actual-definition (el-patch--locate expected-definition)))
(cond
((not actual-definition)
(display-warning
'el-patch
(format "Could not find definition of %S `%S'" type name))
nil)
((not (equal expected-definition actual-definition))
(display-warning
'el-patch
(format (concat "Definition of %S `%S' differs from what "
"is assumed by its patch")
type name))
nil)
(t
(unless nomsg
(message "Patch is valid"))
t))))
(when run-hooks
(run-hooks 'el-patch-post-validate-hook))))
;;;###autoload
(defun el-patch-validate-all ()
"Validate all currently defined patches.
Runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'.
See `el-patch-validate'."
(interactive)
(run-hooks 'el-patch-pre-validate-hook)
(unwind-protect
(let ((patch-count 0)
(warning-count 0))
(dolist (name (hash-table-keys el-patch--patches))
(let ((patch-hash (gethash name el-patch--patches)))
(dolist (type (hash-table-keys patch-hash))
(setq patch-count (1+ patch-count))
(unless (el-patch-validate name type 'nomsg)
(setq warning-count (1+ warning-count))))))
(cond
((zerop patch-count)
(user-error "No patches defined"))
((zerop warning-count)
(if (= patch-count 1)
(message "Patch is valid (only one defined)")
(message "All %d patches are valid" patch-count)))
((= patch-count warning-count)
(if (= patch-count 1)
(message "Patch is invalid (only one defined)")
(message "All %d patches are invalid" patch-count)))
(t
(message "%s valid, %s invalid"
(if (= warning-count (1- patch-count))
"1 patch is"
(format "%d patches are" (- patch-count warning-count)))
(if (= warning-count 1)
"1 patch is"
(format "%d patches are" warning-count))))))
(run-hooks 'el-patch-post-validate-hook)))
;;;;; el-patch-feature
;;;###autoload
(defmacro el-patch-feature (feature &rest args)
"Declare that some patches are only defined after FEATURE is loaded.
This is a convenience macro that creates a function for invoking
`require' on that feature, and then adds it to
`el-patch-pre-validate-hook' so that your patches are loaded and
`el-patch' can properly validate them.
FEATURE should be an unquoted symbol. ARGS, if given, are passed
as quoted literals along with FEATURE to
`el-patch-require-function' when `el-patch-validate-all' is
called."
(let ((defun-name (intern (format "el-patch-require-%S" feature))))
`(progn
(defun ,defun-name ()
(apply el-patch-require-function ',feature ',args))
(add-hook 'el-patch-pre-validate-hook #',defun-name))))
;;;; Viewing patches
;;;###autoload
(defun el-patch-get (name type)
"Return the patch for object NAME of the given TYPE.
NAME is a symbol for the name of the definition that was patched,
and TYPE is a symbol `defun', `defmacro', etc. If the patch could
not be found, return nil."
(condition-case nil
(gethash type (gethash name el-patch--patches))
(error nil)))
(defun el-patch--select-patch ()
"Use `completing-read' to select a patched function.
Return a list of two elements, the name (a symbol) of the object
being patched and the type (a symbol `defun', `defmacro', etc.)
of the definition."
(let ((options (mapcar #'symbol-name (hash-table-keys el-patch--patches))))
(unless options
(user-error "No patches defined"))
(let* ((name (intern (completing-read
"Which patch? "
options
nil
'require-match)))
(patch-hash (gethash name el-patch--patches))
(options (mapcar #'symbol-name
(hash-table-keys patch-hash))))
(list name
(intern (pcase (length options)
(0 (error "Internal `el-patch' error"))
(1 (car options))
(_ (completing-read
"Which version? "
options
nil
'require-match))))))))
(defun el-patch--ediff-forms (name1 form1 name2 form2)
"Ediff two forms.
Obtain and empty buffer named NAME1 and pretty-print FORM1 into
it. Do the same for NAME2 and FORM2, and then run Ediff on the
two buffers wordwise."
(let (min1 max1 min2 max2)
(with-current-buffer (get-buffer-create name1)
(erase-buffer)
(emacs-lisp-mode)
(pp form1 (current-buffer))
(setq min1 (point-min)
max1 (point-max)))
(with-current-buffer (get-buffer-create name2)
(erase-buffer)
(emacs-lisp-mode)
(pp form2 (current-buffer))
(setq min2 (point-min)
max2 (point-max)))
;; Ugly hack because Ediff is missing an `ediff-buffers-wordwise'
;; function.
(eval-and-compile
(require 'ediff))
(ediff-regions-internal
(get-buffer name1) min1 max1
(get-buffer name2) min2 max2
nil 'ediff-regions-wordwise 'word-mode nil)))
;;;###autoload
(defun el-patch-ediff-patch (name type)
"Show the patch for an object in Ediff.
NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((old-definition (el-patch--resolve-definition
patch-definition nil))
(new-definition (el-patch--resolve-definition
patch-definition t)))
(el-patch--ediff-forms
"*el-patch original*" old-definition
"*el-patch patched*" new-definition)
(when (equal old-definition new-definition)
(message "No patch")))
(error "There is no patch for %S %S" type name)))
;;;###autoload
(defun el-patch-ediff-conflict (name type)
"Show a patch conflict in Ediff.
This is a diff between the expected and actual values of a
patch's original definition. NAME and TYPE are as returned by
`el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((expected-definition (el-patch--resolve-definition
patch-definition nil))
(actual-definition (el-patch--locate expected-definition)))
(el-patch--ediff-forms
"*el-patch actual*" actual-definition
"*el-patch expected*" expected-definition)
(when (equal actual-definition expected-definition)
(message "No conflict")))
(error "There is no patch for %S %S" type name)))
;;;; use-package integration
(defun el-patch--use-package-handler
(base-keyword name _keyword args rest state)
"When applied partially, return a `use-package' handler.
BASE-KEYWORD is either `:init' or `:config'. The remaining
arguments NAME, KEYWORD, ARGS, REST, and STATE are explained by
the `use-package' documentation."
(setq rest
(plist-put
rest base-keyword
(append
(mapcar
(lambda (arg)
(if (and (consp arg)
(assq (car arg) el-patch-deftype-alist))
(cons (or
(plist-get
(alist-get (car arg) el-patch-deftype-alist)
:macro-name)
(intern (format "el-patch-%S" (car arg))))
(cdr arg))
arg))
args)
(plist-get rest base-keyword))))
(setq rest
(plist-put
rest :init
(cons `(el-patch-feature ,name)
(plist-get rest :init))))
(use-package-process-keywords name rest state))
(define-minor-mode el-patch-use-package-mode
"Minor mode to enable `use-package' integration for `el-patch'.
This mode is enabled or disabled automatically when the
`el-patch' library is loaded, according to the value of
`el-patch-enable-use-package-integration'."
:global t
:group 'el-patch
(if el-patch-use-package-mode
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(cl-pushnew kw use-package-keywords))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch))
(defalias fun #'use-package-normalize-forms))
(defalias 'use-package-handler/:init/el-patch
(apply-partially #'el-patch--use-package-handler :init))
(defalias 'use-package-handler/:config/el-patch
(apply-partially #'el-patch--use-package-handler :config)))
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(setq use-package-keywords (delq kw use-package-keywords)))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch
use-package-handler/:init/el-patch
use-package-handler/:config/el-patch))
(fmakunbound fun)))))
(if el-patch-enable-use-package-integration
(el-patch-use-package-mode +1)
(el-patch-use-package-mode -1))
;;;; Closing remarks
(provide 'el-patch)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; el-patch.el ends here
| 27120 | ;;; el-patch.el --- Future-proof your Elisp -*- lexical-binding: t -*-
;; Copyright (C) 2016 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Created: 31 Dec 2016
;; Homepage: https://github.com/raxod502/el-patch
;; Keywords: extensions
;; Package-Requires: ((emacs "25"))
;; SPDX-License-Identifier: MIT
;; Version: 2.3.1
;;; Commentary:
;; el-patch allows you to override Emacs Lisp functions in a
;; future-proof way. Specifically, you can override a function by
;; providing an s-expression-based "patch", from which the "original"
;; and "modified" definitions can both be computed -- just like a Git
;; patch.
;; The "modified" definition is what is actually evaluated in your
;; init-file, but at any time you can ask el-patch to look up the
;; actual definition of the function and compare it to the patch's
;; "original" definition. If there is a difference -- meaning that the
;; original function definition was updated since you created the
;; patch -- el-patch will show you with Ediff. This means you know
;; when you might need to update your customizations (this is the
;; future-proof part).
;; el-patch also provides a powerful mechanism to help you lazy-load
;; packages. If you want to use a function from a package without
;; triggering its autoload (for instance, activating a minor mode or
;; defining keybindings), you can just copy its definition to your
;; init-file and declare it as a patch. Then you can freely use the
;; function, but you will still be notified of updates to the original
;; definition by el-patch so you will know when to update your copy of
;; the definition.
;; Please see https://github.com/raxod502/el-patch for more
;; information.
;;; Code:
;; To see the outline of this file, run M-x outline-minor-mode and
;; then press C-c @ C-t. To also show the top-level functions and
;; variable declarations in each section, run M-x occur with the
;; following query: ^;;;;* \|^(
;;;; Libraries
(require 'seq)
(require 'subr-x)
(require 'cl-lib)
(defvar use-package-keywords)
(declare-function use-package-normalize-forms "use-package")
(declare-function use-package-process-keywords "use-package")
;;;; User-facing variables
;;;###autoload
(defgroup el-patch nil
"Future-proof your Emacs Lisp customizations!"
:prefix "el-patch-"
:group 'lisp
:link '(url-link :tag "GitHub" "https://github.com/raxod502/el-patch")
:link '(emacs-commentary-link :tag "Commentary" "el-patch"))
(defcustom el-patch-use-aggressive-defvar nil
"When patching `defvar' or similar, override existing values.
This means that `el-patch-defvar', `el-patch-defconst', and
`el-patch-defcustom' will unbind the old variable definition
before evaluating the new one."
:type 'boolean)
(defcustom el-patch-require-function #'require
"Function to `require' a feature in `el-patch-pre-validate-hook'.
This is passed all of the arguments of `el-patch-feature' as
quoted literals, and it should load the feature. This function
might be useful if, for example, some of your features are
provided by lazy-installed packages, and those packages need to
be installed before the features can be loaded."
:type 'function)
(defcustom el-patch-deftype-alist nil
"Alist of types of definitions that can be patched with `el-patch'.
The keys are definition types, like `defun', `define-minor-mode',
etc. The values are plists; the following keywords are accepted:
`:classify' - a function which may be called with a full
definition form (a list starting with e.g. `defun') and which
returns an alist detailing what it defines. In this alist, the
keys are symbols; only the values `function' and `variable' are
allowed. The values are names of functions and variables,
respectively, that are defined by the definition form. This
argument is mandatory.
`:locate' - a function which may be called with a full definition
form (a list starting with e.g. `defun') and which returns the
actual source code of the definition, as a list. If the patch
correct and up to date, then this will actually be the same as
the definition which was passed in. This argument is optional,
but required if you want patch validation to work.
`:declare' - a list to be put in a `declare' form of the
resulting `el-patch' macro, like:
((doc-string 2) (indent defun))
This argument is optional.
`:macro-name' - normally the name of the macro generated for
patching a `defun' is called `el-patch-defun', but you can
override that by providing this argument. This argument is
optional."
:type '(alist
:key-type symbol
:value-type (plist
:key-type (choice
(const :classify)
(const :locate)
(const :declare)
(const :macro-name))
:value-type sexp)))
(defcustom el-patch-enable-use-package-integration t
"Non-nil means to automatically enable `use-package' integration.
This variable has an effect only when the `el-patch' library is
loaded. You can toggle the `use-package' integration later using
\\[el-patch-use-package-mode]."
:type 'boolean)
;;;; Internal variables
(defvar el-patch--patches (make-hash-table :test 'equal)
"Hash table of patches that have been defined.
The keys are symbols naming the objects that have been patched.
The values are hash tables mapping definition types (symbols
`defun', `defmacro', etc.) to patch definitions, which are lists
beginning with `defun', `defmacro', etc.
Note that the symbols are from the versions of patches that have
been resolved in favor of the modified version, when a patch
renames a symbol.")
(defvar el-patch--not-present (make-symbol "el-patch--not-present")
"Value used as a default argument to `gethash'.")
;;;; Resolving patches
(defmacro el-patch--with-puthash (table kvs &rest body)
"Bind variables in hash TABLE according to KVS then eval BODY.
Each of the KVS is a list whose first element is the key and
whose second element is the value. After BODY is evaluated, the
original state of TABLE is restored. Return value is the result
of evaluating the last form in BODY."
(declare (indent 2))
`(let* ((table ,table)
(kvs ,kvs)
(original-kvs (mapcar (lambda (kv)
(list (car kv)
(gethash (cadr kv) table
el-patch--not-present)))
kvs)))
(prog2
(dolist (kv kvs)
(puthash (car kv) (cadr kv) table))
(progn ,@body)
(dolist (kv original-kvs)
;; Note that we can't distinguish between a missing value and
;; a value that is coincidentally equal to
;; `el-patch--not-present', due to limitations in the Emacs
;; Lisp hash table API.
(if (eq (car kv) el-patch--not-present)
(remhash (car kv) table)
(puthash (car kv) (cadr kv) table))))))
(defun el-patch--copy-semitree (tree)
"Copy the list TREE, and return the copy. The list may be improper.
This function lives halfway between `copy-sequence' and
`copy-tree', since it only recurses into cdrs."
(if (consp tree)
(cons (car tree) (el-patch--copy-semitree (cdr tree)))
tree))
(defun el-patch--resolve (form new &optional table)
"Resolve a patch FORM.
Return a list of forms to be spliced into the surrounding
s-expression. Resolve in favor of the original version if NEW is
nil; otherwise resolve in favor of the new version. TABLE is a
hash table of `el-patch-let' bindings, which maps symbols to
their bindings."
(let ((table (or table (make-hash-table :test 'equal))))
(cond
((consp form)
(let* ((directive (car form))
(this-directive (pcase directive
('el-patch-remove 'el-patch-add)
('el-patch-splice 'el-patch-wrap)
(_ directive)))
(inverted (not (equal this-directive directive)))
(this-new (if inverted (not new) new))
(resolve (lambda (form) (el-patch--resolve form new table))))
(pcase this-directive
((quote el-patch-add)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
(when this-new
(cl-mapcan resolve (cdr form))))
((quote el-patch-swap)
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-swap'"
(1- (length form))))
((>= (length form) 4)
(error "Too many arguments (%d) in for `el-patch-swap'"
(1- (length form)))))
(funcall resolve
(if this-new
(cl-caddr form)
(cadr form))))
((quote el-patch-wrap)
(let ((triml (if (>= (length form) 3)
(nth 1 form)
0))
(trimr (if (>= (length form) 4)
(nth 2 form)
0))
(body (car (last form))))
(cond
((<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
((>= (length form) 5)
(error "Too many arguments (%d) for `%s'"
(1- (length form)) directive))
((not (listp body))
(error "Non-list (%s) as last argument for `%s'"
(car (last form)) directive))
((and (>= (length form) 3)
(not (integerp triml)))
(error "Non-integer (%s) as first argument for `%s'"
(nth 1 form) directive))
((and (>= (length form) 4)
(not (integerp trimr)))
(error "Non-integer (%s) as second argument for `%s'"
(nth 2 form) directive))
((< triml 0)
(error "Left trim less than zero (%d) for `%s'"
triml directive))
((< trimr 0)
(error "Right trim less than zero (%d) for `%s'"
trimr directive))
((> (+ triml trimr) (length body))
(error (concat "Combined trim (%d + %d) greater "
"than body length (%d) for `%s'")
triml trimr (length body) directive)))
(if this-new
(list (cl-mapcan resolve body))
(cl-mapcan resolve (nthcdr triml (butlast body trimr))))))
((quote el-patch-let)
(let ((bindings (nth 1 form))
(body (nthcdr 2 form)))
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-let'"
(1- (length form))))
((not (listp bindings))
(error "Non-list (%s) as first argument for `el-patch-let'"
bindings)))
(el-patch--with-puthash table
(mapcar
(lambda (kv)
(unless (symbolp (car kv))
(error "Non-symbol (%s) as binding for `el-patch-let'"
(car kv)))
(list (car kv)
(funcall resolve (cadr kv))))
bindings)
(cl-mapcan resolve body))))
((quote el-patch-literal)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-literal'"
(1- (length form))))
(cdr form))
((quote el-patch-concat)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-concat'"
(1- (length form))))
(list (apply #'concat (cl-mapcan resolve (cdr form)))))
(_
(let ((car-forms (funcall resolve (car form)))
(cdr-forms (funcall resolve (cdr form))))
(cond
((null car-forms) cdr-forms)
((null cdr-forms) car-forms)
(t
(let ((forms (nconc car-forms (butlast cdr-forms))))
(setf (nthcdr (length forms) forms)
(car (last cdr-forms)))
(list forms)))))))))
((vectorp form)
(list
(seq-mapcat
(lambda (subform)
(el-patch--resolve subform new table))
form
'vector)))
(t
(or
;; Copy since otherwise we may end up with the same list object
;; returned multiple times, which is not okay since lists
;; returned by this function may be modified destructively.
(el-patch--copy-semitree (gethash form table))
(list form))))))
(defun el-patch--resolve-definition (patch-definition new)
"Resolve a PATCH-DEFINITION.
PATCH-DEFINITION is a list starting with `defun', `defmacro',
etc. Return a list of the same format. Resolve in favor of the
original version if NEW is nil; otherwise resolve in favor of the
new version."
(cons (car patch-definition)
(cl-mapcan (lambda (form)
(el-patch--resolve form new))
(cdr patch-definition))))
;;;; Patch directives
;;;###autoload
(defmacro el-patch-add (&rest args)
"Patch directive for inserting forms.
In the original definition, the ARGS and their containing form
are removed. In the new definition, the ARGS are spliced into the
containing s-expression."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-add' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-remove (&rest args)
"Patch directive for removing forms.
In the original definition, the ARGS are spliced into the
containing s-expression. In the new definition, the ARGS and
their containing form are removed."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-remove' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-swap (old new)
"Patch directive for swapping forms.
In the original definition, OLD is spliced into the containing
s-expression. In the new definition, NEW is spliced instead."
(declare (indent 0))
(ignore old new)
`(error "Can't use `el-patch-swap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-wrap (&optional triml trimr args)
"Patch directive for wrapping forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS are spliced into the
containing s-expression. If TRIML is provided, the first TRIML of
the ARGS are removed first. If TRIMR is provided, the last TRIMR
are also removed. In the new definition, the ARGS and their
containing list are spliced into the containing s-expression."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-wrap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-splice (&optional triml trimr args)
"Patch directive for splicing forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS and their containing list
are spliced into the containing s-expression. In the new
definition, the ARGS are spliced into the containing
s-expression. If TRIML is provided, the first TRIML of the ARGS
are removed first. If TRIMR is provided, the last TRIMR are also
removed."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-splice' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-let (varlist &rest args)
"Patch directive for creating local el-patch bindings.
Creates local bindings according to VARLIST, then splices ARGS
into both the original and new definitions. You may bind symbols
that are also patch directives, but the bindings will not have
effect if the symbols are used at the beginning of a list (they
will act as patch directives)."
(declare (indent 1))
(ignore varlist args)
`(error "Can't use `el-patch-let' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-literal (&rest args)
"Patch directive for treating patch directives literally.
ARGS are spliced into the containing s-expression, but are not
processed further by el-patch."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-literal' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-concat (&rest args)
"Patch directive for modifying string literals.
ARGS should resolve to strings; those strings are passed to
`concat' and spliced into the containing s-expression in both the
original and new definitions."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-concat' outside of an `el-patch'"))
;;;; Applying patches
(defmacro el-patch--stealthy-eval (definition &optional docstring-note)
"Evaluate DEFINITION without updating `load-history'.
DEFINITION should be an unquoted list beginning with `defun',
`defmacro', `define-minor-mode', etc. DOCSTRING-NOTE, if given,
is a sentence to put in brackets at the end of the docstring."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist)))
(unless props
(error "Unregistered definition type `%S'" type))
(let* ((classify (plist-get props :classify))
(docstring-idx
(nth 1 (assq 'doc-string (plist-get props :declare)))))
(unless classify
(error
"Definition type `%S' has no `:classify' in `el-patch-deftype-alist'"
type))
(when (and docstring-note docstring-idx)
(let ((old-docstring (nth docstring-idx definition)))
(if (stringp old-docstring)
(let ((new-docstring
(concat
old-docstring
(format "\n\n[%s]" docstring-note))))
(setq definition (cl-copy-list definition))
(setf (nth docstring-idx definition)
new-docstring))
(setq definition (append
(butlast definition
(- (length definition) docstring-idx))
(cons (format "[%s]" docstring-note)
(nthcdr docstring-idx definition)))))))
(let* ((classification
(funcall classify definition))
(items
(cl-remove-if
(lambda (item)
(member item current-load-list))
(mapcar
(lambda (entry)
(pcase (car entry)
(`function (cons 'defun (cdr entry)))
(`variable (cdr entry))
(_ (error
"Unexpected classification type `%S'" (car entry)))))
classification))))
`(prog2
;; Using a `progn' here so that the `prog2' above will
;; correctly cause the evaluated definition to be
;; returned, even if `el-patch-use-aggressive-defvar' is
;; nil.
(progn
,@(when el-patch-use-aggressive-defvar
(cl-mapcan
(lambda (entry)
(when (eq (car entry) 'variable)
`((makunbound ',(cdr entry)))))
classification)))
,definition
,@(mapcar (lambda (item)
`(setq current-load-list
(remove ',item current-load-list)))
items))))))
;;;###autoload
(defmacro el-patch--definition (patch-definition)
"Activate a PATCH-DEFINITION and update `el-patch--patches'.
PATCH-DEFINITION is an unquoted list starting with `defun',
`defmacro', etc., which may contain patch directives."
;; First we resolve the patch definition in favor of the modified
;; version, because that is the version we need to activate (no
;; validation happens here).
(let ((definition (el-patch--resolve-definition patch-definition t)))
;; Then we parse out the definition type and symbol name.
(cl-destructuring-bind (type name . body) definition
`(progn
;; Register the patch in our hash. We want to do this right
;; away so that if there is an error then at least the user
;; can undo the patch (as long as it is not too terribly
;; wrong).
(let ((patches (or (bound-and-true-p el-patch--patches)
(make-hash-table :test #'equal))))
(puthash ',type
',patch-definition
(or (gethash ',name patches)
(puthash ',name
(make-hash-table :test #'equal)
patches))))
;; Now we actually overwrite the current definition.
(el-patch--stealthy-eval
,definition
"This function was patched by `el-patch'.")))))
;;;;; Removing patches
;;;###autoload
(defun el-patch-unpatch (name type)
"Remove the patch given by the PATCH-DEFINITION.
This restores the original functionality of the object being
patched. NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(eval `(el-patch--stealthy-eval
,(el-patch--resolve-definition
patch-definition nil)
"This function was patched and then unpatched by `el-patch'."))
(error "There is no patch for %S %S" type name)))
;;;; Defining patch types
;;;###autoload
(cl-defmacro el-patch-deftype
(type &rest kwargs &key classify locate declare macro-name)
"Allow `el-patch' to patch definitions of the given TYPE.
TYPE is a symbol like `defun', `define-minor-mode', etc. This
updates `el-patch-deftype-alist' (which see for explanations of
CLASSIFY, LOCATE, and DECLARE) with the provided KWARGS and
defines a macro named like `el-patch-defun',
`el-patch-define-minor-mode', etc. (which can be overridden by
MACRO-NAME)."
(declare (indent defun))
(ignore locate)
(unless classify
(error "You must specify `:classify' in calls to `el-patch-deftype'"))
`(progn
(unless (bound-and-true-p el-patch-deftype-alist)
(setq el-patch-deftype-alist nil))
(setf (alist-get ',type el-patch-deftype-alist)
;; Make sure we don't accidentally create self-modifying
;; code if somebody decides to mutate
;; `el-patch-deftype-alist'.
(copy-tree ',kwargs))
(defmacro ,(or macro-name (intern (format "el-patch-%S" type)))
(name &rest args)
,(format "Use `el-patch' to override a `%S' form.
The ARGS are the same as for `%S'."
type type)
,@(when declare
`((declare ,@declare)))
(list #'el-patch--definition (cl-list* ',type name args)))))
(put 'el-patch-deftype 'el-patch-defined-properly t)
;;;;; Classification functions
(defun el-patch-classify-variable (definition)
"Classify the items defined by a variable DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(list (cons 'variable (nth 1 definition))))
(defun el-patch-classify-function (definition)
"Classify the items defined by a function DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(list (cons 'function (nth 1 definition))))
(defun el-patch-classify-define-minor-mode (definition)
"Classify the items defined by a minor mode DEFINITION.
DEFINITION is a list starting with `define-minor-mode' or
similar."
(let* ((function-name (nth 1 definition))
(variable-name (nth 1 definition))
(kw-args (nthcdr 3 definition)))
(dotimes (_ 3)
(unless (keywordp (car kw-args))
(setq kw-args (cdr kw-args))))
(while (keywordp (car kw-args))
(when (eq (car kw-args) :variable)
(setq variable-name (car kw-args)))
(setq kw-args (nthcdr 2 kw-args)))
(list (cons 'function function-name)
(cons 'variable variable-name))))
;;;;; Location functions
(defmacro el-patch-wrap-locator (&rest body)
"Wrap the operation of `find-function-noselect' or similar.
This disables local variables and messaging, saves the current
buffer and point, etc. BODY is executed within this context. It
is assumed that BODY finds the appropriate file in a buffer using
`get-file-buffer', and then returns a cons cell with the buffer
and point for the beginning of some Lisp form. The return value
is the Lisp form, read from the buffer at point."
(declare (indent 0))
`(let* (;; Since Emacs actually opens the source file in a (hidden)
;; buffer, it can try to apply local variables, which might
;; result in an annoying interactive prompt. Let's disable
;; that.
(enable-local-variables nil)
(enable-dir-local-variables nil)
;; This is supposed to be noninteractive so we also suppress
;; all the messages. This has the side effect of masking all
;; debugging messages (you can use `insert' instead, or
;; temporarily remove these bindings), but there are just so
;; many different messages that can happen for various
;; reasons and I haven't found any other standard way to
;; suppress them.
(inhibit-message t)
(message-log-max nil)
;; Now we actually execute BODY to move point to the right
;; file and location.
(buffer-point (save-excursion
;; This horrifying bit of hackery on
;; `get-file-buffer' prevents
;; `find-function-noselect' from returning
;; an existing buffer, so that later on when
;; we jump to the definition, we don't
;; temporarily scroll the window if the
;; definition happens to be in the *current*
;; buffer.
(cl-letf (((symbol-function #'get-file-buffer)
#'ignore))
;; Because we get an error if the function
;; doesn't have a definition anywhere.
(ignore-errors
,@body))))
(defun-buffer (car buffer-point))
(defun-point (cdr buffer-point)))
(prog1 (and defun-buffer
defun-point
(with-current-buffer defun-buffer
(save-excursion
(goto-char defun-point)
(read (current-buffer)))))
(when defun-buffer
(kill-buffer defun-buffer)))))
(defun el-patch-locate-variable (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(el-patch-wrap-locator
(find-variable-noselect (nth 1 definition))))
(defun el-patch-locate-function (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(el-patch-wrap-locator
(find-function-noselect (nth 1 definition) 'lisp-only)))
;;;;; Predefined patch types
;;;###autoload(require 'el-patch-stub)
;;;###autoload(el-patch--deftype-stub-setup)
;; These are alphabetized.
;;;###autoload
(el-patch-deftype cl-defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defconst
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defcustom
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype define-minor-mode
:classify el-patch-classify-define-minor-mode
:locate el-patch-locate-function
:declare ((doc-string 2)
(indent defun)))
;;;###autoload
(el-patch-deftype defmacro
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defsubst
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defvar
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;; Validating patches
(defcustom el-patch-pre-validate-hook nil
"Hook run before `el-patch-validate-all'.
Also run before `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that make sure all
of your patches are defined (for example, you might need to load
some features if your patches are lazily defined)."
:type 'hook)
(defcustom el-patch-post-validate-hook nil
"Hook run after `el-patch-validate-all'.
Also run after `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that undo any
patching that might have taken place in
`el-patch-pre-validate-hook', if you do not want the patches to
be defined permanently."
:type 'hook)
(defun el-patch--locate (definition)
"Return the Lisp form corresponding to the given DEFINITION.
Return nil if such a definition cannot be found. (That would
happen if the definition were generated dynamically.) TYPE is a
symbol `defun', `defmacro', etc. which is used to determine
whether the symbol is a function or variable."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist))
(locator (plist-get props :locate)))
(unless locator
(error
"Definition type `%S' has no `:locate' in `el-patch-deftype-alist'"
type))
(funcall locator definition)))
;;;###autoload
(defun el-patch-validate (name type &optional nomsg run-hooks)
"Validate the patch with given NAME and TYPE.
This means el-patch will attempt to find the original definition
for the function, and verify that it is the same as the original
function assumed by the patch. A warning will be signaled if the
original definition for a patched function cannot be found, or if
there is a difference between the actual and expected original
definitions.
Interactively, use `completing-read' to select a function to
inspect the patch of.
NAME is a symbol naming the object being patched; TYPE is a
symbol `defun', `defmacro', etc.
Returns nil if the patch is not valid, and otherwise returns t.
If NOMSG is non-nil, does not signal a message when the patch is
valid.
If RUN-HOOKS is non-nil, runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'. Interactively, this happens unless
a prefix argument is provided.
See also `el-patch-validate-all'."
(interactive (progn
(unless current-prefix-arg
(run-hooks 'el-patch-pre-validate-hook))
(append (el-patch--select-patch)
(list nil (unless current-prefix-arg
'post-only)))))
(unless (member run-hooks '(nil post-only))
(run-hooks 'el-patch-pre-validate-hook))
(unwind-protect
(progn
(let* ((patch-definition (el-patch-get name type))
(type (car patch-definition))
(expected-definition (el-patch--resolve-definition
patch-definition nil))
(name (cadr expected-definition))
(actual-definition (el-patch--locate expected-definition)))
(cond
((not actual-definition)
(display-warning
'el-patch
(format "Could not find definition of %S `%S'" type name))
nil)
((not (equal expected-definition actual-definition))
(display-warning
'el-patch
(format (concat "Definition of %S `%S' differs from what "
"is assumed by its patch")
type name))
nil)
(t
(unless nomsg
(message "Patch is valid"))
t))))
(when run-hooks
(run-hooks 'el-patch-post-validate-hook))))
;;;###autoload
(defun el-patch-validate-all ()
"Validate all currently defined patches.
Runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'.
See `el-patch-validate'."
(interactive)
(run-hooks 'el-patch-pre-validate-hook)
(unwind-protect
(let ((patch-count 0)
(warning-count 0))
(dolist (name (hash-table-keys el-patch--patches))
(let ((patch-hash (gethash name el-patch--patches)))
(dolist (type (hash-table-keys patch-hash))
(setq patch-count (1+ patch-count))
(unless (el-patch-validate name type 'nomsg)
(setq warning-count (1+ warning-count))))))
(cond
((zerop patch-count)
(user-error "No patches defined"))
((zerop warning-count)
(if (= patch-count 1)
(message "Patch is valid (only one defined)")
(message "All %d patches are valid" patch-count)))
((= patch-count warning-count)
(if (= patch-count 1)
(message "Patch is invalid (only one defined)")
(message "All %d patches are invalid" patch-count)))
(t
(message "%s valid, %s invalid"
(if (= warning-count (1- patch-count))
"1 patch is"
(format "%d patches are" (- patch-count warning-count)))
(if (= warning-count 1)
"1 patch is"
(format "%d patches are" warning-count))))))
(run-hooks 'el-patch-post-validate-hook)))
;;;;; el-patch-feature
;;;###autoload
(defmacro el-patch-feature (feature &rest args)
"Declare that some patches are only defined after FEATURE is loaded.
This is a convenience macro that creates a function for invoking
`require' on that feature, and then adds it to
`el-patch-pre-validate-hook' so that your patches are loaded and
`el-patch' can properly validate them.
FEATURE should be an unquoted symbol. ARGS, if given, are passed
as quoted literals along with FEATURE to
`el-patch-require-function' when `el-patch-validate-all' is
called."
(let ((defun-name (intern (format "el-patch-require-%S" feature))))
`(progn
(defun ,defun-name ()
(apply el-patch-require-function ',feature ',args))
(add-hook 'el-patch-pre-validate-hook #',defun-name))))
;;;; Viewing patches
;;;###autoload
(defun el-patch-get (name type)
"Return the patch for object NAME of the given TYPE.
NAME is a symbol for the name of the definition that was patched,
and TYPE is a symbol `defun', `defmacro', etc. If the patch could
not be found, return nil."
(condition-case nil
(gethash type (gethash name el-patch--patches))
(error nil)))
(defun el-patch--select-patch ()
"Use `completing-read' to select a patched function.
Return a list of two elements, the name (a symbol) of the object
being patched and the type (a symbol `defun', `defmacro', etc.)
of the definition."
(let ((options (mapcar #'symbol-name (hash-table-keys el-patch--patches))))
(unless options
(user-error "No patches defined"))
(let* ((name (intern (completing-read
"Which patch? "
options
nil
'require-match)))
(patch-hash (gethash name el-patch--patches))
(options (mapcar #'symbol-name
(hash-table-keys patch-hash))))
(list name
(intern (pcase (length options)
(0 (error "Internal `el-patch' error"))
(1 (car options))
(_ (completing-read
"Which version? "
options
nil
'require-match))))))))
(defun el-patch--ediff-forms (name1 form1 name2 form2)
"Ediff two forms.
Obtain and empty buffer named NAME1 and pretty-print FORM1 into
it. Do the same for NAME2 and FORM2, and then run Ediff on the
two buffers wordwise."
(let (min1 max1 min2 max2)
(with-current-buffer (get-buffer-create name1)
(erase-buffer)
(emacs-lisp-mode)
(pp form1 (current-buffer))
(setq min1 (point-min)
max1 (point-max)))
(with-current-buffer (get-buffer-create name2)
(erase-buffer)
(emacs-lisp-mode)
(pp form2 (current-buffer))
(setq min2 (point-min)
max2 (point-max)))
;; Ugly hack because Ediff is missing an `ediff-buffers-wordwise'
;; function.
(eval-and-compile
(require 'ediff))
(ediff-regions-internal
(get-buffer name1) min1 max1
(get-buffer name2) min2 max2
nil 'ediff-regions-wordwise 'word-mode nil)))
;;;###autoload
(defun el-patch-ediff-patch (name type)
"Show the patch for an object in Ediff.
NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((old-definition (el-patch--resolve-definition
patch-definition nil))
(new-definition (el-patch--resolve-definition
patch-definition t)))
(el-patch--ediff-forms
"*el-patch original*" old-definition
"*el-patch patched*" new-definition)
(when (equal old-definition new-definition)
(message "No patch")))
(error "There is no patch for %S %S" type name)))
;;;###autoload
(defun el-patch-ediff-conflict (name type)
"Show a patch conflict in Ediff.
This is a diff between the expected and actual values of a
patch's original definition. NAME and TYPE are as returned by
`el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((expected-definition (el-patch--resolve-definition
patch-definition nil))
(actual-definition (el-patch--locate expected-definition)))
(el-patch--ediff-forms
"*el-patch actual*" actual-definition
"*el-patch expected*" expected-definition)
(when (equal actual-definition expected-definition)
(message "No conflict")))
(error "There is no patch for %S %S" type name)))
;;;; use-package integration
(defun el-patch--use-package-handler
(base-keyword name _keyword args rest state)
"When applied partially, return a `use-package' handler.
BASE-KEYWORD is either `:init' or `:config'. The remaining
arguments NAME, KEYWORD, ARGS, REST, and STATE are explained by
the `use-package' documentation."
(setq rest
(plist-put
rest base-keyword
(append
(mapcar
(lambda (arg)
(if (and (consp arg)
(assq (car arg) el-patch-deftype-alist))
(cons (or
(plist-get
(alist-get (car arg) el-patch-deftype-alist)
:macro-name)
(intern (format "el-patch-%S" (car arg))))
(cdr arg))
arg))
args)
(plist-get rest base-keyword))))
(setq rest
(plist-put
rest :init
(cons `(el-patch-feature ,name)
(plist-get rest :init))))
(use-package-process-keywords name rest state))
(define-minor-mode el-patch-use-package-mode
"Minor mode to enable `use-package' integration for `el-patch'.
This mode is enabled or disabled automatically when the
`el-patch' library is loaded, according to the value of
`el-patch-enable-use-package-integration'."
:global t
:group 'el-patch
(if el-patch-use-package-mode
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(cl-pushnew kw use-package-keywords))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch))
(defalias fun #'use-package-normalize-forms))
(defalias 'use-package-handler/:init/el-patch
(apply-partially #'el-patch--use-package-handler :init))
(defalias 'use-package-handler/:config/el-patch
(apply-partially #'el-patch--use-package-handler :config)))
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(setq use-package-keywords (delq kw use-package-keywords)))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch
use-package-handler/:init/el-patch
use-package-handler/:config/el-patch))
(fmakunbound fun)))))
(if el-patch-enable-use-package-integration
(el-patch-use-package-mode +1)
(el-patch-use-package-mode -1))
;;;; Closing remarks
(provide 'el-patch)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; el-patch.el ends here
| true | ;;; el-patch.el --- Future-proof your Elisp -*- lexical-binding: t -*-
;; Copyright (C) 2016 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 31 Dec 2016
;; Homepage: https://github.com/raxod502/el-patch
;; Keywords: extensions
;; Package-Requires: ((emacs "25"))
;; SPDX-License-Identifier: MIT
;; Version: 2.3.1
;;; Commentary:
;; el-patch allows you to override Emacs Lisp functions in a
;; future-proof way. Specifically, you can override a function by
;; providing an s-expression-based "patch", from which the "original"
;; and "modified" definitions can both be computed -- just like a Git
;; patch.
;; The "modified" definition is what is actually evaluated in your
;; init-file, but at any time you can ask el-patch to look up the
;; actual definition of the function and compare it to the patch's
;; "original" definition. If there is a difference -- meaning that the
;; original function definition was updated since you created the
;; patch -- el-patch will show you with Ediff. This means you know
;; when you might need to update your customizations (this is the
;; future-proof part).
;; el-patch also provides a powerful mechanism to help you lazy-load
;; packages. If you want to use a function from a package without
;; triggering its autoload (for instance, activating a minor mode or
;; defining keybindings), you can just copy its definition to your
;; init-file and declare it as a patch. Then you can freely use the
;; function, but you will still be notified of updates to the original
;; definition by el-patch so you will know when to update your copy of
;; the definition.
;; Please see https://github.com/raxod502/el-patch for more
;; information.
;;; Code:
;; To see the outline of this file, run M-x outline-minor-mode and
;; then press C-c @ C-t. To also show the top-level functions and
;; variable declarations in each section, run M-x occur with the
;; following query: ^;;;;* \|^(
;;;; Libraries
(require 'seq)
(require 'subr-x)
(require 'cl-lib)
(defvar use-package-keywords)
(declare-function use-package-normalize-forms "use-package")
(declare-function use-package-process-keywords "use-package")
;;;; User-facing variables
;;;###autoload
(defgroup el-patch nil
"Future-proof your Emacs Lisp customizations!"
:prefix "el-patch-"
:group 'lisp
:link '(url-link :tag "GitHub" "https://github.com/raxod502/el-patch")
:link '(emacs-commentary-link :tag "Commentary" "el-patch"))
(defcustom el-patch-use-aggressive-defvar nil
"When patching `defvar' or similar, override existing values.
This means that `el-patch-defvar', `el-patch-defconst', and
`el-patch-defcustom' will unbind the old variable definition
before evaluating the new one."
:type 'boolean)
(defcustom el-patch-require-function #'require
"Function to `require' a feature in `el-patch-pre-validate-hook'.
This is passed all of the arguments of `el-patch-feature' as
quoted literals, and it should load the feature. This function
might be useful if, for example, some of your features are
provided by lazy-installed packages, and those packages need to
be installed before the features can be loaded."
:type 'function)
(defcustom el-patch-deftype-alist nil
"Alist of types of definitions that can be patched with `el-patch'.
The keys are definition types, like `defun', `define-minor-mode',
etc. The values are plists; the following keywords are accepted:
`:classify' - a function which may be called with a full
definition form (a list starting with e.g. `defun') and which
returns an alist detailing what it defines. In this alist, the
keys are symbols; only the values `function' and `variable' are
allowed. The values are names of functions and variables,
respectively, that are defined by the definition form. This
argument is mandatory.
`:locate' - a function which may be called with a full definition
form (a list starting with e.g. `defun') and which returns the
actual source code of the definition, as a list. If the patch
correct and up to date, then this will actually be the same as
the definition which was passed in. This argument is optional,
but required if you want patch validation to work.
`:declare' - a list to be put in a `declare' form of the
resulting `el-patch' macro, like:
((doc-string 2) (indent defun))
This argument is optional.
`:macro-name' - normally the name of the macro generated for
patching a `defun' is called `el-patch-defun', but you can
override that by providing this argument. This argument is
optional."
:type '(alist
:key-type symbol
:value-type (plist
:key-type (choice
(const :classify)
(const :locate)
(const :declare)
(const :macro-name))
:value-type sexp)))
(defcustom el-patch-enable-use-package-integration t
"Non-nil means to automatically enable `use-package' integration.
This variable has an effect only when the `el-patch' library is
loaded. You can toggle the `use-package' integration later using
\\[el-patch-use-package-mode]."
:type 'boolean)
;;;; Internal variables
(defvar el-patch--patches (make-hash-table :test 'equal)
"Hash table of patches that have been defined.
The keys are symbols naming the objects that have been patched.
The values are hash tables mapping definition types (symbols
`defun', `defmacro', etc.) to patch definitions, which are lists
beginning with `defun', `defmacro', etc.
Note that the symbols are from the versions of patches that have
been resolved in favor of the modified version, when a patch
renames a symbol.")
(defvar el-patch--not-present (make-symbol "el-patch--not-present")
"Value used as a default argument to `gethash'.")
;;;; Resolving patches
(defmacro el-patch--with-puthash (table kvs &rest body)
"Bind variables in hash TABLE according to KVS then eval BODY.
Each of the KVS is a list whose first element is the key and
whose second element is the value. After BODY is evaluated, the
original state of TABLE is restored. Return value is the result
of evaluating the last form in BODY."
(declare (indent 2))
`(let* ((table ,table)
(kvs ,kvs)
(original-kvs (mapcar (lambda (kv)
(list (car kv)
(gethash (cadr kv) table
el-patch--not-present)))
kvs)))
(prog2
(dolist (kv kvs)
(puthash (car kv) (cadr kv) table))
(progn ,@body)
(dolist (kv original-kvs)
;; Note that we can't distinguish between a missing value and
;; a value that is coincidentally equal to
;; `el-patch--not-present', due to limitations in the Emacs
;; Lisp hash table API.
(if (eq (car kv) el-patch--not-present)
(remhash (car kv) table)
(puthash (car kv) (cadr kv) table))))))
(defun el-patch--copy-semitree (tree)
"Copy the list TREE, and return the copy. The list may be improper.
This function lives halfway between `copy-sequence' and
`copy-tree', since it only recurses into cdrs."
(if (consp tree)
(cons (car tree) (el-patch--copy-semitree (cdr tree)))
tree))
(defun el-patch--resolve (form new &optional table)
"Resolve a patch FORM.
Return a list of forms to be spliced into the surrounding
s-expression. Resolve in favor of the original version if NEW is
nil; otherwise resolve in favor of the new version. TABLE is a
hash table of `el-patch-let' bindings, which maps symbols to
their bindings."
(let ((table (or table (make-hash-table :test 'equal))))
(cond
((consp form)
(let* ((directive (car form))
(this-directive (pcase directive
('el-patch-remove 'el-patch-add)
('el-patch-splice 'el-patch-wrap)
(_ directive)))
(inverted (not (equal this-directive directive)))
(this-new (if inverted (not new) new))
(resolve (lambda (form) (el-patch--resolve form new table))))
(pcase this-directive
((quote el-patch-add)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
(when this-new
(cl-mapcan resolve (cdr form))))
((quote el-patch-swap)
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-swap'"
(1- (length form))))
((>= (length form) 4)
(error "Too many arguments (%d) in for `el-patch-swap'"
(1- (length form)))))
(funcall resolve
(if this-new
(cl-caddr form)
(cadr form))))
((quote el-patch-wrap)
(let ((triml (if (>= (length form) 3)
(nth 1 form)
0))
(trimr (if (>= (length form) 4)
(nth 2 form)
0))
(body (car (last form))))
(cond
((<= (length form) 1)
(error "Not enough arguments (%d) for `%s'"
(1- (length form)) directive))
((>= (length form) 5)
(error "Too many arguments (%d) for `%s'"
(1- (length form)) directive))
((not (listp body))
(error "Non-list (%s) as last argument for `%s'"
(car (last form)) directive))
((and (>= (length form) 3)
(not (integerp triml)))
(error "Non-integer (%s) as first argument for `%s'"
(nth 1 form) directive))
((and (>= (length form) 4)
(not (integerp trimr)))
(error "Non-integer (%s) as second argument for `%s'"
(nth 2 form) directive))
((< triml 0)
(error "Left trim less than zero (%d) for `%s'"
triml directive))
((< trimr 0)
(error "Right trim less than zero (%d) for `%s'"
trimr directive))
((> (+ triml trimr) (length body))
(error (concat "Combined trim (%d + %d) greater "
"than body length (%d) for `%s'")
triml trimr (length body) directive)))
(if this-new
(list (cl-mapcan resolve body))
(cl-mapcan resolve (nthcdr triml (butlast body trimr))))))
((quote el-patch-let)
(let ((bindings (nth 1 form))
(body (nthcdr 2 form)))
(cond
((<= (length form) 2)
(error "Not enough arguments (%d) for `el-patch-let'"
(1- (length form))))
((not (listp bindings))
(error "Non-list (%s) as first argument for `el-patch-let'"
bindings)))
(el-patch--with-puthash table
(mapcar
(lambda (kv)
(unless (symbolp (car kv))
(error "Non-symbol (%s) as binding for `el-patch-let'"
(car kv)))
(list (car kv)
(funcall resolve (cadr kv))))
bindings)
(cl-mapcan resolve body))))
((quote el-patch-literal)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-literal'"
(1- (length form))))
(cdr form))
((quote el-patch-concat)
(when (<= (length form) 1)
(error "Not enough arguments (%d) for `el-patch-concat'"
(1- (length form))))
(list (apply #'concat (cl-mapcan resolve (cdr form)))))
(_
(let ((car-forms (funcall resolve (car form)))
(cdr-forms (funcall resolve (cdr form))))
(cond
((null car-forms) cdr-forms)
((null cdr-forms) car-forms)
(t
(let ((forms (nconc car-forms (butlast cdr-forms))))
(setf (nthcdr (length forms) forms)
(car (last cdr-forms)))
(list forms)))))))))
((vectorp form)
(list
(seq-mapcat
(lambda (subform)
(el-patch--resolve subform new table))
form
'vector)))
(t
(or
;; Copy since otherwise we may end up with the same list object
;; returned multiple times, which is not okay since lists
;; returned by this function may be modified destructively.
(el-patch--copy-semitree (gethash form table))
(list form))))))
(defun el-patch--resolve-definition (patch-definition new)
"Resolve a PATCH-DEFINITION.
PATCH-DEFINITION is a list starting with `defun', `defmacro',
etc. Return a list of the same format. Resolve in favor of the
original version if NEW is nil; otherwise resolve in favor of the
new version."
(cons (car patch-definition)
(cl-mapcan (lambda (form)
(el-patch--resolve form new))
(cdr patch-definition))))
;;;; Patch directives
;;;###autoload
(defmacro el-patch-add (&rest args)
"Patch directive for inserting forms.
In the original definition, the ARGS and their containing form
are removed. In the new definition, the ARGS are spliced into the
containing s-expression."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-add' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-remove (&rest args)
"Patch directive for removing forms.
In the original definition, the ARGS are spliced into the
containing s-expression. In the new definition, the ARGS and
their containing form are removed."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-remove' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-swap (old new)
"Patch directive for swapping forms.
In the original definition, OLD is spliced into the containing
s-expression. In the new definition, NEW is spliced instead."
(declare (indent 0))
(ignore old new)
`(error "Can't use `el-patch-swap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-wrap (&optional triml trimr args)
"Patch directive for wrapping forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS are spliced into the
containing s-expression. If TRIML is provided, the first TRIML of
the ARGS are removed first. If TRIMR is provided, the last TRIMR
are also removed. In the new definition, the ARGS and their
containing list are spliced into the containing s-expression."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-wrap' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-splice (&optional triml trimr args)
"Patch directive for splicing forms.
TRIML and TRIMR are optional arguments. If only one is provided,
it is assumed to be TRIML. ARGS is required, and it must be a
list.
In the original definition, the ARGS and their containing list
are spliced into the containing s-expression. In the new
definition, the ARGS are spliced into the containing
s-expression. If TRIML is provided, the first TRIML of the ARGS
are removed first. If TRIMR is provided, the last TRIMR are also
removed."
(declare (indent defun))
(ignore triml trimr args)
`(error "Can't use `el-patch-splice' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-let (varlist &rest args)
"Patch directive for creating local el-patch bindings.
Creates local bindings according to VARLIST, then splices ARGS
into both the original and new definitions. You may bind symbols
that are also patch directives, but the bindings will not have
effect if the symbols are used at the beginning of a list (they
will act as patch directives)."
(declare (indent 1))
(ignore varlist args)
`(error "Can't use `el-patch-let' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-literal (&rest args)
"Patch directive for treating patch directives literally.
ARGS are spliced into the containing s-expression, but are not
processed further by el-patch."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-literal' outside of an `el-patch'"))
;;;###autoload
(defmacro el-patch-concat (&rest args)
"Patch directive for modifying string literals.
ARGS should resolve to strings; those strings are passed to
`concat' and spliced into the containing s-expression in both the
original and new definitions."
(declare (indent 0))
(ignore args)
`(error "Can't use `el-patch-concat' outside of an `el-patch'"))
;;;; Applying patches
(defmacro el-patch--stealthy-eval (definition &optional docstring-note)
"Evaluate DEFINITION without updating `load-history'.
DEFINITION should be an unquoted list beginning with `defun',
`defmacro', `define-minor-mode', etc. DOCSTRING-NOTE, if given,
is a sentence to put in brackets at the end of the docstring."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist)))
(unless props
(error "Unregistered definition type `%S'" type))
(let* ((classify (plist-get props :classify))
(docstring-idx
(nth 1 (assq 'doc-string (plist-get props :declare)))))
(unless classify
(error
"Definition type `%S' has no `:classify' in `el-patch-deftype-alist'"
type))
(when (and docstring-note docstring-idx)
(let ((old-docstring (nth docstring-idx definition)))
(if (stringp old-docstring)
(let ((new-docstring
(concat
old-docstring
(format "\n\n[%s]" docstring-note))))
(setq definition (cl-copy-list definition))
(setf (nth docstring-idx definition)
new-docstring))
(setq definition (append
(butlast definition
(- (length definition) docstring-idx))
(cons (format "[%s]" docstring-note)
(nthcdr docstring-idx definition)))))))
(let* ((classification
(funcall classify definition))
(items
(cl-remove-if
(lambda (item)
(member item current-load-list))
(mapcar
(lambda (entry)
(pcase (car entry)
(`function (cons 'defun (cdr entry)))
(`variable (cdr entry))
(_ (error
"Unexpected classification type `%S'" (car entry)))))
classification))))
`(prog2
;; Using a `progn' here so that the `prog2' above will
;; correctly cause the evaluated definition to be
;; returned, even if `el-patch-use-aggressive-defvar' is
;; nil.
(progn
,@(when el-patch-use-aggressive-defvar
(cl-mapcan
(lambda (entry)
(when (eq (car entry) 'variable)
`((makunbound ',(cdr entry)))))
classification)))
,definition
,@(mapcar (lambda (item)
`(setq current-load-list
(remove ',item current-load-list)))
items))))))
;;;###autoload
(defmacro el-patch--definition (patch-definition)
"Activate a PATCH-DEFINITION and update `el-patch--patches'.
PATCH-DEFINITION is an unquoted list starting with `defun',
`defmacro', etc., which may contain patch directives."
;; First we resolve the patch definition in favor of the modified
;; version, because that is the version we need to activate (no
;; validation happens here).
(let ((definition (el-patch--resolve-definition patch-definition t)))
;; Then we parse out the definition type and symbol name.
(cl-destructuring-bind (type name . body) definition
`(progn
;; Register the patch in our hash. We want to do this right
;; away so that if there is an error then at least the user
;; can undo the patch (as long as it is not too terribly
;; wrong).
(let ((patches (or (bound-and-true-p el-patch--patches)
(make-hash-table :test #'equal))))
(puthash ',type
',patch-definition
(or (gethash ',name patches)
(puthash ',name
(make-hash-table :test #'equal)
patches))))
;; Now we actually overwrite the current definition.
(el-patch--stealthy-eval
,definition
"This function was patched by `el-patch'.")))))
;;;;; Removing patches
;;;###autoload
(defun el-patch-unpatch (name type)
"Remove the patch given by the PATCH-DEFINITION.
This restores the original functionality of the object being
patched. NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(eval `(el-patch--stealthy-eval
,(el-patch--resolve-definition
patch-definition nil)
"This function was patched and then unpatched by `el-patch'."))
(error "There is no patch for %S %S" type name)))
;;;; Defining patch types
;;;###autoload
(cl-defmacro el-patch-deftype
(type &rest kwargs &key classify locate declare macro-name)
"Allow `el-patch' to patch definitions of the given TYPE.
TYPE is a symbol like `defun', `define-minor-mode', etc. This
updates `el-patch-deftype-alist' (which see for explanations of
CLASSIFY, LOCATE, and DECLARE) with the provided KWARGS and
defines a macro named like `el-patch-defun',
`el-patch-define-minor-mode', etc. (which can be overridden by
MACRO-NAME)."
(declare (indent defun))
(ignore locate)
(unless classify
(error "You must specify `:classify' in calls to `el-patch-deftype'"))
`(progn
(unless (bound-and-true-p el-patch-deftype-alist)
(setq el-patch-deftype-alist nil))
(setf (alist-get ',type el-patch-deftype-alist)
;; Make sure we don't accidentally create self-modifying
;; code if somebody decides to mutate
;; `el-patch-deftype-alist'.
(copy-tree ',kwargs))
(defmacro ,(or macro-name (intern (format "el-patch-%S" type)))
(name &rest args)
,(format "Use `el-patch' to override a `%S' form.
The ARGS are the same as for `%S'."
type type)
,@(when declare
`((declare ,@declare)))
(list #'el-patch--definition (cl-list* ',type name args)))))
(put 'el-patch-deftype 'el-patch-defined-properly t)
;;;;; Classification functions
(defun el-patch-classify-variable (definition)
"Classify the items defined by a variable DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(list (cons 'variable (nth 1 definition))))
(defun el-patch-classify-function (definition)
"Classify the items defined by a function DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(list (cons 'function (nth 1 definition))))
(defun el-patch-classify-define-minor-mode (definition)
"Classify the items defined by a minor mode DEFINITION.
DEFINITION is a list starting with `define-minor-mode' or
similar."
(let* ((function-name (nth 1 definition))
(variable-name (nth 1 definition))
(kw-args (nthcdr 3 definition)))
(dotimes (_ 3)
(unless (keywordp (car kw-args))
(setq kw-args (cdr kw-args))))
(while (keywordp (car kw-args))
(when (eq (car kw-args) :variable)
(setq variable-name (car kw-args)))
(setq kw-args (nthcdr 2 kw-args)))
(list (cons 'function function-name)
(cons 'variable variable-name))))
;;;;; Location functions
(defmacro el-patch-wrap-locator (&rest body)
"Wrap the operation of `find-function-noselect' or similar.
This disables local variables and messaging, saves the current
buffer and point, etc. BODY is executed within this context. It
is assumed that BODY finds the appropriate file in a buffer using
`get-file-buffer', and then returns a cons cell with the buffer
and point for the beginning of some Lisp form. The return value
is the Lisp form, read from the buffer at point."
(declare (indent 0))
`(let* (;; Since Emacs actually opens the source file in a (hidden)
;; buffer, it can try to apply local variables, which might
;; result in an annoying interactive prompt. Let's disable
;; that.
(enable-local-variables nil)
(enable-dir-local-variables nil)
;; This is supposed to be noninteractive so we also suppress
;; all the messages. This has the side effect of masking all
;; debugging messages (you can use `insert' instead, or
;; temporarily remove these bindings), but there are just so
;; many different messages that can happen for various
;; reasons and I haven't found any other standard way to
;; suppress them.
(inhibit-message t)
(message-log-max nil)
;; Now we actually execute BODY to move point to the right
;; file and location.
(buffer-point (save-excursion
;; This horrifying bit of hackery on
;; `get-file-buffer' prevents
;; `find-function-noselect' from returning
;; an existing buffer, so that later on when
;; we jump to the definition, we don't
;; temporarily scroll the window if the
;; definition happens to be in the *current*
;; buffer.
(cl-letf (((symbol-function #'get-file-buffer)
#'ignore))
;; Because we get an error if the function
;; doesn't have a definition anywhere.
(ignore-errors
,@body))))
(defun-buffer (car buffer-point))
(defun-point (cdr buffer-point)))
(prog1 (and defun-buffer
defun-point
(with-current-buffer defun-buffer
(save-excursion
(goto-char defun-point)
(read (current-buffer)))))
(when defun-buffer
(kill-buffer defun-buffer)))))
(defun el-patch-locate-variable (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defvar' or similar."
(el-patch-wrap-locator
(find-variable-noselect (nth 1 definition))))
(defun el-patch-locate-function (definition)
"Return the source code of DEFINITION.
DEFINITION is a list starting with `defun' or similar."
(el-patch-wrap-locator
(find-function-noselect (nth 1 definition) 'lisp-only)))
;;;;; Predefined patch types
;;;###autoload(require 'el-patch-stub)
;;;###autoload(el-patch--deftype-stub-setup)
;; These are alphabetized.
;;;###autoload
(el-patch-deftype cl-defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defconst
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defcustom
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype define-minor-mode
:classify el-patch-classify-define-minor-mode
:locate el-patch-locate-function
:declare ((doc-string 2)
(indent defun)))
;;;###autoload
(el-patch-deftype defmacro
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defsubst
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defun
:classify el-patch-classify-function
:locate el-patch-locate-function
:declare ((doc-string 3)
(indent defun)))
;;;###autoload
(el-patch-deftype defvar
:classify el-patch-classify-variable
:locate el-patch-locate-variable
:declare ((doc-string 3)
(indent defun)))
;;;; Validating patches
(defcustom el-patch-pre-validate-hook nil
"Hook run before `el-patch-validate-all'.
Also run before `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that make sure all
of your patches are defined (for example, you might need to load
some features if your patches are lazily defined)."
:type 'hook)
(defcustom el-patch-post-validate-hook nil
"Hook run after `el-patch-validate-all'.
Also run after `el-patch-validate' if a prefix argument is
provided. This hook should contain functions that undo any
patching that might have taken place in
`el-patch-pre-validate-hook', if you do not want the patches to
be defined permanently."
:type 'hook)
(defun el-patch--locate (definition)
"Return the Lisp form corresponding to the given DEFINITION.
Return nil if such a definition cannot be found. (That would
happen if the definition were generated dynamically.) TYPE is a
symbol `defun', `defmacro', etc. which is used to determine
whether the symbol is a function or variable."
(let* ((type (nth 0 definition))
(props (alist-get type el-patch-deftype-alist))
(locator (plist-get props :locate)))
(unless locator
(error
"Definition type `%S' has no `:locate' in `el-patch-deftype-alist'"
type))
(funcall locator definition)))
;;;###autoload
(defun el-patch-validate (name type &optional nomsg run-hooks)
"Validate the patch with given NAME and TYPE.
This means el-patch will attempt to find the original definition
for the function, and verify that it is the same as the original
function assumed by the patch. A warning will be signaled if the
original definition for a patched function cannot be found, or if
there is a difference between the actual and expected original
definitions.
Interactively, use `completing-read' to select a function to
inspect the patch of.
NAME is a symbol naming the object being patched; TYPE is a
symbol `defun', `defmacro', etc.
Returns nil if the patch is not valid, and otherwise returns t.
If NOMSG is non-nil, does not signal a message when the patch is
valid.
If RUN-HOOKS is non-nil, runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'. Interactively, this happens unless
a prefix argument is provided.
See also `el-patch-validate-all'."
(interactive (progn
(unless current-prefix-arg
(run-hooks 'el-patch-pre-validate-hook))
(append (el-patch--select-patch)
(list nil (unless current-prefix-arg
'post-only)))))
(unless (member run-hooks '(nil post-only))
(run-hooks 'el-patch-pre-validate-hook))
(unwind-protect
(progn
(let* ((patch-definition (el-patch-get name type))
(type (car patch-definition))
(expected-definition (el-patch--resolve-definition
patch-definition nil))
(name (cadr expected-definition))
(actual-definition (el-patch--locate expected-definition)))
(cond
((not actual-definition)
(display-warning
'el-patch
(format "Could not find definition of %S `%S'" type name))
nil)
((not (equal expected-definition actual-definition))
(display-warning
'el-patch
(format (concat "Definition of %S `%S' differs from what "
"is assumed by its patch")
type name))
nil)
(t
(unless nomsg
(message "Patch is valid"))
t))))
(when run-hooks
(run-hooks 'el-patch-post-validate-hook))))
;;;###autoload
(defun el-patch-validate-all ()
"Validate all currently defined patches.
Runs `el-patch-pre-validate-hook' and
`el-patch-post-validate-hook'.
See `el-patch-validate'."
(interactive)
(run-hooks 'el-patch-pre-validate-hook)
(unwind-protect
(let ((patch-count 0)
(warning-count 0))
(dolist (name (hash-table-keys el-patch--patches))
(let ((patch-hash (gethash name el-patch--patches)))
(dolist (type (hash-table-keys patch-hash))
(setq patch-count (1+ patch-count))
(unless (el-patch-validate name type 'nomsg)
(setq warning-count (1+ warning-count))))))
(cond
((zerop patch-count)
(user-error "No patches defined"))
((zerop warning-count)
(if (= patch-count 1)
(message "Patch is valid (only one defined)")
(message "All %d patches are valid" patch-count)))
((= patch-count warning-count)
(if (= patch-count 1)
(message "Patch is invalid (only one defined)")
(message "All %d patches are invalid" patch-count)))
(t
(message "%s valid, %s invalid"
(if (= warning-count (1- patch-count))
"1 patch is"
(format "%d patches are" (- patch-count warning-count)))
(if (= warning-count 1)
"1 patch is"
(format "%d patches are" warning-count))))))
(run-hooks 'el-patch-post-validate-hook)))
;;;;; el-patch-feature
;;;###autoload
(defmacro el-patch-feature (feature &rest args)
"Declare that some patches are only defined after FEATURE is loaded.
This is a convenience macro that creates a function for invoking
`require' on that feature, and then adds it to
`el-patch-pre-validate-hook' so that your patches are loaded and
`el-patch' can properly validate them.
FEATURE should be an unquoted symbol. ARGS, if given, are passed
as quoted literals along with FEATURE to
`el-patch-require-function' when `el-patch-validate-all' is
called."
(let ((defun-name (intern (format "el-patch-require-%S" feature))))
`(progn
(defun ,defun-name ()
(apply el-patch-require-function ',feature ',args))
(add-hook 'el-patch-pre-validate-hook #',defun-name))))
;;;; Viewing patches
;;;###autoload
(defun el-patch-get (name type)
"Return the patch for object NAME of the given TYPE.
NAME is a symbol for the name of the definition that was patched,
and TYPE is a symbol `defun', `defmacro', etc. If the patch could
not be found, return nil."
(condition-case nil
(gethash type (gethash name el-patch--patches))
(error nil)))
(defun el-patch--select-patch ()
"Use `completing-read' to select a patched function.
Return a list of two elements, the name (a symbol) of the object
being patched and the type (a symbol `defun', `defmacro', etc.)
of the definition."
(let ((options (mapcar #'symbol-name (hash-table-keys el-patch--patches))))
(unless options
(user-error "No patches defined"))
(let* ((name (intern (completing-read
"Which patch? "
options
nil
'require-match)))
(patch-hash (gethash name el-patch--patches))
(options (mapcar #'symbol-name
(hash-table-keys patch-hash))))
(list name
(intern (pcase (length options)
(0 (error "Internal `el-patch' error"))
(1 (car options))
(_ (completing-read
"Which version? "
options
nil
'require-match))))))))
(defun el-patch--ediff-forms (name1 form1 name2 form2)
"Ediff two forms.
Obtain and empty buffer named NAME1 and pretty-print FORM1 into
it. Do the same for NAME2 and FORM2, and then run Ediff on the
two buffers wordwise."
(let (min1 max1 min2 max2)
(with-current-buffer (get-buffer-create name1)
(erase-buffer)
(emacs-lisp-mode)
(pp form1 (current-buffer))
(setq min1 (point-min)
max1 (point-max)))
(with-current-buffer (get-buffer-create name2)
(erase-buffer)
(emacs-lisp-mode)
(pp form2 (current-buffer))
(setq min2 (point-min)
max2 (point-max)))
;; Ugly hack because Ediff is missing an `ediff-buffers-wordwise'
;; function.
(eval-and-compile
(require 'ediff))
(ediff-regions-internal
(get-buffer name1) min1 max1
(get-buffer name2) min2 max2
nil 'ediff-regions-wordwise 'word-mode nil)))
;;;###autoload
(defun el-patch-ediff-patch (name type)
"Show the patch for an object in Ediff.
NAME and TYPE are as returned by `el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((old-definition (el-patch--resolve-definition
patch-definition nil))
(new-definition (el-patch--resolve-definition
patch-definition t)))
(el-patch--ediff-forms
"*el-patch original*" old-definition
"*el-patch patched*" new-definition)
(when (equal old-definition new-definition)
(message "No patch")))
(error "There is no patch for %S %S" type name)))
;;;###autoload
(defun el-patch-ediff-conflict (name type)
"Show a patch conflict in Ediff.
This is a diff between the expected and actual values of a
patch's original definition. NAME and TYPE are as returned by
`el-patch-get'."
(interactive (el-patch--select-patch))
(if-let ((patch-definition (el-patch-get name type)))
(let* ((expected-definition (el-patch--resolve-definition
patch-definition nil))
(actual-definition (el-patch--locate expected-definition)))
(el-patch--ediff-forms
"*el-patch actual*" actual-definition
"*el-patch expected*" expected-definition)
(when (equal actual-definition expected-definition)
(message "No conflict")))
(error "There is no patch for %S %S" type name)))
;;;; use-package integration
(defun el-patch--use-package-handler
(base-keyword name _keyword args rest state)
"When applied partially, return a `use-package' handler.
BASE-KEYWORD is either `:init' or `:config'. The remaining
arguments NAME, KEYWORD, ARGS, REST, and STATE are explained by
the `use-package' documentation."
(setq rest
(plist-put
rest base-keyword
(append
(mapcar
(lambda (arg)
(if (and (consp arg)
(assq (car arg) el-patch-deftype-alist))
(cons (or
(plist-get
(alist-get (car arg) el-patch-deftype-alist)
:macro-name)
(intern (format "el-patch-%S" (car arg))))
(cdr arg))
arg))
args)
(plist-get rest base-keyword))))
(setq rest
(plist-put
rest :init
(cons `(el-patch-feature ,name)
(plist-get rest :init))))
(use-package-process-keywords name rest state))
(define-minor-mode el-patch-use-package-mode
"Minor mode to enable `use-package' integration for `el-patch'.
This mode is enabled or disabled automatically when the
`el-patch' library is loaded, according to the value of
`el-patch-enable-use-package-integration'."
:global t
:group 'el-patch
(if el-patch-use-package-mode
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(cl-pushnew kw use-package-keywords))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch))
(defalias fun #'use-package-normalize-forms))
(defalias 'use-package-handler/:init/el-patch
(apply-partially #'el-patch--use-package-handler :init))
(defalias 'use-package-handler/:config/el-patch
(apply-partially #'el-patch--use-package-handler :config)))
(with-eval-after-load 'use-package-core
(dolist (kw '(:init/el-patch :config/el-patch))
(setq use-package-keywords (delq kw use-package-keywords)))
(dolist (fun '(use-package-normalize/:init/el-patch
use-package-normalize/:config/el-patch
use-package-handler/:init/el-patch
use-package-handler/:config/el-patch))
(fmakunbound fun)))))
(if el-patch-enable-use-package-integration
(el-patch-use-package-mode +1)
(el-patch-use-package-mode -1))
;;;; Closing remarks
(provide 'el-patch)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; el-patch.el ends here
|
[
{
"context": "7, 1998 Free Software Foundation, Inc.\n\n;; Author: Bill Rozas <jinx@martigny.ai.mit.edu>\n;; Adapted-by: Dave Lo",
"end": 145,
"score": 0.9998667240142822,
"start": 135,
"tag": "NAME",
"value": "Bill Rozas"
},
{
"context": "Software Foundation, Inc.\n\n;; Author: Bill Rozas <jinx@martigny.ai.mit.edu>\n;; Adapted-by: Dave Love <d.love@dl.ac.uk>\n;; Ke",
"end": 171,
"score": 0.9999381899833679,
"start": 147,
"tag": "EMAIL",
"value": "jinx@martigny.ai.mit.edu"
},
{
"context": "ll Rozas <jinx@martigny.ai.mit.edu>\n;; Adapted-by: Dave Love <d.love@dl.ac.uk>\n;; Keywords: languages, lisp\n\n;",
"end": 197,
"score": 0.9998884201049805,
"start": 188,
"tag": "NAME",
"value": "Dave Love"
},
{
"context": "nx@martigny.ai.mit.edu>\n;; Adapted-by: Dave Love <d.love@dl.ac.uk>\n;; Keywords: languages, lisp\n\n;; This file is pa",
"end": 214,
"score": 0.9999348521232605,
"start": 199,
"tag": "EMAIL",
"value": "d.love@dl.ac.uk"
},
{
"context": "n-compile\n (list\n ;;\n ;; Declarations. Hannes Haug <hannes.haug@student.uni-tuebingen.de> says\n ",
"end": 10732,
"score": 0.9998655319213867,
"start": 10721,
"tag": "NAME",
"value": "Hannes Haug"
},
{
"context": "(list\n ;;\n ;; Declarations. Hannes Haug <hannes.haug@student.uni-tuebingen.de> says\n ;; this works for SOS, STklos, SCOOPS,",
"end": 10770,
"score": 0.9999099969863892,
"start": 10734,
"tag": "EMAIL",
"value": "hannes.haug@student.uni-tuebingen.de"
},
{
"context": "\" \"let-syntax\" \"letrec\" \"letrec-syntax\"\n\t ;; Hannes Haug <hannes.haug@student.uni-tuebingen.de> wants:\n\t ",
"end": 11971,
"score": 0.9998844265937805,
"start": 11960,
"tag": "NAME",
"value": "Hannes Haug"
},
{
"context": " \"letrec\" \"letrec-syntax\"\n\t ;; Hannes Haug <hannes.haug@student.uni-tuebingen.de> wants:\n\t \"and\" \"or\" \"delay\"\n\t ;; Ste",
"end": 12009,
"score": 0.9999212622642517,
"start": 11973,
"tag": "EMAIL",
"value": "hannes.haug@student.uni-tuebingen.de"
},
{
"context": "n.de> wants:\n\t \"and\" \"or\" \"delay\"\n\t ;; Stefan Monnier <stefan.monnier@epfl.ch> says don't bother:\n\t ",
"end": 12070,
"score": 0.9998798370361328,
"start": 12056,
"tag": "NAME",
"value": "Stefan Monnier"
},
{
"context": " \"and\" \"or\" \"delay\"\n\t ;; Stefan Monnier <stefan.monnier@epfl.ch> says don't bother:\n\t ;;\"quasiquote\" \"quote",
"end": 12094,
"score": 0.9998945593833923,
"start": 12072,
"tag": "EMAIL",
"value": "stefan.monnier@epfl.ch"
},
{
"context": "x\" \"syntax-rules\") t)\n\t\"\\\\>\") 1)\n ;;\n ;; David Fox <fox@graphics.cs.nyu.edu> for SOS/STklos class sp",
"end": 12255,
"score": 0.9996981620788574,
"start": 12246,
"tag": "NAME",
"value": "David Fox"
},
{
"context": "ules\") t)\n\t\"\\\\>\") 1)\n ;;\n ;; David Fox <fox@graphics.cs.nyu.edu> for SOS/STklos class specifiers.\n '(\"\\\\<<\\\\",
"end": 12280,
"score": 0.9999300241470337,
"start": 12257,
"tag": "EMAIL",
"value": "fox@graphics.cs.nyu.edu"
}
] | make_1.4/make/inputs/sdir-cov11/lisp/progmodes/scheme.el | m-zakeri/benchmark | 0 | ;;; scheme.el --- Scheme (and DSSSL) editing mode.
;; Copyright (C) 1986, 87, 88, 97, 1998 Free Software Foundation, Inc.
;; Author: Bill Rozas <jinx@martigny.ai.mit.edu>
;; Adapted-by: Dave Love <d.love@dl.ac.uk>
;; Keywords: languages, 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; The major mode for editing Scheme-type Lisp code, very similar to
;; the Lisp mode documented in the Emacs manual. `dsssl-mode' is a
;; variant of scheme-mode for editing DSSSL specifications for SGML
;; documents. [As of Apr 1997, some pointers for DSSSL may be found,
;; for instance, at <URL:http://www.sil.org/sgml/related.html#dsssl>.]
;; All these Lisp-ish modes vary basically in details of the language
;; syntax they highlight/indent/index, but dsssl-mode uses "^;;;" as
;; the page-delimiter since ^L isn't normally a legal SGML character.
;;
;; For interacting with a Scheme interpreter See also `run-scheme' in
;; the `cmuscheme' package and also the implementation-specific
;; `xscheme' package.
;; Here's a recipe to generate a TAGS file for DSSSL, by the way:
;; etags --lang=scheme --regex='/[ \t]*(\(mode\|element\)[ \t
;; ]+\([^ \t(
;; ]+\)/\2/' --regex='/[ \t]*(element[ \t
;; ]*([^)]+[ \t
;; ]+\([^)]+\)[ \t
;; ]*)/\1/' --regex='/(declare[^ \t
;; ]*[ \t
;; ]+\([^ \t
;; ]+\)/\1/' "$@"
;;; Code:
(require 'lisp-mode)
(defvar scheme-mode-syntax-table nil "")
(if (not scheme-mode-syntax-table)
(let ((i 0))
(setq scheme-mode-syntax-table (make-syntax-table))
(set-syntax-table scheme-mode-syntax-table)
;; Default is atom-constituent.
(while (< i 256)
(modify-syntax-entry i "_ ")
(setq i (1+ i)))
;; Word components.
(setq i ?0)
(while (<= i ?9)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?A)
(while (<= i ?Z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?a)
(while (<= i ?z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
;; Whitespace
(modify-syntax-entry ?\t " ")
(modify-syntax-entry ?\n "> ")
(modify-syntax-entry ?\f " ")
(modify-syntax-entry ?\r " ")
(modify-syntax-entry ? " ")
;; These characters are delimiters but otherwise undefined.
;; Brackets and braces balance for editing convenience.
(modify-syntax-entry ?\[ "(] ")
(modify-syntax-entry ?\] ")[ ")
(modify-syntax-entry ?{ "(} ")
(modify-syntax-entry ?} "){ ")
(modify-syntax-entry ?\| " 23")
;; Other atom delimiters
(modify-syntax-entry ?\( "() ")
(modify-syntax-entry ?\) ")( ")
(modify-syntax-entry ?\; "< ")
(modify-syntax-entry ?\" "\" ")
(modify-syntax-entry ?' " p")
(modify-syntax-entry ?` " p")
;; Special characters
(modify-syntax-entry ?, "_ p")
(modify-syntax-entry ?@ "_ p")
(modify-syntax-entry ?# "_ p14")
(modify-syntax-entry ?\\ "\\ ")))
(defvar scheme-mode-abbrev-table nil "")
(define-abbrev-table 'scheme-mode-abbrev-table ())
(defvar scheme-imenu-generic-expression
'((nil
"^(define\\(\\|-\\(generic\\(\\|-procedure\\)\\|method\\)\\)*\\s-+(?\\(\\sw+\\)" 4)
("Types"
"^(define-class\\s-+(?\\(\\sw+\\)" 1)
("Macros"
"^(\\(defmacro\\|define-macro\\|define-syntax\\)\\s-+(?\\(\\sw+\\)" 2))
"Imenu generic expression for Scheme mode. See `imenu-generic-expression'.")
(defun scheme-mode-variables ()
(set-syntax-table scheme-mode-syntax-table)
(setq local-abbrev-table scheme-mode-abbrev-table)
(make-local-variable 'paragraph-start)
(setq paragraph-start (concat "$\\|" page-delimiter))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
(make-local-variable 'paragraph-ignore-fill-prefix)
(setq paragraph-ignore-fill-prefix t)
(make-local-variable 'fill-paragraph-function)
(setq fill-paragraph-function 'lisp-fill-paragraph)
;; Adaptive fill mode gets in the way of auto-fill,
;; and should make no difference for explicit fill
;; because lisp-fill-paragraph should do the job.
(make-local-variable 'adaptive-fill-mode)
(setq adaptive-fill-mode nil)
(make-local-variable 'normal-auto-fill-function)
(setq normal-auto-fill-function 'lisp-mode-auto-fill)
(make-local-variable 'indent-line-function)
(setq indent-line-function 'lisp-indent-line)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'outline-regexp)
(setq outline-regexp ";;; \\|(....")
(make-local-variable 'comment-start)
(setq comment-start ";")
(make-local-variable 'comment-start-skip)
;; Look within the line for a ; following an even number of backslashes
;; after either a non-backslash or the line beginning.
(setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+[ \t]*")
(make-local-variable 'comment-column)
(setq comment-column 40)
(make-local-variable 'comment-indent-function)
(setq comment-indent-function 'lisp-comment-indent)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'lisp-indent-function)
(set lisp-indent-function 'scheme-indent-function)
(setq mode-line-process '("" scheme-mode-line-process))
(make-local-variable 'imenu-case-fold-search)
(setq imenu-case-fold-search t)
(make-local-variable 'imenu-generic-expression)
(setq imenu-generic-expression scheme-imenu-generic-expression)
(make-local-variable 'imenu-syntax-alist)
(setq imenu-syntax-alist '(("+-*/.<>=?!$%_&~^:" . "w")))
(make-local-variable 'font-lock-defaults)
(setq font-lock-defaults
'((scheme-font-lock-keywords
scheme-font-lock-keywords-1 scheme-font-lock-keywords-2)
nil t (("+-*/.<>=!?$%_&~^:" . "w")) beginning-of-defun
(font-lock-mark-block-function . mark-defun))))
(defvar scheme-mode-line-process "")
(defvar scheme-mode-map nil
"Keymap for Scheme mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")
(if scheme-mode-map
()
(let ((map (make-sparse-keymap "Scheme")))
(setq scheme-mode-map
(nconc (make-sparse-keymap) shared-lisp-mode-map))
(define-key scheme-mode-map [menu-bar] (make-sparse-keymap))
(define-key scheme-mode-map [menu-bar scheme]
(cons "Scheme" map))
(define-key map [run-scheme] '("Run Inferior Scheme" . run-scheme))
(define-key map [uncomment-region]
'("Uncomment Out Region" . (lambda (beg end)
(interactive "r")
(comment-region beg end '(4)))))
(define-key map [comment-region] '("Comment Out Region" . comment-region))
(define-key map [indent-region] '("Indent Region" . indent-region))
(define-key map [indent-line] '("Indent Line" . lisp-indent-line))
(put 'comment-region 'menu-enable 'mark-active)
(put 'uncomment-region 'menu-enable 'mark-active)
(put 'indent-region 'menu-enable 'mark-active)))
;; Used by cmuscheme
(defun scheme-mode-commands (map)
;;(define-key map "\t" 'indent-for-tab-command) ; default
(define-key map "\177" 'backward-delete-char-untabify)
(define-key map "\e\C-q" 'indent-sexp))
;;;###autoload
(defun scheme-mode ()
"Major mode for editing Scheme code.
Editing commands are similar to those of lisp-mode.
In addition, if an inferior Scheme process is running, some additional
commands will be defined, for evaluating expressions and controlling
the interpreter, and the state of the process will be displayed in the
modeline of all Scheme buffers. The names of commands that interact
with the Scheme process start with \"xscheme-\". For more information
see the documentation for xscheme-interaction-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entry to this mode calls the value of scheme-mode-hook
if that value is non-nil."
(interactive)
(kill-all-local-variables)
(scheme-mode-initialize)
(scheme-mode-variables)
(run-hooks 'scheme-mode-hook))
(defun scheme-mode-initialize ()
(use-local-map scheme-mode-map)
(setq major-mode 'scheme-mode)
(setq mode-name "Scheme"))
(defgroup scheme nil
"Editing Scheme code"
:group 'lisp)
(defcustom scheme-mit-dialect t
"If non-nil, scheme mode is specialized for MIT Scheme.
Set this to nil if you normally use another dialect."
:type 'boolean
:group 'scheme)
(defcustom dsssl-sgml-declaration
"<!DOCTYPE style-sheet PUBLIC \"-//James Clark//DTD DSSSL Style Sheet//EN\">
"
"*An SGML declaration for the DSSSL file.
If it is defined as a string this will be inserted into an empty buffer
which is in dsssl-mode. It is typically James Clark's style-sheet
doctype, as required for Jade."
:type '(choice (string :tag "Specified string")
(const :tag "None" :value nil))
:group 'scheme)
(defcustom scheme-mode-hook nil
"Normal hook (list of functions) run when entering scheme-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defcustom dsssl-mode-hook nil
"Normal hook (list of functions) run when entering dsssl-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defvar dsssl-imenu-generic-expression
;; Perhaps this should also look for the style-sheet DTD tags. I'm
;; not sure it's the best way to organize it; perhaps one type
;; should be at the first level, though you don't see this anyhow if
;; it gets split up.
'(("Defines"
"^(define\\s-+(?\\(\\sw+\\)" 1)
("Modes"
"^\\s-*(mode\\s-+\\(\\(\\sw\\|\\s-\\)+\\)" 1)
("Elements"
;; (element foo ...) or (element (foo bar ...) ...)
;; Fixme: Perhaps it should do `root'.
"^\\s-*(element\\s-+(?\\(\\(\\sw\\|\\s-\\)+\\))?" 1)
("Declarations"
"^(declare\\(-\\sw+\\)+\\>\\s-+\\(\\sw+\\)" 2))
"Imenu generic expression for DSSSL mode. See `imenu-generic-expression'.")
(defconst scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Declarations. Hannes Haug <hannes.haug@student.uni-tuebingen.de> says
;; this works for SOS, STklos, SCOOPS, Meroon and Tiny CLOS.
(list (concat "(\\(define\\*?\\("
;; Function names.
"\\(\\|-public\\|-method\\|-generic\\(-procedure\\)?\\)\\|"
;; Macro names, as variable names. A bit dubious, this.
"\\(-syntax\\)\\|"
;; Class names.
"-class"
;; Guile modules.
"\\|-module"
"\\)\\)\\>"
;; Any whitespace and declared object.
"[ \t]*(?"
"\\(\\sw+\\)?")
'(1 font-lock-keyword-face)
'(6 (cond ((match-beginning 3) font-lock-function-name-face)
((match-beginning 5) font-lock-variable-name-face)
(t font-lock-type-face))
nil t))
))
"Subdued expressions to highlight in Scheme modes.")
(defconst scheme-font-lock-keywords-2
(append scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Control structures.
(cons
(concat
"(" (regexp-opt
'("begin" "call-with-current-continuation" "call/cc"
"call-with-input-file" "call-with-output-file" "case" "cond"
"do" "else" "for-each" "if" "lambda"
"let" "let*" "let-syntax" "letrec" "letrec-syntax"
;; Hannes Haug <hannes.haug@student.uni-tuebingen.de> wants:
"and" "or" "delay"
;; Stefan Monnier <stefan.monnier@epfl.ch> says don't bother:
;;"quasiquote" "quote" "unquote" "unquote-splicing"
"map" "syntax" "syntax-rules") t)
"\\>") 1)
;;
;; David Fox <fox@graphics.cs.nyu.edu> for SOS/STklos class specifiers.
'("\\<<\\sw+>\\>" . font-lock-type-face)
;;
;; Scheme `:' keywords as builtins.
'("\\<:\\sw+\\>" . font-lock-builtin-face)
)))
"Gaudy expressions to highlight in Scheme modes.")
(defvar scheme-font-lock-keywords scheme-font-lock-keywords-1
"Default expressions to highlight in Scheme modes.")
;;;###autoload
(defun dsssl-mode ()
"Major mode for editing DSSSL code.
Editing commands are similar to those of lisp-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entering this mode runs the hooks `scheme-mode-hook' and then
`dsssl-mode-hook' and inserts the value of `dsssl-sgml-declaration' if
that variable's value is a string."
(interactive)
(kill-all-local-variables)
(use-local-map scheme-mode-map)
(scheme-mode-initialize)
(make-local-variable 'page-delimiter)
(setq page-delimiter "^;;;" ; ^L not valid SGML char
major-mode 'dsssl-mode
mode-name "DSSSL")
;; Insert a suitable SGML declaration into an empty buffer.
(and (zerop (buffer-size))
(stringp dsssl-sgml-declaration)
(not buffer-read-only)
(insert dsssl-sgml-declaration))
(scheme-mode-variables)
(setq font-lock-defaults '(dsssl-font-lock-keywords
nil t (("+-*/.<>=?$%_&~^:" . "w"))
beginning-of-defun
(font-lock-mark-block-function . mark-defun)))
(setq imenu-case-fold-search nil)
(setq imenu-generic-expression dsssl-imenu-generic-expression)
(setq imenu-syntax-alist '(("+-*/.<>=?$%_&~^:" . "w")))
(run-hooks 'scheme-mode-hook)
(run-hooks 'dsssl-mode-hook))
;; Extra syntax for DSSSL. This isn't separated from Scheme, but
;; shouldn't cause much trouble in scheme-mode.
(put 'element 'scheme-indent-function 1)
(put 'mode 'scheme-indent-function 1)
(put 'with-mode 'scheme-indent-function 1)
(put 'make 'scheme-indent-function 1)
(put 'style 'scheme-indent-function 1)
(put 'root 'scheme-indent-function 1)
(defvar dsssl-font-lock-keywords
(eval-when-compile
(list
;; Similar to Scheme
(list "(\\(define\\(-\\w+\\)?\\)\\>[ ]*\\\((?\\)\\(\\sw+\\)\\>"
'(1 font-lock-keyword-face)
'(4 font-lock-function-name-face))
(cons
(concat "(\\("
;; (make-regexp '("case" "cond" "else" "if" "lambda"
;; "let" "let*" "letrec" "and" "or" "map" "with-mode"))
"and\\|c\\(ase\\|ond\\)\\|else\\|if\\|"
"l\\(ambda\\|et\\(\\|*\\|rec\\)\\)\\|map\\|or\\|with-mode"
"\\)\\>")
1)
;; DSSSL syntax
'("(\\(element\\|mode\\|declare-\\w+\\)\\>[ ]*\\(\\sw+\\)"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("(\\(element\\)\\>[ ]*(\\(\\S)+\\))"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("\\<\\sw+:\\>" . font-lock-constant-face) ; trailing `:' c.f. scheme
;; SGML markup (from sgml-mode) :
'("<\\([!?][-a-z0-9]+\\)" 1 font-lock-keyword-face)
'("<\\(/?[-a-z0-9]+\\)" 1 font-lock-function-name-face)))
"Default expressions to highlight in DSSSL mode.")
(defvar calculate-lisp-indent-last-sexp)
;; Copied from lisp-indent-function, but with gets of
;; scheme-indent-{function,hook}.
(defun scheme-indent-function (indent-point state)
(let ((normal-indent (current-column)))
(goto-char (1+ (elt state 1)))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(if (and (elt state 2)
(not (looking-at "\\sw\\|\\s_")))
;; car of form doesn't seem to be a a symbol
(progn
(if (not (> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp))
(progn (goto-char calculate-lisp-indent-last-sexp)
(beginning-of-line)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp 0 t)))
;; Indent under the list or under the first sexp on the same
;; line as calculate-lisp-indent-last-sexp. Note that first
;; thing on that line has to be complete sexp since we are
;; inside the innermost containing sexp.
(backward-prefix-chars)
(current-column))
(let ((function (buffer-substring (point)
(progn (forward-sexp 1) (point))))
method)
(setq method (or (get (intern-soft function) 'scheme-indent-function)
(get (intern-soft function) 'scheme-indent-hook)))
(cond ((or (eq method 'defun)
(and (null method)
(> (length function) 3)
(string-match "\\`def" function)))
(lisp-indent-defform state indent-point))
((integerp method)
(lisp-indent-specform method state
indent-point normal-indent))
(method
(funcall method state indent-point normal-indent)))))))
;;; Let is different in Scheme
(defun would-be-symbol (string)
(not (string-equal (substring string 0 1) "(")))
(defun next-sexp-as-string ()
;; Assumes that protected by a save-excursion
(forward-sexp 1)
(let ((the-end (point)))
(backward-sexp 1)
(buffer-substring (point) the-end)))
;; This is correct but too slow.
;; The one below works almost always.
;;(defun scheme-let-indent (state indent-point)
;; (if (would-be-symbol (next-sexp-as-string))
;; (scheme-indent-specform 2 state indent-point)
;; (scheme-indent-specform 1 state indent-point)))
(defun scheme-let-indent (state indent-point normal-indent)
(skip-chars-forward " \t")
(if (looking-at "[-a-zA-Z0-9+*/?!@$%^&_:~]")
(lisp-indent-specform 2 state indent-point normal-indent)
(lisp-indent-specform 1 state indent-point normal-indent)))
;; (put 'begin 'scheme-indent-function 0), say, causes begin to be indented
;; like defun if the first form is placed on the next line, otherwise
;; it is indented like any other form (i.e. forms line up under first).
(put 'begin 'scheme-indent-function 0)
(put 'case 'scheme-indent-function 1)
(put 'delay 'scheme-indent-function 0)
(put 'do 'scheme-indent-function 2)
(put 'lambda 'scheme-indent-function 1)
(put 'let 'scheme-indent-function 'scheme-let-indent)
(put 'let* 'scheme-indent-function 1)
(put 'letrec 'scheme-indent-function 1)
(put 'sequence 'scheme-indent-function 0) ; SICP, not r4rs
(put 'let-syntax 'scheme-indent-function 1)
(put 'letrec-syntax 'scheme-indent-function 1)
(put 'syntax-rules 'scheme-indent-function 1)
(put 'call-with-input-file 'scheme-indent-function 1)
(put 'with-input-from-file 'scheme-indent-function 1)
(put 'with-input-from-port 'scheme-indent-function 1)
(put 'call-with-output-file 'scheme-indent-function 1)
(put 'with-output-to-file 'scheme-indent-function 1)
(put 'with-output-to-port 'scheme-indent-function 1)
(put 'call-with-values 'scheme-indent-function 1) ; r5rs?
(put 'dynamic-wind 'scheme-indent-function 3) ; r5rs?
;;;; MIT Scheme specific indentation.
(if scheme-mit-dialect
(progn
(put 'fluid-let 'scheme-indent-function 1)
(put 'in-package 'scheme-indent-function 1)
(put 'local-declare 'scheme-indent-function 1)
(put 'macro 'scheme-indent-function 1)
(put 'make-environment 'scheme-indent-function 0)
(put 'named-lambda 'scheme-indent-function 1)
(put 'using-syntax 'scheme-indent-function 1)
(put 'with-input-from-string 'scheme-indent-function 1)
(put 'with-output-to-string 'scheme-indent-function 0)
(put 'with-values 'scheme-indent-function 1)
(put 'syntax-table-define 'scheme-indent-function 2)
(put 'list-transform-positive 'scheme-indent-function 1)
(put 'list-transform-negative 'scheme-indent-function 1)
(put 'list-search-positive 'scheme-indent-function 1)
(put 'list-search-negative 'scheme-indent-function 1)
(put 'access-components 'scheme-indent-function 1)
(put 'assignment-components 'scheme-indent-function 1)
(put 'combination-components 'scheme-indent-function 1)
(put 'comment-components 'scheme-indent-function 1)
(put 'conditional-components 'scheme-indent-function 1)
(put 'disjunction-components 'scheme-indent-function 1)
(put 'declaration-components 'scheme-indent-function 1)
(put 'definition-components 'scheme-indent-function 1)
(put 'delay-components 'scheme-indent-function 1)
(put 'in-package-components 'scheme-indent-function 1)
(put 'lambda-components 'scheme-indent-function 1)
(put 'lambda-components* 'scheme-indent-function 1)
(put 'lambda-components** 'scheme-indent-function 1)
(put 'open-block-components 'scheme-indent-function 1)
(put 'pathname-components 'scheme-indent-function 1)
(put 'procedure-components 'scheme-indent-function 1)
(put 'sequence-components 'scheme-indent-function 1)
(put 'unassigned\?-components 'scheme-indent-function 1)
(put 'unbound\?-components 'scheme-indent-function 1)
(put 'variable-components 'scheme-indent-function 1)))
(provide 'scheme)
;;; scheme.el ends here
| 42948 | ;;; scheme.el --- Scheme (and DSSSL) editing mode.
;; Copyright (C) 1986, 87, 88, 97, 1998 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; Adapted-by: <NAME> <<EMAIL>>
;; Keywords: languages, 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; The major mode for editing Scheme-type Lisp code, very similar to
;; the Lisp mode documented in the Emacs manual. `dsssl-mode' is a
;; variant of scheme-mode for editing DSSSL specifications for SGML
;; documents. [As of Apr 1997, some pointers for DSSSL may be found,
;; for instance, at <URL:http://www.sil.org/sgml/related.html#dsssl>.]
;; All these Lisp-ish modes vary basically in details of the language
;; syntax they highlight/indent/index, but dsssl-mode uses "^;;;" as
;; the page-delimiter since ^L isn't normally a legal SGML character.
;;
;; For interacting with a Scheme interpreter See also `run-scheme' in
;; the `cmuscheme' package and also the implementation-specific
;; `xscheme' package.
;; Here's a recipe to generate a TAGS file for DSSSL, by the way:
;; etags --lang=scheme --regex='/[ \t]*(\(mode\|element\)[ \t
;; ]+\([^ \t(
;; ]+\)/\2/' --regex='/[ \t]*(element[ \t
;; ]*([^)]+[ \t
;; ]+\([^)]+\)[ \t
;; ]*)/\1/' --regex='/(declare[^ \t
;; ]*[ \t
;; ]+\([^ \t
;; ]+\)/\1/' "$@"
;;; Code:
(require 'lisp-mode)
(defvar scheme-mode-syntax-table nil "")
(if (not scheme-mode-syntax-table)
(let ((i 0))
(setq scheme-mode-syntax-table (make-syntax-table))
(set-syntax-table scheme-mode-syntax-table)
;; Default is atom-constituent.
(while (< i 256)
(modify-syntax-entry i "_ ")
(setq i (1+ i)))
;; Word components.
(setq i ?0)
(while (<= i ?9)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?A)
(while (<= i ?Z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?a)
(while (<= i ?z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
;; Whitespace
(modify-syntax-entry ?\t " ")
(modify-syntax-entry ?\n "> ")
(modify-syntax-entry ?\f " ")
(modify-syntax-entry ?\r " ")
(modify-syntax-entry ? " ")
;; These characters are delimiters but otherwise undefined.
;; Brackets and braces balance for editing convenience.
(modify-syntax-entry ?\[ "(] ")
(modify-syntax-entry ?\] ")[ ")
(modify-syntax-entry ?{ "(} ")
(modify-syntax-entry ?} "){ ")
(modify-syntax-entry ?\| " 23")
;; Other atom delimiters
(modify-syntax-entry ?\( "() ")
(modify-syntax-entry ?\) ")( ")
(modify-syntax-entry ?\; "< ")
(modify-syntax-entry ?\" "\" ")
(modify-syntax-entry ?' " p")
(modify-syntax-entry ?` " p")
;; Special characters
(modify-syntax-entry ?, "_ p")
(modify-syntax-entry ?@ "_ p")
(modify-syntax-entry ?# "_ p14")
(modify-syntax-entry ?\\ "\\ ")))
(defvar scheme-mode-abbrev-table nil "")
(define-abbrev-table 'scheme-mode-abbrev-table ())
(defvar scheme-imenu-generic-expression
'((nil
"^(define\\(\\|-\\(generic\\(\\|-procedure\\)\\|method\\)\\)*\\s-+(?\\(\\sw+\\)" 4)
("Types"
"^(define-class\\s-+(?\\(\\sw+\\)" 1)
("Macros"
"^(\\(defmacro\\|define-macro\\|define-syntax\\)\\s-+(?\\(\\sw+\\)" 2))
"Imenu generic expression for Scheme mode. See `imenu-generic-expression'.")
(defun scheme-mode-variables ()
(set-syntax-table scheme-mode-syntax-table)
(setq local-abbrev-table scheme-mode-abbrev-table)
(make-local-variable 'paragraph-start)
(setq paragraph-start (concat "$\\|" page-delimiter))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
(make-local-variable 'paragraph-ignore-fill-prefix)
(setq paragraph-ignore-fill-prefix t)
(make-local-variable 'fill-paragraph-function)
(setq fill-paragraph-function 'lisp-fill-paragraph)
;; Adaptive fill mode gets in the way of auto-fill,
;; and should make no difference for explicit fill
;; because lisp-fill-paragraph should do the job.
(make-local-variable 'adaptive-fill-mode)
(setq adaptive-fill-mode nil)
(make-local-variable 'normal-auto-fill-function)
(setq normal-auto-fill-function 'lisp-mode-auto-fill)
(make-local-variable 'indent-line-function)
(setq indent-line-function 'lisp-indent-line)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'outline-regexp)
(setq outline-regexp ";;; \\|(....")
(make-local-variable 'comment-start)
(setq comment-start ";")
(make-local-variable 'comment-start-skip)
;; Look within the line for a ; following an even number of backslashes
;; after either a non-backslash or the line beginning.
(setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+[ \t]*")
(make-local-variable 'comment-column)
(setq comment-column 40)
(make-local-variable 'comment-indent-function)
(setq comment-indent-function 'lisp-comment-indent)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'lisp-indent-function)
(set lisp-indent-function 'scheme-indent-function)
(setq mode-line-process '("" scheme-mode-line-process))
(make-local-variable 'imenu-case-fold-search)
(setq imenu-case-fold-search t)
(make-local-variable 'imenu-generic-expression)
(setq imenu-generic-expression scheme-imenu-generic-expression)
(make-local-variable 'imenu-syntax-alist)
(setq imenu-syntax-alist '(("+-*/.<>=?!$%_&~^:" . "w")))
(make-local-variable 'font-lock-defaults)
(setq font-lock-defaults
'((scheme-font-lock-keywords
scheme-font-lock-keywords-1 scheme-font-lock-keywords-2)
nil t (("+-*/.<>=!?$%_&~^:" . "w")) beginning-of-defun
(font-lock-mark-block-function . mark-defun))))
(defvar scheme-mode-line-process "")
(defvar scheme-mode-map nil
"Keymap for Scheme mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")
(if scheme-mode-map
()
(let ((map (make-sparse-keymap "Scheme")))
(setq scheme-mode-map
(nconc (make-sparse-keymap) shared-lisp-mode-map))
(define-key scheme-mode-map [menu-bar] (make-sparse-keymap))
(define-key scheme-mode-map [menu-bar scheme]
(cons "Scheme" map))
(define-key map [run-scheme] '("Run Inferior Scheme" . run-scheme))
(define-key map [uncomment-region]
'("Uncomment Out Region" . (lambda (beg end)
(interactive "r")
(comment-region beg end '(4)))))
(define-key map [comment-region] '("Comment Out Region" . comment-region))
(define-key map [indent-region] '("Indent Region" . indent-region))
(define-key map [indent-line] '("Indent Line" . lisp-indent-line))
(put 'comment-region 'menu-enable 'mark-active)
(put 'uncomment-region 'menu-enable 'mark-active)
(put 'indent-region 'menu-enable 'mark-active)))
;; Used by cmuscheme
(defun scheme-mode-commands (map)
;;(define-key map "\t" 'indent-for-tab-command) ; default
(define-key map "\177" 'backward-delete-char-untabify)
(define-key map "\e\C-q" 'indent-sexp))
;;;###autoload
(defun scheme-mode ()
"Major mode for editing Scheme code.
Editing commands are similar to those of lisp-mode.
In addition, if an inferior Scheme process is running, some additional
commands will be defined, for evaluating expressions and controlling
the interpreter, and the state of the process will be displayed in the
modeline of all Scheme buffers. The names of commands that interact
with the Scheme process start with \"xscheme-\". For more information
see the documentation for xscheme-interaction-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entry to this mode calls the value of scheme-mode-hook
if that value is non-nil."
(interactive)
(kill-all-local-variables)
(scheme-mode-initialize)
(scheme-mode-variables)
(run-hooks 'scheme-mode-hook))
(defun scheme-mode-initialize ()
(use-local-map scheme-mode-map)
(setq major-mode 'scheme-mode)
(setq mode-name "Scheme"))
(defgroup scheme nil
"Editing Scheme code"
:group 'lisp)
(defcustom scheme-mit-dialect t
"If non-nil, scheme mode is specialized for MIT Scheme.
Set this to nil if you normally use another dialect."
:type 'boolean
:group 'scheme)
(defcustom dsssl-sgml-declaration
"<!DOCTYPE style-sheet PUBLIC \"-//James Clark//DTD DSSSL Style Sheet//EN\">
"
"*An SGML declaration for the DSSSL file.
If it is defined as a string this will be inserted into an empty buffer
which is in dsssl-mode. It is typically James Clark's style-sheet
doctype, as required for Jade."
:type '(choice (string :tag "Specified string")
(const :tag "None" :value nil))
:group 'scheme)
(defcustom scheme-mode-hook nil
"Normal hook (list of functions) run when entering scheme-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defcustom dsssl-mode-hook nil
"Normal hook (list of functions) run when entering dsssl-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defvar dsssl-imenu-generic-expression
;; Perhaps this should also look for the style-sheet DTD tags. I'm
;; not sure it's the best way to organize it; perhaps one type
;; should be at the first level, though you don't see this anyhow if
;; it gets split up.
'(("Defines"
"^(define\\s-+(?\\(\\sw+\\)" 1)
("Modes"
"^\\s-*(mode\\s-+\\(\\(\\sw\\|\\s-\\)+\\)" 1)
("Elements"
;; (element foo ...) or (element (foo bar ...) ...)
;; Fixme: Perhaps it should do `root'.
"^\\s-*(element\\s-+(?\\(\\(\\sw\\|\\s-\\)+\\))?" 1)
("Declarations"
"^(declare\\(-\\sw+\\)+\\>\\s-+\\(\\sw+\\)" 2))
"Imenu generic expression for DSSSL mode. See `imenu-generic-expression'.")
(defconst scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Declarations. <NAME> <<EMAIL>> says
;; this works for SOS, STklos, SCOOPS, Meroon and Tiny CLOS.
(list (concat "(\\(define\\*?\\("
;; Function names.
"\\(\\|-public\\|-method\\|-generic\\(-procedure\\)?\\)\\|"
;; Macro names, as variable names. A bit dubious, this.
"\\(-syntax\\)\\|"
;; Class names.
"-class"
;; Guile modules.
"\\|-module"
"\\)\\)\\>"
;; Any whitespace and declared object.
"[ \t]*(?"
"\\(\\sw+\\)?")
'(1 font-lock-keyword-face)
'(6 (cond ((match-beginning 3) font-lock-function-name-face)
((match-beginning 5) font-lock-variable-name-face)
(t font-lock-type-face))
nil t))
))
"Subdued expressions to highlight in Scheme modes.")
(defconst scheme-font-lock-keywords-2
(append scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Control structures.
(cons
(concat
"(" (regexp-opt
'("begin" "call-with-current-continuation" "call/cc"
"call-with-input-file" "call-with-output-file" "case" "cond"
"do" "else" "for-each" "if" "lambda"
"let" "let*" "let-syntax" "letrec" "letrec-syntax"
;; <NAME> <<EMAIL>> wants:
"and" "or" "delay"
;; <NAME> <<EMAIL>> says don't bother:
;;"quasiquote" "quote" "unquote" "unquote-splicing"
"map" "syntax" "syntax-rules") t)
"\\>") 1)
;;
;; <NAME> <<EMAIL>> for SOS/STklos class specifiers.
'("\\<<\\sw+>\\>" . font-lock-type-face)
;;
;; Scheme `:' keywords as builtins.
'("\\<:\\sw+\\>" . font-lock-builtin-face)
)))
"Gaudy expressions to highlight in Scheme modes.")
(defvar scheme-font-lock-keywords scheme-font-lock-keywords-1
"Default expressions to highlight in Scheme modes.")
;;;###autoload
(defun dsssl-mode ()
"Major mode for editing DSSSL code.
Editing commands are similar to those of lisp-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entering this mode runs the hooks `scheme-mode-hook' and then
`dsssl-mode-hook' and inserts the value of `dsssl-sgml-declaration' if
that variable's value is a string."
(interactive)
(kill-all-local-variables)
(use-local-map scheme-mode-map)
(scheme-mode-initialize)
(make-local-variable 'page-delimiter)
(setq page-delimiter "^;;;" ; ^L not valid SGML char
major-mode 'dsssl-mode
mode-name "DSSSL")
;; Insert a suitable SGML declaration into an empty buffer.
(and (zerop (buffer-size))
(stringp dsssl-sgml-declaration)
(not buffer-read-only)
(insert dsssl-sgml-declaration))
(scheme-mode-variables)
(setq font-lock-defaults '(dsssl-font-lock-keywords
nil t (("+-*/.<>=?$%_&~^:" . "w"))
beginning-of-defun
(font-lock-mark-block-function . mark-defun)))
(setq imenu-case-fold-search nil)
(setq imenu-generic-expression dsssl-imenu-generic-expression)
(setq imenu-syntax-alist '(("+-*/.<>=?$%_&~^:" . "w")))
(run-hooks 'scheme-mode-hook)
(run-hooks 'dsssl-mode-hook))
;; Extra syntax for DSSSL. This isn't separated from Scheme, but
;; shouldn't cause much trouble in scheme-mode.
(put 'element 'scheme-indent-function 1)
(put 'mode 'scheme-indent-function 1)
(put 'with-mode 'scheme-indent-function 1)
(put 'make 'scheme-indent-function 1)
(put 'style 'scheme-indent-function 1)
(put 'root 'scheme-indent-function 1)
(defvar dsssl-font-lock-keywords
(eval-when-compile
(list
;; Similar to Scheme
(list "(\\(define\\(-\\w+\\)?\\)\\>[ ]*\\\((?\\)\\(\\sw+\\)\\>"
'(1 font-lock-keyword-face)
'(4 font-lock-function-name-face))
(cons
(concat "(\\("
;; (make-regexp '("case" "cond" "else" "if" "lambda"
;; "let" "let*" "letrec" "and" "or" "map" "with-mode"))
"and\\|c\\(ase\\|ond\\)\\|else\\|if\\|"
"l\\(ambda\\|et\\(\\|*\\|rec\\)\\)\\|map\\|or\\|with-mode"
"\\)\\>")
1)
;; DSSSL syntax
'("(\\(element\\|mode\\|declare-\\w+\\)\\>[ ]*\\(\\sw+\\)"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("(\\(element\\)\\>[ ]*(\\(\\S)+\\))"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("\\<\\sw+:\\>" . font-lock-constant-face) ; trailing `:' c.f. scheme
;; SGML markup (from sgml-mode) :
'("<\\([!?][-a-z0-9]+\\)" 1 font-lock-keyword-face)
'("<\\(/?[-a-z0-9]+\\)" 1 font-lock-function-name-face)))
"Default expressions to highlight in DSSSL mode.")
(defvar calculate-lisp-indent-last-sexp)
;; Copied from lisp-indent-function, but with gets of
;; scheme-indent-{function,hook}.
(defun scheme-indent-function (indent-point state)
(let ((normal-indent (current-column)))
(goto-char (1+ (elt state 1)))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(if (and (elt state 2)
(not (looking-at "\\sw\\|\\s_")))
;; car of form doesn't seem to be a a symbol
(progn
(if (not (> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp))
(progn (goto-char calculate-lisp-indent-last-sexp)
(beginning-of-line)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp 0 t)))
;; Indent under the list or under the first sexp on the same
;; line as calculate-lisp-indent-last-sexp. Note that first
;; thing on that line has to be complete sexp since we are
;; inside the innermost containing sexp.
(backward-prefix-chars)
(current-column))
(let ((function (buffer-substring (point)
(progn (forward-sexp 1) (point))))
method)
(setq method (or (get (intern-soft function) 'scheme-indent-function)
(get (intern-soft function) 'scheme-indent-hook)))
(cond ((or (eq method 'defun)
(and (null method)
(> (length function) 3)
(string-match "\\`def" function)))
(lisp-indent-defform state indent-point))
((integerp method)
(lisp-indent-specform method state
indent-point normal-indent))
(method
(funcall method state indent-point normal-indent)))))))
;;; Let is different in Scheme
(defun would-be-symbol (string)
(not (string-equal (substring string 0 1) "(")))
(defun next-sexp-as-string ()
;; Assumes that protected by a save-excursion
(forward-sexp 1)
(let ((the-end (point)))
(backward-sexp 1)
(buffer-substring (point) the-end)))
;; This is correct but too slow.
;; The one below works almost always.
;;(defun scheme-let-indent (state indent-point)
;; (if (would-be-symbol (next-sexp-as-string))
;; (scheme-indent-specform 2 state indent-point)
;; (scheme-indent-specform 1 state indent-point)))
(defun scheme-let-indent (state indent-point normal-indent)
(skip-chars-forward " \t")
(if (looking-at "[-a-zA-Z0-9+*/?!@$%^&_:~]")
(lisp-indent-specform 2 state indent-point normal-indent)
(lisp-indent-specform 1 state indent-point normal-indent)))
;; (put 'begin 'scheme-indent-function 0), say, causes begin to be indented
;; like defun if the first form is placed on the next line, otherwise
;; it is indented like any other form (i.e. forms line up under first).
(put 'begin 'scheme-indent-function 0)
(put 'case 'scheme-indent-function 1)
(put 'delay 'scheme-indent-function 0)
(put 'do 'scheme-indent-function 2)
(put 'lambda 'scheme-indent-function 1)
(put 'let 'scheme-indent-function 'scheme-let-indent)
(put 'let* 'scheme-indent-function 1)
(put 'letrec 'scheme-indent-function 1)
(put 'sequence 'scheme-indent-function 0) ; SICP, not r4rs
(put 'let-syntax 'scheme-indent-function 1)
(put 'letrec-syntax 'scheme-indent-function 1)
(put 'syntax-rules 'scheme-indent-function 1)
(put 'call-with-input-file 'scheme-indent-function 1)
(put 'with-input-from-file 'scheme-indent-function 1)
(put 'with-input-from-port 'scheme-indent-function 1)
(put 'call-with-output-file 'scheme-indent-function 1)
(put 'with-output-to-file 'scheme-indent-function 1)
(put 'with-output-to-port 'scheme-indent-function 1)
(put 'call-with-values 'scheme-indent-function 1) ; r5rs?
(put 'dynamic-wind 'scheme-indent-function 3) ; r5rs?
;;;; MIT Scheme specific indentation.
(if scheme-mit-dialect
(progn
(put 'fluid-let 'scheme-indent-function 1)
(put 'in-package 'scheme-indent-function 1)
(put 'local-declare 'scheme-indent-function 1)
(put 'macro 'scheme-indent-function 1)
(put 'make-environment 'scheme-indent-function 0)
(put 'named-lambda 'scheme-indent-function 1)
(put 'using-syntax 'scheme-indent-function 1)
(put 'with-input-from-string 'scheme-indent-function 1)
(put 'with-output-to-string 'scheme-indent-function 0)
(put 'with-values 'scheme-indent-function 1)
(put 'syntax-table-define 'scheme-indent-function 2)
(put 'list-transform-positive 'scheme-indent-function 1)
(put 'list-transform-negative 'scheme-indent-function 1)
(put 'list-search-positive 'scheme-indent-function 1)
(put 'list-search-negative 'scheme-indent-function 1)
(put 'access-components 'scheme-indent-function 1)
(put 'assignment-components 'scheme-indent-function 1)
(put 'combination-components 'scheme-indent-function 1)
(put 'comment-components 'scheme-indent-function 1)
(put 'conditional-components 'scheme-indent-function 1)
(put 'disjunction-components 'scheme-indent-function 1)
(put 'declaration-components 'scheme-indent-function 1)
(put 'definition-components 'scheme-indent-function 1)
(put 'delay-components 'scheme-indent-function 1)
(put 'in-package-components 'scheme-indent-function 1)
(put 'lambda-components 'scheme-indent-function 1)
(put 'lambda-components* 'scheme-indent-function 1)
(put 'lambda-components** 'scheme-indent-function 1)
(put 'open-block-components 'scheme-indent-function 1)
(put 'pathname-components 'scheme-indent-function 1)
(put 'procedure-components 'scheme-indent-function 1)
(put 'sequence-components 'scheme-indent-function 1)
(put 'unassigned\?-components 'scheme-indent-function 1)
(put 'unbound\?-components 'scheme-indent-function 1)
(put 'variable-components 'scheme-indent-function 1)))
(provide 'scheme)
;;; scheme.el ends here
| true | ;;; scheme.el --- Scheme (and DSSSL) editing mode.
;; Copyright (C) 1986, 87, 88, 97, 1998 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Adapted-by: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: languages, 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; The major mode for editing Scheme-type Lisp code, very similar to
;; the Lisp mode documented in the Emacs manual. `dsssl-mode' is a
;; variant of scheme-mode for editing DSSSL specifications for SGML
;; documents. [As of Apr 1997, some pointers for DSSSL may be found,
;; for instance, at <URL:http://www.sil.org/sgml/related.html#dsssl>.]
;; All these Lisp-ish modes vary basically in details of the language
;; syntax they highlight/indent/index, but dsssl-mode uses "^;;;" as
;; the page-delimiter since ^L isn't normally a legal SGML character.
;;
;; For interacting with a Scheme interpreter See also `run-scheme' in
;; the `cmuscheme' package and also the implementation-specific
;; `xscheme' package.
;; Here's a recipe to generate a TAGS file for DSSSL, by the way:
;; etags --lang=scheme --regex='/[ \t]*(\(mode\|element\)[ \t
;; ]+\([^ \t(
;; ]+\)/\2/' --regex='/[ \t]*(element[ \t
;; ]*([^)]+[ \t
;; ]+\([^)]+\)[ \t
;; ]*)/\1/' --regex='/(declare[^ \t
;; ]*[ \t
;; ]+\([^ \t
;; ]+\)/\1/' "$@"
;;; Code:
(require 'lisp-mode)
(defvar scheme-mode-syntax-table nil "")
(if (not scheme-mode-syntax-table)
(let ((i 0))
(setq scheme-mode-syntax-table (make-syntax-table))
(set-syntax-table scheme-mode-syntax-table)
;; Default is atom-constituent.
(while (< i 256)
(modify-syntax-entry i "_ ")
(setq i (1+ i)))
;; Word components.
(setq i ?0)
(while (<= i ?9)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?A)
(while (<= i ?Z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
(setq i ?a)
(while (<= i ?z)
(modify-syntax-entry i "w ")
(setq i (1+ i)))
;; Whitespace
(modify-syntax-entry ?\t " ")
(modify-syntax-entry ?\n "> ")
(modify-syntax-entry ?\f " ")
(modify-syntax-entry ?\r " ")
(modify-syntax-entry ? " ")
;; These characters are delimiters but otherwise undefined.
;; Brackets and braces balance for editing convenience.
(modify-syntax-entry ?\[ "(] ")
(modify-syntax-entry ?\] ")[ ")
(modify-syntax-entry ?{ "(} ")
(modify-syntax-entry ?} "){ ")
(modify-syntax-entry ?\| " 23")
;; Other atom delimiters
(modify-syntax-entry ?\( "() ")
(modify-syntax-entry ?\) ")( ")
(modify-syntax-entry ?\; "< ")
(modify-syntax-entry ?\" "\" ")
(modify-syntax-entry ?' " p")
(modify-syntax-entry ?` " p")
;; Special characters
(modify-syntax-entry ?, "_ p")
(modify-syntax-entry ?@ "_ p")
(modify-syntax-entry ?# "_ p14")
(modify-syntax-entry ?\\ "\\ ")))
(defvar scheme-mode-abbrev-table nil "")
(define-abbrev-table 'scheme-mode-abbrev-table ())
(defvar scheme-imenu-generic-expression
'((nil
"^(define\\(\\|-\\(generic\\(\\|-procedure\\)\\|method\\)\\)*\\s-+(?\\(\\sw+\\)" 4)
("Types"
"^(define-class\\s-+(?\\(\\sw+\\)" 1)
("Macros"
"^(\\(defmacro\\|define-macro\\|define-syntax\\)\\s-+(?\\(\\sw+\\)" 2))
"Imenu generic expression for Scheme mode. See `imenu-generic-expression'.")
(defun scheme-mode-variables ()
(set-syntax-table scheme-mode-syntax-table)
(setq local-abbrev-table scheme-mode-abbrev-table)
(make-local-variable 'paragraph-start)
(setq paragraph-start (concat "$\\|" page-delimiter))
(make-local-variable 'paragraph-separate)
(setq paragraph-separate paragraph-start)
(make-local-variable 'paragraph-ignore-fill-prefix)
(setq paragraph-ignore-fill-prefix t)
(make-local-variable 'fill-paragraph-function)
(setq fill-paragraph-function 'lisp-fill-paragraph)
;; Adaptive fill mode gets in the way of auto-fill,
;; and should make no difference for explicit fill
;; because lisp-fill-paragraph should do the job.
(make-local-variable 'adaptive-fill-mode)
(setq adaptive-fill-mode nil)
(make-local-variable 'normal-auto-fill-function)
(setq normal-auto-fill-function 'lisp-mode-auto-fill)
(make-local-variable 'indent-line-function)
(setq indent-line-function 'lisp-indent-line)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'outline-regexp)
(setq outline-regexp ";;; \\|(....")
(make-local-variable 'comment-start)
(setq comment-start ";")
(make-local-variable 'comment-start-skip)
;; Look within the line for a ; following an even number of backslashes
;; after either a non-backslash or the line beginning.
(setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+[ \t]*")
(make-local-variable 'comment-column)
(setq comment-column 40)
(make-local-variable 'comment-indent-function)
(setq comment-indent-function 'lisp-comment-indent)
(make-local-variable 'parse-sexp-ignore-comments)
(setq parse-sexp-ignore-comments t)
(make-local-variable 'lisp-indent-function)
(set lisp-indent-function 'scheme-indent-function)
(setq mode-line-process '("" scheme-mode-line-process))
(make-local-variable 'imenu-case-fold-search)
(setq imenu-case-fold-search t)
(make-local-variable 'imenu-generic-expression)
(setq imenu-generic-expression scheme-imenu-generic-expression)
(make-local-variable 'imenu-syntax-alist)
(setq imenu-syntax-alist '(("+-*/.<>=?!$%_&~^:" . "w")))
(make-local-variable 'font-lock-defaults)
(setq font-lock-defaults
'((scheme-font-lock-keywords
scheme-font-lock-keywords-1 scheme-font-lock-keywords-2)
nil t (("+-*/.<>=!?$%_&~^:" . "w")) beginning-of-defun
(font-lock-mark-block-function . mark-defun))))
(defvar scheme-mode-line-process "")
(defvar scheme-mode-map nil
"Keymap for Scheme mode.
All commands in `shared-lisp-mode-map' are inherited by this map.")
(if scheme-mode-map
()
(let ((map (make-sparse-keymap "Scheme")))
(setq scheme-mode-map
(nconc (make-sparse-keymap) shared-lisp-mode-map))
(define-key scheme-mode-map [menu-bar] (make-sparse-keymap))
(define-key scheme-mode-map [menu-bar scheme]
(cons "Scheme" map))
(define-key map [run-scheme] '("Run Inferior Scheme" . run-scheme))
(define-key map [uncomment-region]
'("Uncomment Out Region" . (lambda (beg end)
(interactive "r")
(comment-region beg end '(4)))))
(define-key map [comment-region] '("Comment Out Region" . comment-region))
(define-key map [indent-region] '("Indent Region" . indent-region))
(define-key map [indent-line] '("Indent Line" . lisp-indent-line))
(put 'comment-region 'menu-enable 'mark-active)
(put 'uncomment-region 'menu-enable 'mark-active)
(put 'indent-region 'menu-enable 'mark-active)))
;; Used by cmuscheme
(defun scheme-mode-commands (map)
;;(define-key map "\t" 'indent-for-tab-command) ; default
(define-key map "\177" 'backward-delete-char-untabify)
(define-key map "\e\C-q" 'indent-sexp))
;;;###autoload
(defun scheme-mode ()
"Major mode for editing Scheme code.
Editing commands are similar to those of lisp-mode.
In addition, if an inferior Scheme process is running, some additional
commands will be defined, for evaluating expressions and controlling
the interpreter, and the state of the process will be displayed in the
modeline of all Scheme buffers. The names of commands that interact
with the Scheme process start with \"xscheme-\". For more information
see the documentation for xscheme-interaction-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entry to this mode calls the value of scheme-mode-hook
if that value is non-nil."
(interactive)
(kill-all-local-variables)
(scheme-mode-initialize)
(scheme-mode-variables)
(run-hooks 'scheme-mode-hook))
(defun scheme-mode-initialize ()
(use-local-map scheme-mode-map)
(setq major-mode 'scheme-mode)
(setq mode-name "Scheme"))
(defgroup scheme nil
"Editing Scheme code"
:group 'lisp)
(defcustom scheme-mit-dialect t
"If non-nil, scheme mode is specialized for MIT Scheme.
Set this to nil if you normally use another dialect."
:type 'boolean
:group 'scheme)
(defcustom dsssl-sgml-declaration
"<!DOCTYPE style-sheet PUBLIC \"-//James Clark//DTD DSSSL Style Sheet//EN\">
"
"*An SGML declaration for the DSSSL file.
If it is defined as a string this will be inserted into an empty buffer
which is in dsssl-mode. It is typically James Clark's style-sheet
doctype, as required for Jade."
:type '(choice (string :tag "Specified string")
(const :tag "None" :value nil))
:group 'scheme)
(defcustom scheme-mode-hook nil
"Normal hook (list of functions) run when entering scheme-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defcustom dsssl-mode-hook nil
"Normal hook (list of functions) run when entering dsssl-mode.
See `run-hooks'."
:type 'hook
:group 'scheme)
(defvar dsssl-imenu-generic-expression
;; Perhaps this should also look for the style-sheet DTD tags. I'm
;; not sure it's the best way to organize it; perhaps one type
;; should be at the first level, though you don't see this anyhow if
;; it gets split up.
'(("Defines"
"^(define\\s-+(?\\(\\sw+\\)" 1)
("Modes"
"^\\s-*(mode\\s-+\\(\\(\\sw\\|\\s-\\)+\\)" 1)
("Elements"
;; (element foo ...) or (element (foo bar ...) ...)
;; Fixme: Perhaps it should do `root'.
"^\\s-*(element\\s-+(?\\(\\(\\sw\\|\\s-\\)+\\))?" 1)
("Declarations"
"^(declare\\(-\\sw+\\)+\\>\\s-+\\(\\sw+\\)" 2))
"Imenu generic expression for DSSSL mode. See `imenu-generic-expression'.")
(defconst scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Declarations. PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> says
;; this works for SOS, STklos, SCOOPS, Meroon and Tiny CLOS.
(list (concat "(\\(define\\*?\\("
;; Function names.
"\\(\\|-public\\|-method\\|-generic\\(-procedure\\)?\\)\\|"
;; Macro names, as variable names. A bit dubious, this.
"\\(-syntax\\)\\|"
;; Class names.
"-class"
;; Guile modules.
"\\|-module"
"\\)\\)\\>"
;; Any whitespace and declared object.
"[ \t]*(?"
"\\(\\sw+\\)?")
'(1 font-lock-keyword-face)
'(6 (cond ((match-beginning 3) font-lock-function-name-face)
((match-beginning 5) font-lock-variable-name-face)
(t font-lock-type-face))
nil t))
))
"Subdued expressions to highlight in Scheme modes.")
(defconst scheme-font-lock-keywords-2
(append scheme-font-lock-keywords-1
(eval-when-compile
(list
;;
;; Control structures.
(cons
(concat
"(" (regexp-opt
'("begin" "call-with-current-continuation" "call/cc"
"call-with-input-file" "call-with-output-file" "case" "cond"
"do" "else" "for-each" "if" "lambda"
"let" "let*" "let-syntax" "letrec" "letrec-syntax"
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> wants:
"and" "or" "delay"
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> says don't bother:
;;"quasiquote" "quote" "unquote" "unquote-splicing"
"map" "syntax" "syntax-rules") t)
"\\>") 1)
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> for SOS/STklos class specifiers.
'("\\<<\\sw+>\\>" . font-lock-type-face)
;;
;; Scheme `:' keywords as builtins.
'("\\<:\\sw+\\>" . font-lock-builtin-face)
)))
"Gaudy expressions to highlight in Scheme modes.")
(defvar scheme-font-lock-keywords scheme-font-lock-keywords-1
"Default expressions to highlight in Scheme modes.")
;;;###autoload
(defun dsssl-mode ()
"Major mode for editing DSSSL code.
Editing commands are similar to those of lisp-mode.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{scheme-mode-map}
Entering this mode runs the hooks `scheme-mode-hook' and then
`dsssl-mode-hook' and inserts the value of `dsssl-sgml-declaration' if
that variable's value is a string."
(interactive)
(kill-all-local-variables)
(use-local-map scheme-mode-map)
(scheme-mode-initialize)
(make-local-variable 'page-delimiter)
(setq page-delimiter "^;;;" ; ^L not valid SGML char
major-mode 'dsssl-mode
mode-name "DSSSL")
;; Insert a suitable SGML declaration into an empty buffer.
(and (zerop (buffer-size))
(stringp dsssl-sgml-declaration)
(not buffer-read-only)
(insert dsssl-sgml-declaration))
(scheme-mode-variables)
(setq font-lock-defaults '(dsssl-font-lock-keywords
nil t (("+-*/.<>=?$%_&~^:" . "w"))
beginning-of-defun
(font-lock-mark-block-function . mark-defun)))
(setq imenu-case-fold-search nil)
(setq imenu-generic-expression dsssl-imenu-generic-expression)
(setq imenu-syntax-alist '(("+-*/.<>=?$%_&~^:" . "w")))
(run-hooks 'scheme-mode-hook)
(run-hooks 'dsssl-mode-hook))
;; Extra syntax for DSSSL. This isn't separated from Scheme, but
;; shouldn't cause much trouble in scheme-mode.
(put 'element 'scheme-indent-function 1)
(put 'mode 'scheme-indent-function 1)
(put 'with-mode 'scheme-indent-function 1)
(put 'make 'scheme-indent-function 1)
(put 'style 'scheme-indent-function 1)
(put 'root 'scheme-indent-function 1)
(defvar dsssl-font-lock-keywords
(eval-when-compile
(list
;; Similar to Scheme
(list "(\\(define\\(-\\w+\\)?\\)\\>[ ]*\\\((?\\)\\(\\sw+\\)\\>"
'(1 font-lock-keyword-face)
'(4 font-lock-function-name-face))
(cons
(concat "(\\("
;; (make-regexp '("case" "cond" "else" "if" "lambda"
;; "let" "let*" "letrec" "and" "or" "map" "with-mode"))
"and\\|c\\(ase\\|ond\\)\\|else\\|if\\|"
"l\\(ambda\\|et\\(\\|*\\|rec\\)\\)\\|map\\|or\\|with-mode"
"\\)\\>")
1)
;; DSSSL syntax
'("(\\(element\\|mode\\|declare-\\w+\\)\\>[ ]*\\(\\sw+\\)"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("(\\(element\\)\\>[ ]*(\\(\\S)+\\))"
(1 font-lock-keyword-face)
(2 font-lock-type-face))
'("\\<\\sw+:\\>" . font-lock-constant-face) ; trailing `:' c.f. scheme
;; SGML markup (from sgml-mode) :
'("<\\([!?][-a-z0-9]+\\)" 1 font-lock-keyword-face)
'("<\\(/?[-a-z0-9]+\\)" 1 font-lock-function-name-face)))
"Default expressions to highlight in DSSSL mode.")
(defvar calculate-lisp-indent-last-sexp)
;; Copied from lisp-indent-function, but with gets of
;; scheme-indent-{function,hook}.
(defun scheme-indent-function (indent-point state)
(let ((normal-indent (current-column)))
(goto-char (1+ (elt state 1)))
(parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
(if (and (elt state 2)
(not (looking-at "\\sw\\|\\s_")))
;; car of form doesn't seem to be a a symbol
(progn
(if (not (> (save-excursion (forward-line 1) (point))
calculate-lisp-indent-last-sexp))
(progn (goto-char calculate-lisp-indent-last-sexp)
(beginning-of-line)
(parse-partial-sexp (point)
calculate-lisp-indent-last-sexp 0 t)))
;; Indent under the list or under the first sexp on the same
;; line as calculate-lisp-indent-last-sexp. Note that first
;; thing on that line has to be complete sexp since we are
;; inside the innermost containing sexp.
(backward-prefix-chars)
(current-column))
(let ((function (buffer-substring (point)
(progn (forward-sexp 1) (point))))
method)
(setq method (or (get (intern-soft function) 'scheme-indent-function)
(get (intern-soft function) 'scheme-indent-hook)))
(cond ((or (eq method 'defun)
(and (null method)
(> (length function) 3)
(string-match "\\`def" function)))
(lisp-indent-defform state indent-point))
((integerp method)
(lisp-indent-specform method state
indent-point normal-indent))
(method
(funcall method state indent-point normal-indent)))))))
;;; Let is different in Scheme
(defun would-be-symbol (string)
(not (string-equal (substring string 0 1) "(")))
(defun next-sexp-as-string ()
;; Assumes that protected by a save-excursion
(forward-sexp 1)
(let ((the-end (point)))
(backward-sexp 1)
(buffer-substring (point) the-end)))
;; This is correct but too slow.
;; The one below works almost always.
;;(defun scheme-let-indent (state indent-point)
;; (if (would-be-symbol (next-sexp-as-string))
;; (scheme-indent-specform 2 state indent-point)
;; (scheme-indent-specform 1 state indent-point)))
(defun scheme-let-indent (state indent-point normal-indent)
(skip-chars-forward " \t")
(if (looking-at "[-a-zA-Z0-9+*/?!@$%^&_:~]")
(lisp-indent-specform 2 state indent-point normal-indent)
(lisp-indent-specform 1 state indent-point normal-indent)))
;; (put 'begin 'scheme-indent-function 0), say, causes begin to be indented
;; like defun if the first form is placed on the next line, otherwise
;; it is indented like any other form (i.e. forms line up under first).
(put 'begin 'scheme-indent-function 0)
(put 'case 'scheme-indent-function 1)
(put 'delay 'scheme-indent-function 0)
(put 'do 'scheme-indent-function 2)
(put 'lambda 'scheme-indent-function 1)
(put 'let 'scheme-indent-function 'scheme-let-indent)
(put 'let* 'scheme-indent-function 1)
(put 'letrec 'scheme-indent-function 1)
(put 'sequence 'scheme-indent-function 0) ; SICP, not r4rs
(put 'let-syntax 'scheme-indent-function 1)
(put 'letrec-syntax 'scheme-indent-function 1)
(put 'syntax-rules 'scheme-indent-function 1)
(put 'call-with-input-file 'scheme-indent-function 1)
(put 'with-input-from-file 'scheme-indent-function 1)
(put 'with-input-from-port 'scheme-indent-function 1)
(put 'call-with-output-file 'scheme-indent-function 1)
(put 'with-output-to-file 'scheme-indent-function 1)
(put 'with-output-to-port 'scheme-indent-function 1)
(put 'call-with-values 'scheme-indent-function 1) ; r5rs?
(put 'dynamic-wind 'scheme-indent-function 3) ; r5rs?
;;;; MIT Scheme specific indentation.
(if scheme-mit-dialect
(progn
(put 'fluid-let 'scheme-indent-function 1)
(put 'in-package 'scheme-indent-function 1)
(put 'local-declare 'scheme-indent-function 1)
(put 'macro 'scheme-indent-function 1)
(put 'make-environment 'scheme-indent-function 0)
(put 'named-lambda 'scheme-indent-function 1)
(put 'using-syntax 'scheme-indent-function 1)
(put 'with-input-from-string 'scheme-indent-function 1)
(put 'with-output-to-string 'scheme-indent-function 0)
(put 'with-values 'scheme-indent-function 1)
(put 'syntax-table-define 'scheme-indent-function 2)
(put 'list-transform-positive 'scheme-indent-function 1)
(put 'list-transform-negative 'scheme-indent-function 1)
(put 'list-search-positive 'scheme-indent-function 1)
(put 'list-search-negative 'scheme-indent-function 1)
(put 'access-components 'scheme-indent-function 1)
(put 'assignment-components 'scheme-indent-function 1)
(put 'combination-components 'scheme-indent-function 1)
(put 'comment-components 'scheme-indent-function 1)
(put 'conditional-components 'scheme-indent-function 1)
(put 'disjunction-components 'scheme-indent-function 1)
(put 'declaration-components 'scheme-indent-function 1)
(put 'definition-components 'scheme-indent-function 1)
(put 'delay-components 'scheme-indent-function 1)
(put 'in-package-components 'scheme-indent-function 1)
(put 'lambda-components 'scheme-indent-function 1)
(put 'lambda-components* 'scheme-indent-function 1)
(put 'lambda-components** 'scheme-indent-function 1)
(put 'open-block-components 'scheme-indent-function 1)
(put 'pathname-components 'scheme-indent-function 1)
(put 'procedure-components 'scheme-indent-function 1)
(put 'sequence-components 'scheme-indent-function 1)
(put 'unassigned\?-components 'scheme-indent-function 1)
(put 'unbound\?-components 'scheme-indent-function 1)
(put 'variable-components 'scheme-indent-function 1)))
(provide 'scheme)
;;; scheme.el ends here
|
[
{
"context": "*- lexical-binding: t; -*-\n\n;; Copyright (C) 2022 Troy Brumley\n\n;; Author: Troy Brumley <BlameTroi@gmail.com>\n;;",
"end": 117,
"score": 0.9998682737350464,
"start": 105,
"tag": "NAME",
"value": "Troy Brumley"
},
{
"context": "-\n\n;; Copyright (C) 2022 Troy Brumley\n\n;; Author: Troy Brumley <BlameTroi@gmail.com>\n;; Keywords: internal, lisp",
"end": 142,
"score": 0.9998730421066284,
"start": 130,
"tag": "NAME",
"value": "Troy Brumley"
},
{
"context": " (C) 2022 Troy Brumley\n\n;; Author: Troy Brumley <BlameTroi@gmail.com>\n;; Keywords: internal, lisp\n\n;; This program is ",
"end": 163,
"score": 0.9999275803565979,
"start": 144,
"tag": "EMAIL",
"value": "BlameTroi@gmail.com"
}
] | emacs/.emacs.d/site-lisp/init-bgt.el | BlameTroi/.dotfiles | 0 | ;;; init-bgt.el --- blood glucose tracking in org -*- lexical-binding: t; -*-
;; Copyright (C) 2022 Troy Brumley
;; Author: Troy Brumley <BlameTroi@gmail.com>
;; Keywords: internal, lisp
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; A still in development blood glucose tracking application I
;; found on github. I've forked it to better control when I pick
;; up changes.
;;
;; The original is md-arif-shaikh/bgt is on github.
;;; Code:
(use-package bgt
:straight (bgt :type git :host github :repo "blametroi/bgt")
:ensure t
:config
(setq bgt-file-name "~/projects/org/bgt.org"
bgt-csv-file-name "~/projects/org/bgt.csv"
bgt-python-file "~/.emacs.d/straight/repos/bgt/bgt.py"
bgt-python-path "python3"))
(provide 'init-bgt)
;;; init-bgt.el ends here
| 32055 | ;;; init-bgt.el --- blood glucose tracking in org -*- lexical-binding: t; -*-
;; Copyright (C) 2022 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords: internal, lisp
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; A still in development blood glucose tracking application I
;; found on github. I've forked it to better control when I pick
;; up changes.
;;
;; The original is md-arif-shaikh/bgt is on github.
;;; Code:
(use-package bgt
:straight (bgt :type git :host github :repo "blametroi/bgt")
:ensure t
:config
(setq bgt-file-name "~/projects/org/bgt.org"
bgt-csv-file-name "~/projects/org/bgt.csv"
bgt-python-file "~/.emacs.d/straight/repos/bgt/bgt.py"
bgt-python-path "python3"))
(provide 'init-bgt)
;;; init-bgt.el ends here
| true | ;;; init-bgt.el --- blood glucose tracking in org -*- lexical-binding: t; -*-
;; Copyright (C) 2022 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: internal, lisp
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; A still in development blood glucose tracking application I
;; found on github. I've forked it to better control when I pick
;; up changes.
;;
;; The original is md-arif-shaikh/bgt is on github.
;;; Code:
(use-package bgt
:straight (bgt :type git :host github :repo "blametroi/bgt")
:ensure t
:config
(setq bgt-file-name "~/projects/org/bgt.org"
bgt-csv-file-name "~/projects/org/bgt.csv"
bgt-python-file "~/.emacs.d/straight/repos/bgt/bgt.py"
bgt-python-path "python3"))
(provide 'init-bgt)
;;; init-bgt.el ends here
|
[
{
"context": "C) 2017 Free Software Foundation, Inc\n\n;; Author: Alex Harsanyi (AlexHarsanyi@gmail.com)\n;; Created: 23 May 2017\n",
"end": 168,
"score": 0.9998685717582703,
"start": 155,
"tag": "NAME",
"value": "Alex Harsanyi"
},
{
"context": "ftware Foundation, Inc\n\n;; Author: Alex Harsanyi (AlexHarsanyi@gmail.com)\n;; Created: 23 May 2017\n;; Keywords: languages s",
"end": 192,
"score": 0.9999282360076904,
"start": 170,
"tag": "EMAIL",
"value": "AlexHarsanyi@gmail.com"
},
{
"context": "ds: languages sql\n;; Homepage: https://github.com/alex-hhh/emacs-sql-indent\n\n;; This program is free softwar",
"end": 285,
"score": 0.9992046356201172,
"start": 277,
"tag": "USERNAME",
"value": "alex-hhh"
},
{
"context": "actual tests ....\n\n;; See https://gist.github.com/alex-hhh/834a91621680e826a27b2b08463eb12f\n\n(defvar m-inden",
"end": 9946,
"score": 0.9996605515480042,
"start": 9938,
"tag": "USERNAME",
"value": "alex-hhh"
}
] | elpa-26.1/sql-indent-1.2/sql-indent-test.el | zayfen/emacs.d | 0 | ;;; sql-indent-test.el --- Automated tests for sql-indent.el. -*- lexical-binding: t -*-
;; Copyright (C) 2017 Free Software Foundation, Inc
;; Author: Alex Harsanyi (AlexHarsanyi@gmail.com)
;; Created: 23 May 2017
;; Keywords: languages sql
;; Homepage: https://github.com/alex-hhh/emacs-sql-indent
;; 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 3 of the License, 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file defines tests for the sql-indent.el package. To run the tests,
;; eval this file, than type:
;;
;; M-x ert RET "^sqlind-" RET
;;
;; Tests can also be run in batch mode using the following command:
;;
;; emacs -batch -Q --no-site-file -L . -l sql-indent-test.el -f ert-run-tests-batch-and-exit
;;
;; The above command used '-Q' and '--no-site-file options', making sure that
;; the tests are run in a "standard" environment, regardless of what packages
;; and settings are present in your personal init and site-init files.
;;
;;;; There are two types of tests,
;;
;; * SYNTAX CHECKS check if the syntax in an SQL file is correctly
;; identified. These tests are independent of indentation preferences (see
;; `sqlind-ert-check-file-syntax')
;;
;; * INDENTATION CHECKS check if a file is indented correctly for a set of
;; rules. (see `sqlind-ert-check-file-indentation')
;;
;; Both types of tests work by having a sample SQL file with syntax and
;; indentation data saved in an .eld files. These data files need to be
;; prepared separately using `sqlind-collect-syntax-from-buffer' and
;; `sqlind-collect-indentation-offsets-from-buffer'.
;;
;;
;;;; PREPARING NEW TESTS
;;
;; To create a syntax check file, open an *ielm* buffer (M-x ielm RET) and
;; run:
;;
;; (sqlind-collect-syntax-from-buffer (find-file-noselect "./test-data/pr7.sql"))
;;
;; The function will output a set of syntax definitions. Put these into an
;; .eld file.
;;
;; To create an indentation offsets file, run:
;;
;; (sqlind-collect-indentation-offsets-from-buffer
;; (find-file-noselect "./test-data/pr7.sql")
;; sqlind-indentation-left-offsets-alist
;; 2)
;;
;; The function will output a list of indentation offsets. Put these into an
;; .eld file.
;;
;; See the end of file for examples on how to put together the actual tests.
;;
;;
;;;; NAMING CONVENTION
;;
;; If there's a problem report on GitHub, use the issue number as the "tag"
;; for the test. For example, a test that addresses issue number 30 will have
;; a tag "pr30". If there is no issue on GitHub, use the pull request number.
;; In this case you will have to create the pull request first, so you know
;; the number, before you can add the tests -- sorry about that.
;;
;; With the issue or pull request tag the following files are created:
;;
;; * "test-data/pr30.sql" -- contains the sample SQL code that is verified
;;
;; * "test-data/pr30-syn.eld" -- contains the syntactic information for the ;;
;; test (as generated by `sqlind-collect-syntax-from-buffer')
;;
;; * "test-data/pr30-io-XXX.eld" -- contains the indentation offsets for the
;; indentation rules being tested (where XXX is a short name for those
;; rules)
;;
;; * `sqlind-ert-pr30' -- is the name of the test function in this file. If
;; there are multiple tests, append another tag (e.g. `sqlind-ert-pr30-syn',
;; for the syntactic check test, `sqlind-ert-pr30-io-XXX' for the indentation
;; offset test).
;;
;;; Code
(require 'ert)
(require 'sql-indent)
(require 'sql-indent-left)
;;................................................ test data preparation ....
(defun sqlind-collect-syntax-from-buffer (buffer)
(let ((result '()))
(with-current-buffer buffer
;; NOTE: we indent the buffer according to the default rules first, as
;; this affects anchor points. We could get rid of this if we write a
;; smarter `sqlind-ert-check-line-syntax'
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))
(while (= (forward-line 1) 0)
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))))
(reverse result)))
(defun sqlind-collect-indentation-offsets-from-buffer (buffer rules basic-offset)
(let ((result '()))
(with-current-buffer buffer
(sqlind-ert-indent-buffer
(or rules (default-value 'sqlind-indentation-offsets-alist))
(or basic-offset (default-value 'sqlind-basic-offset)))
(goto-char (point-min))
(setq result (cons (current-indentation) result))
(while (= (forward-line 1) 0)
(setq result (cons (current-indentation) result))))
(reverse result)))
;;......................................................... test helpers ....
(defun sqlind-ert-indent-buffer (rules basic-offset)
"Indent the buffer according to RULES and BASIC-OFFSET.
The RULES and BASIC-OFFSET are installed as
`sqlind-indentation-offsets-alist' and `sqlind-basic-offset' than
indent the whole buffer."
(when rules
(setq sqlind-indentation-offsets-alist rules))
(when basic-offset
(setq sqlind-basic-offset basic-offset))
;; To ensure we are consistent in our offsets regardless of he users
;; personal tab choices, setup spaces only indentation for this buffer.
(setq indent-tabs-mode nil)
(untabify (point-min) (point-max))
(indent-region (point-min) (point-max))
;; (save-buffer) ; if you want to see the result of this command
(set-buffer-modified-p nil))
(defun sqlind-ert-check-line-syntax (expected)
"Check that the current line has EXPECTED syntax.
Get the syntax of the current line in the current buffer using
`sqlind-syntax-of-line' and compare it against EXPECTED.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (sqlind-syntax-of-line))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-read-data (file)
"Read saved ELISP data from FILE."
(with-current-buffer (or (get-buffer file)
(find-file-noselect file))
(goto-char (point-min))
(read (current-buffer))))
(defun sqlind-ert-check-file-syntax (sql-file data-file)
"Check the syntax of each line in SQL-FILE.
The syntax of each line in SQL-FILE is checked against the
previously saved syntax data in DATA-FILE. An error is signalled
if there is a mismatch."
(let ((syntax-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1) ; ensure this is enabled
;; NOTE: indent the buffer according to default rules first -- this
;; affects anchor points.
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))
(while (= (forward-line 1) 0)
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))))))
(defun sqlind-ert-check-line-indentation (expected)
"Check that the current line has EXPECTED indentation.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (current-indentation))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-check-file-indentation (sql-file data-file rules basic-offset)
"Check that SQL-FILE is indented correctly according to RULES
and BASIC-OFFSET The file is indented first according to RULES
and BASIC-OFFSET, than each line is compared with the indentation
information read from DATA-FILE (as generated by
`sqlind-collect-indentation-offsets-from-buffer')"
(let ((indentation-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1)
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer rules basic-offset)
(goto-char (point-min))
(should (consp indentation-data)) ; "premature end of indentation-data
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))
(while (= (forward-line 1) 0)
(should (consp indentation-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))))))
;;..................................................... the actual tests ....
;; See https://gist.github.com/alex-hhh/834a91621680e826a27b2b08463eb12f
(defvar m-indentation-offsets-alist
`((select-clause 0)
(insert-clause 0)
(delete-clause 0)
(update-clause 0)
(in-insert-clause +)
(in-select-clause sqlind-lineup-to-clause-end)
(nested-statement-continuation sqlind-lineup-into-nested-statement
sqlind-align-comma)
(nested-statement-close sqlind-lineup-to-anchor)
(select-column sqlind-indent-select-column
sqlind-align-comma)
(select-column-continuation sqlind-indent-select-column)
(select-table-continuation sqlind-indent-select-table
sqlind-lineup-joins-to-anchor
sqlind-lineup-open-paren-to-anchor
sqlind-align-comma)
,@sqlind-default-indentation-offsets-alist))
(ert-deftest sqlind-ert-pr17 ()
(sqlind-ert-check-file-syntax "test-data/pr17.sql" "test-data/pr17-syn.eld"))
(ert-deftest sqlind-ert-pr17-indentation-default ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-default.eld"
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-left ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-left.eld"
sqlind-indentation-left-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-right ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-right.eld"
sqlind-indentation-right-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr7 ()
(sqlind-ert-check-file-syntax "test-data/pr7.sql" "test-data/pr7-syn.eld"))
(ert-deftest sqlind-ert-case-stmt ()
(sqlind-ert-check-file-syntax "test-data/case-stmt.sql" "test-data/case-stmt-syn.eld"))
(ert-deftest sqlind-ert-m-syn ()
(sqlind-ert-check-file-syntax "test-data/m.sql" "test-data/m-syn.eld"))
(ert-deftest sqlind-ert-m-io ()
(sqlind-ert-check-file-indentation
"test-data/m.sql" "test-data/m-io.eld"
m-indentation-offsets-alist 4))
(ert-deftest sqlind-ert-pr18 ()
(sqlind-ert-check-file-syntax "test-data/pr18.sql" "test-data/pr18-syn.eld"))
(ert-deftest sqlind-ert-pr19 ()
(sqlind-ert-check-file-syntax "test-data/pr19.sql" "test-data/pr19-syn.eld"))
(ert-deftest sqlind-ert-pr24 ()
(sqlind-ert-check-file-syntax "test-data/pr24.sql" "test-data/pr24-syn.eld"))
(ert-deftest sqlind-ert-pr28 ()
(sqlind-ert-check-file-syntax "test-data/pr28.sql" "test-data/pr28-syn.eld"))
(ert-deftest sqlind-ert-pr29 ()
(sqlind-ert-check-file-syntax "test-data/pr29.sql" "test-data/pr29-syn.eld"))
(ert-deftest sqlind-ert-if-exists ()
(sqlind-ert-check-file-syntax "test-data/if-exists.sql" "test-data/if-exists-syn.eld"))
(ert-deftest sqlind-ert-pr33 ()
(sqlind-ert-check-file-syntax "test-data/pr33.sql" "test-data/pr33-syn.eld"))
(ert-deftest sqlind-ert-pr33-io-left ()
(sqlind-ert-check-file-indentation
"test-data/pr33.sql" "test-data/pr33-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr36 ()
(sqlind-ert-check-file-syntax "test-data/pr36.sql" "test-data/pr36-syn.eld"))
(ert-deftest sqlind-ert-pr36-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr36.sql" "test-data/pr36-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr37 ()
(sqlind-ert-check-file-syntax "test-data/pr37.sql" "test-data/pr37-syn.eld"))
(ert-deftest sqlind-ert-pr37-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr37.sql" "test-data/pr37-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr39 ()
(sqlind-ert-check-file-syntax "test-data/pr39.sql" "test-data/pr39-syn.eld"))
(ert-deftest sqlind-ert-pr40 ()
(sqlind-ert-check-file-syntax "test-data/pr40.sql" "test-data/pr40-syn.eld"))
(ert-deftest sqlind-ert-pr42 ()
(sqlind-ert-check-file-syntax "test-data/pr42.sql" "test-data/pr42-syn.eld"))
(ert-deftest sqlind-ert-pr46 ()
(sqlind-ert-check-file-syntax "test-data/pr46.sql" "test-data/pr46-syn.eld"))
(ert-deftest sqlind-ert-pr48 ()
(sqlind-ert-check-file-syntax "test-data/pr48.sql" "test-data/pr48-syn.eld"))
(ert-deftest sqlind-ert-pr49 ()
(sqlind-ert-check-file-syntax "test-data/pr49.sql" "test-data/pr49-syn.eld"))
(ert-deftest sqlind-ert-pr50-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr50.sql" "test-data/pr50-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr52-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr52.sql" "test-data/pr52-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr53-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr53.sql" "test-data/pr53-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr54 ()
(sqlind-ert-check-file-syntax "test-data/pr54.sql" "test-data/pr54-syn.eld"))
(ert-deftest sqlind-ert-pr60 ()
(sqlind-ert-check-file-syntax "test-data/pr60.sql" "test-data/pr60-syn.eld"))
;;; sql-indent-test.el ends here
| 52401 | ;;; sql-indent-test.el --- Automated tests for sql-indent.el. -*- lexical-binding: t -*-
;; Copyright (C) 2017 Free Software Foundation, Inc
;; Author: <NAME> (<EMAIL>)
;; Created: 23 May 2017
;; Keywords: languages sql
;; Homepage: https://github.com/alex-hhh/emacs-sql-indent
;; 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 3 of the License, 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file defines tests for the sql-indent.el package. To run the tests,
;; eval this file, than type:
;;
;; M-x ert RET "^sqlind-" RET
;;
;; Tests can also be run in batch mode using the following command:
;;
;; emacs -batch -Q --no-site-file -L . -l sql-indent-test.el -f ert-run-tests-batch-and-exit
;;
;; The above command used '-Q' and '--no-site-file options', making sure that
;; the tests are run in a "standard" environment, regardless of what packages
;; and settings are present in your personal init and site-init files.
;;
;;;; There are two types of tests,
;;
;; * SYNTAX CHECKS check if the syntax in an SQL file is correctly
;; identified. These tests are independent of indentation preferences (see
;; `sqlind-ert-check-file-syntax')
;;
;; * INDENTATION CHECKS check if a file is indented correctly for a set of
;; rules. (see `sqlind-ert-check-file-indentation')
;;
;; Both types of tests work by having a sample SQL file with syntax and
;; indentation data saved in an .eld files. These data files need to be
;; prepared separately using `sqlind-collect-syntax-from-buffer' and
;; `sqlind-collect-indentation-offsets-from-buffer'.
;;
;;
;;;; PREPARING NEW TESTS
;;
;; To create a syntax check file, open an *ielm* buffer (M-x ielm RET) and
;; run:
;;
;; (sqlind-collect-syntax-from-buffer (find-file-noselect "./test-data/pr7.sql"))
;;
;; The function will output a set of syntax definitions. Put these into an
;; .eld file.
;;
;; To create an indentation offsets file, run:
;;
;; (sqlind-collect-indentation-offsets-from-buffer
;; (find-file-noselect "./test-data/pr7.sql")
;; sqlind-indentation-left-offsets-alist
;; 2)
;;
;; The function will output a list of indentation offsets. Put these into an
;; .eld file.
;;
;; See the end of file for examples on how to put together the actual tests.
;;
;;
;;;; NAMING CONVENTION
;;
;; If there's a problem report on GitHub, use the issue number as the "tag"
;; for the test. For example, a test that addresses issue number 30 will have
;; a tag "pr30". If there is no issue on GitHub, use the pull request number.
;; In this case you will have to create the pull request first, so you know
;; the number, before you can add the tests -- sorry about that.
;;
;; With the issue or pull request tag the following files are created:
;;
;; * "test-data/pr30.sql" -- contains the sample SQL code that is verified
;;
;; * "test-data/pr30-syn.eld" -- contains the syntactic information for the ;;
;; test (as generated by `sqlind-collect-syntax-from-buffer')
;;
;; * "test-data/pr30-io-XXX.eld" -- contains the indentation offsets for the
;; indentation rules being tested (where XXX is a short name for those
;; rules)
;;
;; * `sqlind-ert-pr30' -- is the name of the test function in this file. If
;; there are multiple tests, append another tag (e.g. `sqlind-ert-pr30-syn',
;; for the syntactic check test, `sqlind-ert-pr30-io-XXX' for the indentation
;; offset test).
;;
;;; Code
(require 'ert)
(require 'sql-indent)
(require 'sql-indent-left)
;;................................................ test data preparation ....
(defun sqlind-collect-syntax-from-buffer (buffer)
(let ((result '()))
(with-current-buffer buffer
;; NOTE: we indent the buffer according to the default rules first, as
;; this affects anchor points. We could get rid of this if we write a
;; smarter `sqlind-ert-check-line-syntax'
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))
(while (= (forward-line 1) 0)
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))))
(reverse result)))
(defun sqlind-collect-indentation-offsets-from-buffer (buffer rules basic-offset)
(let ((result '()))
(with-current-buffer buffer
(sqlind-ert-indent-buffer
(or rules (default-value 'sqlind-indentation-offsets-alist))
(or basic-offset (default-value 'sqlind-basic-offset)))
(goto-char (point-min))
(setq result (cons (current-indentation) result))
(while (= (forward-line 1) 0)
(setq result (cons (current-indentation) result))))
(reverse result)))
;;......................................................... test helpers ....
(defun sqlind-ert-indent-buffer (rules basic-offset)
"Indent the buffer according to RULES and BASIC-OFFSET.
The RULES and BASIC-OFFSET are installed as
`sqlind-indentation-offsets-alist' and `sqlind-basic-offset' than
indent the whole buffer."
(when rules
(setq sqlind-indentation-offsets-alist rules))
(when basic-offset
(setq sqlind-basic-offset basic-offset))
;; To ensure we are consistent in our offsets regardless of he users
;; personal tab choices, setup spaces only indentation for this buffer.
(setq indent-tabs-mode nil)
(untabify (point-min) (point-max))
(indent-region (point-min) (point-max))
;; (save-buffer) ; if you want to see the result of this command
(set-buffer-modified-p nil))
(defun sqlind-ert-check-line-syntax (expected)
"Check that the current line has EXPECTED syntax.
Get the syntax of the current line in the current buffer using
`sqlind-syntax-of-line' and compare it against EXPECTED.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (sqlind-syntax-of-line))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-read-data (file)
"Read saved ELISP data from FILE."
(with-current-buffer (or (get-buffer file)
(find-file-noselect file))
(goto-char (point-min))
(read (current-buffer))))
(defun sqlind-ert-check-file-syntax (sql-file data-file)
"Check the syntax of each line in SQL-FILE.
The syntax of each line in SQL-FILE is checked against the
previously saved syntax data in DATA-FILE. An error is signalled
if there is a mismatch."
(let ((syntax-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1) ; ensure this is enabled
;; NOTE: indent the buffer according to default rules first -- this
;; affects anchor points.
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))
(while (= (forward-line 1) 0)
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))))))
(defun sqlind-ert-check-line-indentation (expected)
"Check that the current line has EXPECTED indentation.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (current-indentation))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-check-file-indentation (sql-file data-file rules basic-offset)
"Check that SQL-FILE is indented correctly according to RULES
and BASIC-OFFSET The file is indented first according to RULES
and BASIC-OFFSET, than each line is compared with the indentation
information read from DATA-FILE (as generated by
`sqlind-collect-indentation-offsets-from-buffer')"
(let ((indentation-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1)
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer rules basic-offset)
(goto-char (point-min))
(should (consp indentation-data)) ; "premature end of indentation-data
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))
(while (= (forward-line 1) 0)
(should (consp indentation-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))))))
;;..................................................... the actual tests ....
;; See https://gist.github.com/alex-hhh/834a91621680e826a27b2b08463eb12f
(defvar m-indentation-offsets-alist
`((select-clause 0)
(insert-clause 0)
(delete-clause 0)
(update-clause 0)
(in-insert-clause +)
(in-select-clause sqlind-lineup-to-clause-end)
(nested-statement-continuation sqlind-lineup-into-nested-statement
sqlind-align-comma)
(nested-statement-close sqlind-lineup-to-anchor)
(select-column sqlind-indent-select-column
sqlind-align-comma)
(select-column-continuation sqlind-indent-select-column)
(select-table-continuation sqlind-indent-select-table
sqlind-lineup-joins-to-anchor
sqlind-lineup-open-paren-to-anchor
sqlind-align-comma)
,@sqlind-default-indentation-offsets-alist))
(ert-deftest sqlind-ert-pr17 ()
(sqlind-ert-check-file-syntax "test-data/pr17.sql" "test-data/pr17-syn.eld"))
(ert-deftest sqlind-ert-pr17-indentation-default ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-default.eld"
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-left ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-left.eld"
sqlind-indentation-left-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-right ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-right.eld"
sqlind-indentation-right-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr7 ()
(sqlind-ert-check-file-syntax "test-data/pr7.sql" "test-data/pr7-syn.eld"))
(ert-deftest sqlind-ert-case-stmt ()
(sqlind-ert-check-file-syntax "test-data/case-stmt.sql" "test-data/case-stmt-syn.eld"))
(ert-deftest sqlind-ert-m-syn ()
(sqlind-ert-check-file-syntax "test-data/m.sql" "test-data/m-syn.eld"))
(ert-deftest sqlind-ert-m-io ()
(sqlind-ert-check-file-indentation
"test-data/m.sql" "test-data/m-io.eld"
m-indentation-offsets-alist 4))
(ert-deftest sqlind-ert-pr18 ()
(sqlind-ert-check-file-syntax "test-data/pr18.sql" "test-data/pr18-syn.eld"))
(ert-deftest sqlind-ert-pr19 ()
(sqlind-ert-check-file-syntax "test-data/pr19.sql" "test-data/pr19-syn.eld"))
(ert-deftest sqlind-ert-pr24 ()
(sqlind-ert-check-file-syntax "test-data/pr24.sql" "test-data/pr24-syn.eld"))
(ert-deftest sqlind-ert-pr28 ()
(sqlind-ert-check-file-syntax "test-data/pr28.sql" "test-data/pr28-syn.eld"))
(ert-deftest sqlind-ert-pr29 ()
(sqlind-ert-check-file-syntax "test-data/pr29.sql" "test-data/pr29-syn.eld"))
(ert-deftest sqlind-ert-if-exists ()
(sqlind-ert-check-file-syntax "test-data/if-exists.sql" "test-data/if-exists-syn.eld"))
(ert-deftest sqlind-ert-pr33 ()
(sqlind-ert-check-file-syntax "test-data/pr33.sql" "test-data/pr33-syn.eld"))
(ert-deftest sqlind-ert-pr33-io-left ()
(sqlind-ert-check-file-indentation
"test-data/pr33.sql" "test-data/pr33-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr36 ()
(sqlind-ert-check-file-syntax "test-data/pr36.sql" "test-data/pr36-syn.eld"))
(ert-deftest sqlind-ert-pr36-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr36.sql" "test-data/pr36-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr37 ()
(sqlind-ert-check-file-syntax "test-data/pr37.sql" "test-data/pr37-syn.eld"))
(ert-deftest sqlind-ert-pr37-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr37.sql" "test-data/pr37-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr39 ()
(sqlind-ert-check-file-syntax "test-data/pr39.sql" "test-data/pr39-syn.eld"))
(ert-deftest sqlind-ert-pr40 ()
(sqlind-ert-check-file-syntax "test-data/pr40.sql" "test-data/pr40-syn.eld"))
(ert-deftest sqlind-ert-pr42 ()
(sqlind-ert-check-file-syntax "test-data/pr42.sql" "test-data/pr42-syn.eld"))
(ert-deftest sqlind-ert-pr46 ()
(sqlind-ert-check-file-syntax "test-data/pr46.sql" "test-data/pr46-syn.eld"))
(ert-deftest sqlind-ert-pr48 ()
(sqlind-ert-check-file-syntax "test-data/pr48.sql" "test-data/pr48-syn.eld"))
(ert-deftest sqlind-ert-pr49 ()
(sqlind-ert-check-file-syntax "test-data/pr49.sql" "test-data/pr49-syn.eld"))
(ert-deftest sqlind-ert-pr50-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr50.sql" "test-data/pr50-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr52-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr52.sql" "test-data/pr52-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr53-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr53.sql" "test-data/pr53-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr54 ()
(sqlind-ert-check-file-syntax "test-data/pr54.sql" "test-data/pr54-syn.eld"))
(ert-deftest sqlind-ert-pr60 ()
(sqlind-ert-check-file-syntax "test-data/pr60.sql" "test-data/pr60-syn.eld"))
;;; sql-indent-test.el ends here
| true | ;;; sql-indent-test.el --- Automated tests for sql-indent.el. -*- lexical-binding: t -*-
;; Copyright (C) 2017 Free Software Foundation, Inc
;; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;; Created: 23 May 2017
;; Keywords: languages sql
;; Homepage: https://github.com/alex-hhh/emacs-sql-indent
;; 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 3 of the License, 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This file defines tests for the sql-indent.el package. To run the tests,
;; eval this file, than type:
;;
;; M-x ert RET "^sqlind-" RET
;;
;; Tests can also be run in batch mode using the following command:
;;
;; emacs -batch -Q --no-site-file -L . -l sql-indent-test.el -f ert-run-tests-batch-and-exit
;;
;; The above command used '-Q' and '--no-site-file options', making sure that
;; the tests are run in a "standard" environment, regardless of what packages
;; and settings are present in your personal init and site-init files.
;;
;;;; There are two types of tests,
;;
;; * SYNTAX CHECKS check if the syntax in an SQL file is correctly
;; identified. These tests are independent of indentation preferences (see
;; `sqlind-ert-check-file-syntax')
;;
;; * INDENTATION CHECKS check if a file is indented correctly for a set of
;; rules. (see `sqlind-ert-check-file-indentation')
;;
;; Both types of tests work by having a sample SQL file with syntax and
;; indentation data saved in an .eld files. These data files need to be
;; prepared separately using `sqlind-collect-syntax-from-buffer' and
;; `sqlind-collect-indentation-offsets-from-buffer'.
;;
;;
;;;; PREPARING NEW TESTS
;;
;; To create a syntax check file, open an *ielm* buffer (M-x ielm RET) and
;; run:
;;
;; (sqlind-collect-syntax-from-buffer (find-file-noselect "./test-data/pr7.sql"))
;;
;; The function will output a set of syntax definitions. Put these into an
;; .eld file.
;;
;; To create an indentation offsets file, run:
;;
;; (sqlind-collect-indentation-offsets-from-buffer
;; (find-file-noselect "./test-data/pr7.sql")
;; sqlind-indentation-left-offsets-alist
;; 2)
;;
;; The function will output a list of indentation offsets. Put these into an
;; .eld file.
;;
;; See the end of file for examples on how to put together the actual tests.
;;
;;
;;;; NAMING CONVENTION
;;
;; If there's a problem report on GitHub, use the issue number as the "tag"
;; for the test. For example, a test that addresses issue number 30 will have
;; a tag "pr30". If there is no issue on GitHub, use the pull request number.
;; In this case you will have to create the pull request first, so you know
;; the number, before you can add the tests -- sorry about that.
;;
;; With the issue or pull request tag the following files are created:
;;
;; * "test-data/pr30.sql" -- contains the sample SQL code that is verified
;;
;; * "test-data/pr30-syn.eld" -- contains the syntactic information for the ;;
;; test (as generated by `sqlind-collect-syntax-from-buffer')
;;
;; * "test-data/pr30-io-XXX.eld" -- contains the indentation offsets for the
;; indentation rules being tested (where XXX is a short name for those
;; rules)
;;
;; * `sqlind-ert-pr30' -- is the name of the test function in this file. If
;; there are multiple tests, append another tag (e.g. `sqlind-ert-pr30-syn',
;; for the syntactic check test, `sqlind-ert-pr30-io-XXX' for the indentation
;; offset test).
;;
;;; Code
(require 'ert)
(require 'sql-indent)
(require 'sql-indent-left)
;;................................................ test data preparation ....
(defun sqlind-collect-syntax-from-buffer (buffer)
(let ((result '()))
(with-current-buffer buffer
;; NOTE: we indent the buffer according to the default rules first, as
;; this affects anchor points. We could get rid of this if we write a
;; smarter `sqlind-ert-check-line-syntax'
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))
(while (= (forward-line 1) 0)
(let ((syn (sqlind-syntax-of-line)))
(setq result (cons syn result)))))
(reverse result)))
(defun sqlind-collect-indentation-offsets-from-buffer (buffer rules basic-offset)
(let ((result '()))
(with-current-buffer buffer
(sqlind-ert-indent-buffer
(or rules (default-value 'sqlind-indentation-offsets-alist))
(or basic-offset (default-value 'sqlind-basic-offset)))
(goto-char (point-min))
(setq result (cons (current-indentation) result))
(while (= (forward-line 1) 0)
(setq result (cons (current-indentation) result))))
(reverse result)))
;;......................................................... test helpers ....
(defun sqlind-ert-indent-buffer (rules basic-offset)
"Indent the buffer according to RULES and BASIC-OFFSET.
The RULES and BASIC-OFFSET are installed as
`sqlind-indentation-offsets-alist' and `sqlind-basic-offset' than
indent the whole buffer."
(when rules
(setq sqlind-indentation-offsets-alist rules))
(when basic-offset
(setq sqlind-basic-offset basic-offset))
;; To ensure we are consistent in our offsets regardless of he users
;; personal tab choices, setup spaces only indentation for this buffer.
(setq indent-tabs-mode nil)
(untabify (point-min) (point-max))
(indent-region (point-min) (point-max))
;; (save-buffer) ; if you want to see the result of this command
(set-buffer-modified-p nil))
(defun sqlind-ert-check-line-syntax (expected)
"Check that the current line has EXPECTED syntax.
Get the syntax of the current line in the current buffer using
`sqlind-syntax-of-line' and compare it against EXPECTED.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (sqlind-syntax-of-line))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-read-data (file)
"Read saved ELISP data from FILE."
(with-current-buffer (or (get-buffer file)
(find-file-noselect file))
(goto-char (point-min))
(read (current-buffer))))
(defun sqlind-ert-check-file-syntax (sql-file data-file)
"Check the syntax of each line in SQL-FILE.
The syntax of each line in SQL-FILE is checked against the
previously saved syntax data in DATA-FILE. An error is signalled
if there is a mismatch."
(let ((syntax-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1) ; ensure this is enabled
;; NOTE: indent the buffer according to default rules first -- this
;; affects anchor points.
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset))
(goto-char (point-min))
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))
(while (= (forward-line 1) 0)
(should (consp syntax-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-syntax (car syntax-data))
(setq syntax-data (cdr syntax-data))))))
(defun sqlind-ert-check-line-indentation (expected)
"Check that the current line has EXPECTED indentation.
The comparison is done using the `should' ERT macro, so this
function should be run a part of an ERT test."
(let ((actual (current-indentation))
(info (format "%s:%s"
(buffer-file-name)
(line-number-at-pos))))
;; NOTE: should does not appear to have a message argument, so the "cons"
;; trick is used to add some information in case of failure.
(should
(equal (cons info actual) (cons info expected)))))
(defun sqlind-ert-check-file-indentation (sql-file data-file rules basic-offset)
"Check that SQL-FILE is indented correctly according to RULES
and BASIC-OFFSET The file is indented first according to RULES
and BASIC-OFFSET, than each line is compared with the indentation
information read from DATA-FILE (as generated by
`sqlind-collect-indentation-offsets-from-buffer')"
(let ((indentation-data (sqlind-ert-read-data data-file)))
(with-current-buffer (find-file sql-file)
(sqlind-minor-mode 1)
;; (message "sql-product: %s" sql-product)
(sqlind-ert-indent-buffer rules basic-offset)
(goto-char (point-min))
(should (consp indentation-data)) ; "premature end of indentation-data
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))
(while (= (forward-line 1) 0)
(should (consp indentation-data)) ; "premature end of syntax-data"
(sqlind-ert-check-line-indentation (car indentation-data))
(setq indentation-data (cdr indentation-data))))))
;;..................................................... the actual tests ....
;; See https://gist.github.com/alex-hhh/834a91621680e826a27b2b08463eb12f
(defvar m-indentation-offsets-alist
`((select-clause 0)
(insert-clause 0)
(delete-clause 0)
(update-clause 0)
(in-insert-clause +)
(in-select-clause sqlind-lineup-to-clause-end)
(nested-statement-continuation sqlind-lineup-into-nested-statement
sqlind-align-comma)
(nested-statement-close sqlind-lineup-to-anchor)
(select-column sqlind-indent-select-column
sqlind-align-comma)
(select-column-continuation sqlind-indent-select-column)
(select-table-continuation sqlind-indent-select-table
sqlind-lineup-joins-to-anchor
sqlind-lineup-open-paren-to-anchor
sqlind-align-comma)
,@sqlind-default-indentation-offsets-alist))
(ert-deftest sqlind-ert-pr17 ()
(sqlind-ert-check-file-syntax "test-data/pr17.sql" "test-data/pr17-syn.eld"))
(ert-deftest sqlind-ert-pr17-indentation-default ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-default.eld"
(default-value 'sqlind-indentation-offsets-alist)
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-left ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-left.eld"
sqlind-indentation-left-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr17-indentation-right ()
(sqlind-ert-check-file-indentation
"test-data/pr17.sql" "test-data/pr17-io-right.eld"
sqlind-indentation-right-offsets-alist
(default-value 'sqlind-basic-offset)))
(ert-deftest sqlind-ert-pr7 ()
(sqlind-ert-check-file-syntax "test-data/pr7.sql" "test-data/pr7-syn.eld"))
(ert-deftest sqlind-ert-case-stmt ()
(sqlind-ert-check-file-syntax "test-data/case-stmt.sql" "test-data/case-stmt-syn.eld"))
(ert-deftest sqlind-ert-m-syn ()
(sqlind-ert-check-file-syntax "test-data/m.sql" "test-data/m-syn.eld"))
(ert-deftest sqlind-ert-m-io ()
(sqlind-ert-check-file-indentation
"test-data/m.sql" "test-data/m-io.eld"
m-indentation-offsets-alist 4))
(ert-deftest sqlind-ert-pr18 ()
(sqlind-ert-check-file-syntax "test-data/pr18.sql" "test-data/pr18-syn.eld"))
(ert-deftest sqlind-ert-pr19 ()
(sqlind-ert-check-file-syntax "test-data/pr19.sql" "test-data/pr19-syn.eld"))
(ert-deftest sqlind-ert-pr24 ()
(sqlind-ert-check-file-syntax "test-data/pr24.sql" "test-data/pr24-syn.eld"))
(ert-deftest sqlind-ert-pr28 ()
(sqlind-ert-check-file-syntax "test-data/pr28.sql" "test-data/pr28-syn.eld"))
(ert-deftest sqlind-ert-pr29 ()
(sqlind-ert-check-file-syntax "test-data/pr29.sql" "test-data/pr29-syn.eld"))
(ert-deftest sqlind-ert-if-exists ()
(sqlind-ert-check-file-syntax "test-data/if-exists.sql" "test-data/if-exists-syn.eld"))
(ert-deftest sqlind-ert-pr33 ()
(sqlind-ert-check-file-syntax "test-data/pr33.sql" "test-data/pr33-syn.eld"))
(ert-deftest sqlind-ert-pr33-io-left ()
(sqlind-ert-check-file-indentation
"test-data/pr33.sql" "test-data/pr33-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr36 ()
(sqlind-ert-check-file-syntax "test-data/pr36.sql" "test-data/pr36-syn.eld"))
(ert-deftest sqlind-ert-pr36-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr36.sql" "test-data/pr36-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr37 ()
(sqlind-ert-check-file-syntax "test-data/pr37.sql" "test-data/pr37-syn.eld"))
(ert-deftest sqlind-ert-pr37-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr37.sql" "test-data/pr37-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr39 ()
(sqlind-ert-check-file-syntax "test-data/pr39.sql" "test-data/pr39-syn.eld"))
(ert-deftest sqlind-ert-pr40 ()
(sqlind-ert-check-file-syntax "test-data/pr40.sql" "test-data/pr40-syn.eld"))
(ert-deftest sqlind-ert-pr42 ()
(sqlind-ert-check-file-syntax "test-data/pr42.sql" "test-data/pr42-syn.eld"))
(ert-deftest sqlind-ert-pr46 ()
(sqlind-ert-check-file-syntax "test-data/pr46.sql" "test-data/pr46-syn.eld"))
(ert-deftest sqlind-ert-pr48 ()
(sqlind-ert-check-file-syntax "test-data/pr48.sql" "test-data/pr48-syn.eld"))
(ert-deftest sqlind-ert-pr49 ()
(sqlind-ert-check-file-syntax "test-data/pr49.sql" "test-data/pr49-syn.eld"))
(ert-deftest sqlind-ert-pr50-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr50.sql" "test-data/pr50-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr52-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr52.sql" "test-data/pr52-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr53-io-left ()
(sqlind-ert-check-file-indentation "test-data/pr53.sql" "test-data/pr53-io-left.eld"
sqlind-indentation-left-offsets-alist 2))
(ert-deftest sqlind-ert-pr54 ()
(sqlind-ert-check-file-syntax "test-data/pr54.sql" "test-data/pr54-syn.eld"))
(ert-deftest sqlind-ert-pr60 ()
(sqlind-ert-check-file-syntax "test-data/pr60.sql" "test-data/pr60-syn.eld"))
;;; sql-indent-test.el ends here
|
[
{
"context": "exical Pre-processor\n\n;;; Copyright (C) 2006, 2007 Eric M. Ludlam\n\n;; X-CVS: $Id: semantic-lex-spp.el,v 1.8 2007/06",
"end": 103,
"score": 0.9998430609703064,
"start": 89,
"tag": "NAME",
"value": "Eric M. Ludlam"
}
] | .emacs.d/cedet/semantic/semantic-lex-spp.el | ybakos/dotfiles | 3 | ;;; semantic-lex-spp.el --- Semantic Lexical Pre-processor
;;; Copyright (C) 2006, 2007 Eric M. Ludlam
;; X-CVS: $Id: semantic-lex-spp.el,v 1.8 2007/06/06 01:05:05 zappo Exp $
;; This file is not part of GNU Emacs.
;; Semantic 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 software 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 Semantic Preprocessor works with semantic-lex to provide a phase
;; during lexical analysis to do the work of a pre-processor.
;;
;; A pre-processor identifies lexical syntax mixed in with another language
;; and replaces some keyword tokens with streams of alternate tokens.
;;
;; If you use SPP in your language, be sure to specify this in your
;; semantic language setup function:
;;
;; (add-hook 'semantic-lex-reset-hooks 'semantic-lex-spp-reset-hook nil t)
;;
;;; TODO:
;;
;; Use `semantic-push-parser-warning' for situations where there are likely
;; macros that are undefined unexpectedly, or other problem.
(require 'semantic-lex)
;;; Code:
(defvar semantic-lex-spp-macro-symbol-obarray nil
"Table of macro keywords used by the Semantic Macro.")
(make-variable-buffer-local 'semantic-lex-spp-macro-symbol-obarray)
(defvar semantic-lex-spp-dynamic-macro-symbol-obarray nil
"Table of macro keywords found during lexical analysis.
This table is then used by the macro during the lexical analysis
step.")
(make-variable-buffer-local 'semantic-lex-spp-dynamic-macro-symbol-obarray)
;;; MACRO TABLE UTILS
;;
(defun semantic-lex-spp-symbol-replacement (name)
"Return an SPP replacement stream for NAME.
nil is a valid return. Use `semantic-lex-spp-symbol-l\p' to determine
if the symbol is in the table."
)
(defsubst semantic-lex-spp-symbol (name)
"Return spp symbol with NAME or nil if not found."
(and
(stringp name)
(or (and (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-dynamic-macro-symbol-obarray))
(and (arrayp semantic-lex-spp-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-macro-symbol-obarray)))))
(defsubst semantic-lex-spp-symbol-p (name)
"Return non-nil if a keyword with NAME exists in any keyword table."
(if (semantic-lex-spp-symbol name)
t))
(defsubst semantic-lex-spp-dynamic-map ()
"Return the dynamic macro map for the current buffer."
(or semantic-lex-spp-dynamic-macro-symbol-obarray
(setq semantic-lex-spp-dynamic-macro-symbol-obarray
(make-vector 13 0))))
(defsubst semantic-lex-spp-symbol-set (name value &optional obarray)
"Set value of spp symbol with NAME to VALUE and return VALUE.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(if (string= value "") (setq value nil))
(set (intern name (or obarray
(semantic-lex-spp-dynamic-map)))
value))
(defsubst semantic-lex-spp-symbol-remove (name &optional obarray)
"Remove the spp symbol with NAME.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(unintern name (or obarray
(semantic-lex-spp-dynamic-map))))
(defsubst semantic-lex-spp-symbol-stream (name)
"Return replacement stream of macro with NAME."
(let ((spp (semantic-lex-spp-symbol name)))
(if spp
(symbol-value spp))))
(defun semantic-lex-make-spp-table (specs)
"Convert spp macro list SPECS into an obarray and return it.
SPECS must be a list of (NAME . REPLACEMENT) elements, where:
NAME is the name of the spp macro symbol to define.
REPLACEMENT a string that would be substituted in for NAME."
;; Create the symbol hash table
(let ((semantic-lex-spp-macro-symbol-obarray (make-vector 13 0))
spec)
;; fill it with stuff
(while specs
(setq spec (car specs)
specs (cdr specs))
(semantic-lex-spp-symbol-set
(car spec)
(cdr spec)
semantic-lex-spp-macro-symbol-obarray))
semantic-lex-spp-macro-symbol-obarray))
(defun semantic-lex-spp-macros ()
"Return a list of spp macros as Lisp symbols.
The value of each symbol is the replacement stream."
(let (macros)
(when (arrayp semantic-lex-spp-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-macro-symbol-obarray))
(when (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-dynamic-macro-symbol-obarray))
macros))
(defun semantic-lex-spp-reset-dynamic-table ()
"Reset the dynamic spp symbol table.
This should be done before any new parsing step."
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil))
(defun semantic-lex-spp-reset-hook (start end)
"Reset anything needed by SPP for parsing.
In this case, reset the dynamic macro symbol table if
START recons the entire buffer.
END is not used."
(if (= start (point-min))
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil)))
;;; MACRO EXPANSION PARSING
;;
(defun semantic-lex-spp-string-to-macro-stream (val beg end)
"Convert string VAL into a macro expansion stream.
Argument VAL is the value of some macro to be converted into a stream.
BEG and END are the token bounds of the macro to be expanded
that will somehow gain a much longer token stream."
;; NOTE: Must write this function!!!!!
;; We perform a replacement. Technically, this should
;; be a full lexical step over the "val" string, but take
;; a guess that its just a keyword or existing symbol.
;;
;; Probably a really bad idea. See how it goes.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p val) 'symbol)
beg end
val))
)
;;; MACRO TABLE DEBUG
;;
(defun semantic-lex-spp-describe (&optional buffer)
"Describe the current list of spp macros for BUFFER.
If BUFFER is not provided, use the current buffer."
(interactive)
(let ((syms (save-excursion
(if buffer (set-buffer buffer))
(semantic-lex-spp-macros)))
(sym nil))
(with-output-to-temp-buffer "*SPP MACROS*"
(princ "Macro\t\tValue\n")
(while syms
(setq sym (car syms)
syms (cdr syms))
(princ (symbol-name sym))
(princ "\t")
(if (< (length (symbol-name sym)) 8)
(princ "\t"))
(prin1 (symbol-value sym))
(princ "\n")
))))
;;; Analyzers
;;
(define-lex-regex-analyzer semantic-lex-spp-replace-or-symbol-or-keyword
"Like 'semantic-lex-symbol-or-keyword' plus preprocessor macro replacement."
"\\(\\sw\\|\\s_\\)+"
(let ((str (match-string 0))
(beg (match-beginning 0))
(end (match-end 0)))
(if (semantic-lex-spp-symbol-p str)
;; It is a macro. Prepare for a replacement.
(let* ((sym (semantic-lex-spp-symbol str))
(val (symbol-value sym)))
(if (not val)
(setq semantic-lex-end-point end)
(semantic-lex-spp-string-to-macro-stream val beg end)
))
;; A regular keyword.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p str) 'symbol)
beg end)))))
(defmacro define-lex-spp-macro-declaration-analyzer (name doc regexp tokidx
&rest valform)
"Define a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-def' is to be created.
Optional VALFORM are forms that return the value to be saved for
this macro, or nil."
(let ((start (make-symbol "start"))
(end (make-symbol "end"))
(val (make-symbol "val"))
(startpnt (make-symbol "startpnt"))
(endpnt (make-symbol "endpnt")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx))
(,startpnt semantic-lex-end-point)
(,val (save-match-data ,@valform))
(,endpnt semantic-lex-end-point))
(semantic-lex-spp-symbol-set
(buffer-substring-no-properties ,start ,end)
,val)
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-def
,start ,end))
;; Preserve setting of the end point from the calling macro.
(when (and (/= ,startpnt ,endpnt)
(/= ,endpnt semantic-lex-end-point))
(setq semantic-lex-end-point ,endpnt))
))))
(defmacro define-lex-spp-macro-undeclaration-analyzer (name doc regexp tokidx)
"Undefine a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-undef' is to be created."
(let ((start (make-symbol "start"))
(end (make-symbol "end")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx)))
(semantic-lex-spp-symbol-remove
(buffer-substring-no-properties ,start ,end))
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-undef
,start ,end))
))))
(add-hook
'edebug-setup-hook
#'(lambda ()
(def-edebug-spec define-lex-spp-macro-declaration-analyzer
(&define name stringp stringp form def-body)
)
(def-edebug-spec define-lex-spp-macro-undeclaration-analyzer
(&define name stringp stringp form def-body)
)
))
(provide 'semantic-lex-spp)
;;; semantic-lex-spp.el ends here
| 19636 | ;;; semantic-lex-spp.el --- Semantic Lexical Pre-processor
;;; Copyright (C) 2006, 2007 <NAME>
;; X-CVS: $Id: semantic-lex-spp.el,v 1.8 2007/06/06 01:05:05 zappo Exp $
;; This file is not part of GNU Emacs.
;; Semantic 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 software 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 Semantic Preprocessor works with semantic-lex to provide a phase
;; during lexical analysis to do the work of a pre-processor.
;;
;; A pre-processor identifies lexical syntax mixed in with another language
;; and replaces some keyword tokens with streams of alternate tokens.
;;
;; If you use SPP in your language, be sure to specify this in your
;; semantic language setup function:
;;
;; (add-hook 'semantic-lex-reset-hooks 'semantic-lex-spp-reset-hook nil t)
;;
;;; TODO:
;;
;; Use `semantic-push-parser-warning' for situations where there are likely
;; macros that are undefined unexpectedly, or other problem.
(require 'semantic-lex)
;;; Code:
(defvar semantic-lex-spp-macro-symbol-obarray nil
"Table of macro keywords used by the Semantic Macro.")
(make-variable-buffer-local 'semantic-lex-spp-macro-symbol-obarray)
(defvar semantic-lex-spp-dynamic-macro-symbol-obarray nil
"Table of macro keywords found during lexical analysis.
This table is then used by the macro during the lexical analysis
step.")
(make-variable-buffer-local 'semantic-lex-spp-dynamic-macro-symbol-obarray)
;;; MACRO TABLE UTILS
;;
(defun semantic-lex-spp-symbol-replacement (name)
"Return an SPP replacement stream for NAME.
nil is a valid return. Use `semantic-lex-spp-symbol-l\p' to determine
if the symbol is in the table."
)
(defsubst semantic-lex-spp-symbol (name)
"Return spp symbol with NAME or nil if not found."
(and
(stringp name)
(or (and (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-dynamic-macro-symbol-obarray))
(and (arrayp semantic-lex-spp-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-macro-symbol-obarray)))))
(defsubst semantic-lex-spp-symbol-p (name)
"Return non-nil if a keyword with NAME exists in any keyword table."
(if (semantic-lex-spp-symbol name)
t))
(defsubst semantic-lex-spp-dynamic-map ()
"Return the dynamic macro map for the current buffer."
(or semantic-lex-spp-dynamic-macro-symbol-obarray
(setq semantic-lex-spp-dynamic-macro-symbol-obarray
(make-vector 13 0))))
(defsubst semantic-lex-spp-symbol-set (name value &optional obarray)
"Set value of spp symbol with NAME to VALUE and return VALUE.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(if (string= value "") (setq value nil))
(set (intern name (or obarray
(semantic-lex-spp-dynamic-map)))
value))
(defsubst semantic-lex-spp-symbol-remove (name &optional obarray)
"Remove the spp symbol with NAME.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(unintern name (or obarray
(semantic-lex-spp-dynamic-map))))
(defsubst semantic-lex-spp-symbol-stream (name)
"Return replacement stream of macro with NAME."
(let ((spp (semantic-lex-spp-symbol name)))
(if spp
(symbol-value spp))))
(defun semantic-lex-make-spp-table (specs)
"Convert spp macro list SPECS into an obarray and return it.
SPECS must be a list of (NAME . REPLACEMENT) elements, where:
NAME is the name of the spp macro symbol to define.
REPLACEMENT a string that would be substituted in for NAME."
;; Create the symbol hash table
(let ((semantic-lex-spp-macro-symbol-obarray (make-vector 13 0))
spec)
;; fill it with stuff
(while specs
(setq spec (car specs)
specs (cdr specs))
(semantic-lex-spp-symbol-set
(car spec)
(cdr spec)
semantic-lex-spp-macro-symbol-obarray))
semantic-lex-spp-macro-symbol-obarray))
(defun semantic-lex-spp-macros ()
"Return a list of spp macros as Lisp symbols.
The value of each symbol is the replacement stream."
(let (macros)
(when (arrayp semantic-lex-spp-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-macro-symbol-obarray))
(when (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-dynamic-macro-symbol-obarray))
macros))
(defun semantic-lex-spp-reset-dynamic-table ()
"Reset the dynamic spp symbol table.
This should be done before any new parsing step."
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil))
(defun semantic-lex-spp-reset-hook (start end)
"Reset anything needed by SPP for parsing.
In this case, reset the dynamic macro symbol table if
START recons the entire buffer.
END is not used."
(if (= start (point-min))
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil)))
;;; MACRO EXPANSION PARSING
;;
(defun semantic-lex-spp-string-to-macro-stream (val beg end)
"Convert string VAL into a macro expansion stream.
Argument VAL is the value of some macro to be converted into a stream.
BEG and END are the token bounds of the macro to be expanded
that will somehow gain a much longer token stream."
;; NOTE: Must write this function!!!!!
;; We perform a replacement. Technically, this should
;; be a full lexical step over the "val" string, but take
;; a guess that its just a keyword or existing symbol.
;;
;; Probably a really bad idea. See how it goes.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p val) 'symbol)
beg end
val))
)
;;; MACRO TABLE DEBUG
;;
(defun semantic-lex-spp-describe (&optional buffer)
"Describe the current list of spp macros for BUFFER.
If BUFFER is not provided, use the current buffer."
(interactive)
(let ((syms (save-excursion
(if buffer (set-buffer buffer))
(semantic-lex-spp-macros)))
(sym nil))
(with-output-to-temp-buffer "*SPP MACROS*"
(princ "Macro\t\tValue\n")
(while syms
(setq sym (car syms)
syms (cdr syms))
(princ (symbol-name sym))
(princ "\t")
(if (< (length (symbol-name sym)) 8)
(princ "\t"))
(prin1 (symbol-value sym))
(princ "\n")
))))
;;; Analyzers
;;
(define-lex-regex-analyzer semantic-lex-spp-replace-or-symbol-or-keyword
"Like 'semantic-lex-symbol-or-keyword' plus preprocessor macro replacement."
"\\(\\sw\\|\\s_\\)+"
(let ((str (match-string 0))
(beg (match-beginning 0))
(end (match-end 0)))
(if (semantic-lex-spp-symbol-p str)
;; It is a macro. Prepare for a replacement.
(let* ((sym (semantic-lex-spp-symbol str))
(val (symbol-value sym)))
(if (not val)
(setq semantic-lex-end-point end)
(semantic-lex-spp-string-to-macro-stream val beg end)
))
;; A regular keyword.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p str) 'symbol)
beg end)))))
(defmacro define-lex-spp-macro-declaration-analyzer (name doc regexp tokidx
&rest valform)
"Define a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-def' is to be created.
Optional VALFORM are forms that return the value to be saved for
this macro, or nil."
(let ((start (make-symbol "start"))
(end (make-symbol "end"))
(val (make-symbol "val"))
(startpnt (make-symbol "startpnt"))
(endpnt (make-symbol "endpnt")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx))
(,startpnt semantic-lex-end-point)
(,val (save-match-data ,@valform))
(,endpnt semantic-lex-end-point))
(semantic-lex-spp-symbol-set
(buffer-substring-no-properties ,start ,end)
,val)
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-def
,start ,end))
;; Preserve setting of the end point from the calling macro.
(when (and (/= ,startpnt ,endpnt)
(/= ,endpnt semantic-lex-end-point))
(setq semantic-lex-end-point ,endpnt))
))))
(defmacro define-lex-spp-macro-undeclaration-analyzer (name doc regexp tokidx)
"Undefine a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-undef' is to be created."
(let ((start (make-symbol "start"))
(end (make-symbol "end")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx)))
(semantic-lex-spp-symbol-remove
(buffer-substring-no-properties ,start ,end))
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-undef
,start ,end))
))))
(add-hook
'edebug-setup-hook
#'(lambda ()
(def-edebug-spec define-lex-spp-macro-declaration-analyzer
(&define name stringp stringp form def-body)
)
(def-edebug-spec define-lex-spp-macro-undeclaration-analyzer
(&define name stringp stringp form def-body)
)
))
(provide 'semantic-lex-spp)
;;; semantic-lex-spp.el ends here
| true | ;;; semantic-lex-spp.el --- Semantic Lexical Pre-processor
;;; Copyright (C) 2006, 2007 PI:NAME:<NAME>END_PI
;; X-CVS: $Id: semantic-lex-spp.el,v 1.8 2007/06/06 01:05:05 zappo Exp $
;; This file is not part of GNU Emacs.
;; Semantic 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 software 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 Semantic Preprocessor works with semantic-lex to provide a phase
;; during lexical analysis to do the work of a pre-processor.
;;
;; A pre-processor identifies lexical syntax mixed in with another language
;; and replaces some keyword tokens with streams of alternate tokens.
;;
;; If you use SPP in your language, be sure to specify this in your
;; semantic language setup function:
;;
;; (add-hook 'semantic-lex-reset-hooks 'semantic-lex-spp-reset-hook nil t)
;;
;;; TODO:
;;
;; Use `semantic-push-parser-warning' for situations where there are likely
;; macros that are undefined unexpectedly, or other problem.
(require 'semantic-lex)
;;; Code:
(defvar semantic-lex-spp-macro-symbol-obarray nil
"Table of macro keywords used by the Semantic Macro.")
(make-variable-buffer-local 'semantic-lex-spp-macro-symbol-obarray)
(defvar semantic-lex-spp-dynamic-macro-symbol-obarray nil
"Table of macro keywords found during lexical analysis.
This table is then used by the macro during the lexical analysis
step.")
(make-variable-buffer-local 'semantic-lex-spp-dynamic-macro-symbol-obarray)
;;; MACRO TABLE UTILS
;;
(defun semantic-lex-spp-symbol-replacement (name)
"Return an SPP replacement stream for NAME.
nil is a valid return. Use `semantic-lex-spp-symbol-l\p' to determine
if the symbol is in the table."
)
(defsubst semantic-lex-spp-symbol (name)
"Return spp symbol with NAME or nil if not found."
(and
(stringp name)
(or (and (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-dynamic-macro-symbol-obarray))
(and (arrayp semantic-lex-spp-macro-symbol-obarray)
(intern-soft name semantic-lex-spp-macro-symbol-obarray)))))
(defsubst semantic-lex-spp-symbol-p (name)
"Return non-nil if a keyword with NAME exists in any keyword table."
(if (semantic-lex-spp-symbol name)
t))
(defsubst semantic-lex-spp-dynamic-map ()
"Return the dynamic macro map for the current buffer."
(or semantic-lex-spp-dynamic-macro-symbol-obarray
(setq semantic-lex-spp-dynamic-macro-symbol-obarray
(make-vector 13 0))))
(defsubst semantic-lex-spp-symbol-set (name value &optional obarray)
"Set value of spp symbol with NAME to VALUE and return VALUE.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(if (string= value "") (setq value nil))
(set (intern name (or obarray
(semantic-lex-spp-dynamic-map)))
value))
(defsubst semantic-lex-spp-symbol-remove (name &optional obarray)
"Remove the spp symbol with NAME.
If optional OBARRAY is non-nil, then use that obarray instead of
the dynamic map."
(unintern name (or obarray
(semantic-lex-spp-dynamic-map))))
(defsubst semantic-lex-spp-symbol-stream (name)
"Return replacement stream of macro with NAME."
(let ((spp (semantic-lex-spp-symbol name)))
(if spp
(symbol-value spp))))
(defun semantic-lex-make-spp-table (specs)
"Convert spp macro list SPECS into an obarray and return it.
SPECS must be a list of (NAME . REPLACEMENT) elements, where:
NAME is the name of the spp macro symbol to define.
REPLACEMENT a string that would be substituted in for NAME."
;; Create the symbol hash table
(let ((semantic-lex-spp-macro-symbol-obarray (make-vector 13 0))
spec)
;; fill it with stuff
(while specs
(setq spec (car specs)
specs (cdr specs))
(semantic-lex-spp-symbol-set
(car spec)
(cdr spec)
semantic-lex-spp-macro-symbol-obarray))
semantic-lex-spp-macro-symbol-obarray))
(defun semantic-lex-spp-macros ()
"Return a list of spp macros as Lisp symbols.
The value of each symbol is the replacement stream."
(let (macros)
(when (arrayp semantic-lex-spp-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-macro-symbol-obarray))
(when (arrayp semantic-lex-spp-dynamic-macro-symbol-obarray)
(mapatoms
#'(lambda (symbol)
(setq macros (cons symbol macros)))
semantic-lex-spp-dynamic-macro-symbol-obarray))
macros))
(defun semantic-lex-spp-reset-dynamic-table ()
"Reset the dynamic spp symbol table.
This should be done before any new parsing step."
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil))
(defun semantic-lex-spp-reset-hook (start end)
"Reset anything needed by SPP for parsing.
In this case, reset the dynamic macro symbol table if
START recons the entire buffer.
END is not used."
(if (= start (point-min))
(setq semantic-lex-spp-dynamic-macro-symbol-obarray nil)))
;;; MACRO EXPANSION PARSING
;;
(defun semantic-lex-spp-string-to-macro-stream (val beg end)
"Convert string VAL into a macro expansion stream.
Argument VAL is the value of some macro to be converted into a stream.
BEG and END are the token bounds of the macro to be expanded
that will somehow gain a much longer token stream."
;; NOTE: Must write this function!!!!!
;; We perform a replacement. Technically, this should
;; be a full lexical step over the "val" string, but take
;; a guess that its just a keyword or existing symbol.
;;
;; Probably a really bad idea. See how it goes.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p val) 'symbol)
beg end
val))
)
;;; MACRO TABLE DEBUG
;;
(defun semantic-lex-spp-describe (&optional buffer)
"Describe the current list of spp macros for BUFFER.
If BUFFER is not provided, use the current buffer."
(interactive)
(let ((syms (save-excursion
(if buffer (set-buffer buffer))
(semantic-lex-spp-macros)))
(sym nil))
(with-output-to-temp-buffer "*SPP MACROS*"
(princ "Macro\t\tValue\n")
(while syms
(setq sym (car syms)
syms (cdr syms))
(princ (symbol-name sym))
(princ "\t")
(if (< (length (symbol-name sym)) 8)
(princ "\t"))
(prin1 (symbol-value sym))
(princ "\n")
))))
;;; Analyzers
;;
(define-lex-regex-analyzer semantic-lex-spp-replace-or-symbol-or-keyword
"Like 'semantic-lex-symbol-or-keyword' plus preprocessor macro replacement."
"\\(\\sw\\|\\s_\\)+"
(let ((str (match-string 0))
(beg (match-beginning 0))
(end (match-end 0)))
(if (semantic-lex-spp-symbol-p str)
;; It is a macro. Prepare for a replacement.
(let* ((sym (semantic-lex-spp-symbol str))
(val (symbol-value sym)))
(if (not val)
(setq semantic-lex-end-point end)
(semantic-lex-spp-string-to-macro-stream val beg end)
))
;; A regular keyword.
(semantic-lex-push-token
(semantic-lex-token (or (semantic-lex-keyword-p str) 'symbol)
beg end)))))
(defmacro define-lex-spp-macro-declaration-analyzer (name doc regexp tokidx
&rest valform)
"Define a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-def' is to be created.
Optional VALFORM are forms that return the value to be saved for
this macro, or nil."
(let ((start (make-symbol "start"))
(end (make-symbol "end"))
(val (make-symbol "val"))
(startpnt (make-symbol "startpnt"))
(endpnt (make-symbol "endpnt")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx))
(,startpnt semantic-lex-end-point)
(,val (save-match-data ,@valform))
(,endpnt semantic-lex-end-point))
(semantic-lex-spp-symbol-set
(buffer-substring-no-properties ,start ,end)
,val)
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-def
,start ,end))
;; Preserve setting of the end point from the calling macro.
(when (and (/= ,startpnt ,endpnt)
(/= ,endpnt semantic-lex-end-point))
(setq semantic-lex-end-point ,endpnt))
))))
(defmacro define-lex-spp-macro-undeclaration-analyzer (name doc regexp tokidx)
"Undefine a lexical analyzer for defining new MACROS.
NAME is the name of the analyzer.
DOC is the documentation for the analyzer.
REGEXP is a regular expression for the analyzer to match.
See `define-lex-regex-analyzer' for more on regexp.
TOKIDX is an index into REGEXP for which a new lexical token
of type `spp-macro-undef' is to be created."
(let ((start (make-symbol "start"))
(end (make-symbol "end")))
`(define-lex-regex-analyzer ,name
,doc
,regexp
(let ((,start (match-beginning ,tokidx))
(,end (match-end ,tokidx)))
(semantic-lex-spp-symbol-remove
(buffer-substring-no-properties ,start ,end))
(semantic-lex-push-token
(semantic-lex-token 'spp-macro-undef
,start ,end))
))))
(add-hook
'edebug-setup-hook
#'(lambda ()
(def-edebug-spec define-lex-spp-macro-declaration-analyzer
(&define name stringp stringp form def-body)
)
(def-edebug-spec define-lex-spp-macro-undeclaration-analyzer
(&define name stringp stringp form def-body)
)
))
(provide 'semantic-lex-spp)
;;; semantic-lex-spp.el ends here
|
[
{
"context": " byte-compiled files.\n\n;; Copyright (C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>",
"end": 112,
"score": 0.9998699426651001,
"start": 102,
"tag": "NAME",
"value": "R.Ramkumar"
},
{
"context": " Copyright (C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>\n;; Created: \t14 Jul 200",
"end": 136,
"score": 0.9998825788497925,
"start": 126,
"tag": "NAME",
"value": "R.Ramkumar"
},
{
"context": "C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>\n;; Created: \t14 Jul 2004\n;; Version: \t1.0\n;; Key",
"end": 161,
"score": 0.9999288320541382,
"start": 138,
"tag": "EMAIL",
"value": "andyetitmoves@gmail.com"
},
{
"context": " this\n;; program's author (send electronic mail to andyetitmoves@gmail.com)\n;; or from the Free Software Foundation, Inc.,\n;",
"end": 900,
"score": 0.9999301433563232,
"start": 877,
"tag": "EMAIL",
"value": "andyetitmoves@gmail.com"
}
] | elisp/misc/safe-load.el | andyetitmoves/dot-files | 1 | ;;; SAFE-LOAD.EL --- Timestamp checking for loading byte-compiled files.
;; Copyright (C) 2004, 2005 R.Ramkumar
;; Author: R.Ramkumar <andyetitmoves@gmail.com>
;; Created: 14 Jul 2004
;; Version: 1.0
;; Keywords: load
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to andyetitmoves@gmail.com)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; A common problem facing elisp developers (atleast me) concerns byte-compiling
;; of the files they are involved in developing. While byte-compiling does speed
;; up your packages, one invariably forgets to update the compiled file after
;; making a change in the source. Worse still, you forget that the byte-compiled
;; file is getting loaded and end up getting frustrated about a change you made
;; but never saw it getting effected. So, here is a function advising before
;; load to check if there is a more recent source file lying around and
;; byte-compile it after prompting the user.
;;; Bugs:
;; This package does not work for autoloads, loading seems to get
;; short-circuited through the C code.
;;; Installation:
;; Just load this file at initialisation time.
;; The earlier, the better, as all further loads are protected.
;;; Code:
(defvar safe-load-compile-start-prompt t
"*Prompt user before compilation on calling `check-load-file'.")
(defvar safe-load-compile-end-prompt t
"*Prompt user after compilation on calling `check-load-file'.")
(require 'help) ; For the `locate-library' function
(defun check-load-file (file &optional nofind)
"Update byte-compiled FILE based on filestamp of corresponding source file.
The corresponding source is the file with the same basename ( in the same
directory ) and with suffix .el. FILE should have an extension of .elc. Unless
NOFIND is non-nil, an attempt is made to locate the file using `locate-library'."
(and (stringp file)
(or nofind (setq file (locate-library file)))
(let (altfile)
(and (string= (file-name-extension file) "elc")
(setq altfile
(substitute-in-file-name
(concat (file-name-sans-extension file) ".el")))
(file-newer-than-file-p altfile file)
(if (file-writable-p file)
(when
(or (not safe-load-compile-start-prompt)
(y-or-n-p (format "Source %s is newer, byte-compile "
altfile)))
(setq nofind (condition-case nil
(byte-compile-file altfile)
(error nil)))
(and safe-load-compile-end-prompt
(read-event
(format "%s byte-compiling file %s, press any key..."
(if nofind "Success" "Error") altfile)))
nofind)
(message "File %s needs byte-compilation, but is not writable."
altfile) nil)))))
(require 'advice)
(defadvice load
(before safe-load (file &optional noerror nomessage nosuffix must-suffix)
disable preactivate)
"Check load file if byte-compiled and old, before load.
The load-file is checked with `check-load-file' before proceeding with the load."
(check-load-file file must-suffix))
(defadvice require
(before safe-load (feature &optional filename noerror) disable preactivate)
"Check if require needs load of old byte-compiled file.
The file is checked with `check-load-file' before proceeding with require."
(and (symbolp feature)
(or (memq feature features)
(check-load-file (or filename (symbol-name feature))))))
;; If this file is on the load-path, do a self test
(if (check-load-file "safe-load")
(load "safe-load")
;; Check over, can go for activation
(ad-activate 'load)
(ad-activate 'require))
(provide 'safe-load)
;;; SAFE-LOAD.EL ends here
| 45423 | ;;; SAFE-LOAD.EL --- Timestamp checking for loading byte-compiled files.
;; Copyright (C) 2004, 2005 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Created: 14 Jul 2004
;; Version: 1.0
;; Keywords: load
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to <EMAIL>)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; A common problem facing elisp developers (atleast me) concerns byte-compiling
;; of the files they are involved in developing. While byte-compiling does speed
;; up your packages, one invariably forgets to update the compiled file after
;; making a change in the source. Worse still, you forget that the byte-compiled
;; file is getting loaded and end up getting frustrated about a change you made
;; but never saw it getting effected. So, here is a function advising before
;; load to check if there is a more recent source file lying around and
;; byte-compile it after prompting the user.
;;; Bugs:
;; This package does not work for autoloads, loading seems to get
;; short-circuited through the C code.
;;; Installation:
;; Just load this file at initialisation time.
;; The earlier, the better, as all further loads are protected.
;;; Code:
(defvar safe-load-compile-start-prompt t
"*Prompt user before compilation on calling `check-load-file'.")
(defvar safe-load-compile-end-prompt t
"*Prompt user after compilation on calling `check-load-file'.")
(require 'help) ; For the `locate-library' function
(defun check-load-file (file &optional nofind)
"Update byte-compiled FILE based on filestamp of corresponding source file.
The corresponding source is the file with the same basename ( in the same
directory ) and with suffix .el. FILE should have an extension of .elc. Unless
NOFIND is non-nil, an attempt is made to locate the file using `locate-library'."
(and (stringp file)
(or nofind (setq file (locate-library file)))
(let (altfile)
(and (string= (file-name-extension file) "elc")
(setq altfile
(substitute-in-file-name
(concat (file-name-sans-extension file) ".el")))
(file-newer-than-file-p altfile file)
(if (file-writable-p file)
(when
(or (not safe-load-compile-start-prompt)
(y-or-n-p (format "Source %s is newer, byte-compile "
altfile)))
(setq nofind (condition-case nil
(byte-compile-file altfile)
(error nil)))
(and safe-load-compile-end-prompt
(read-event
(format "%s byte-compiling file %s, press any key..."
(if nofind "Success" "Error") altfile)))
nofind)
(message "File %s needs byte-compilation, but is not writable."
altfile) nil)))))
(require 'advice)
(defadvice load
(before safe-load (file &optional noerror nomessage nosuffix must-suffix)
disable preactivate)
"Check load file if byte-compiled and old, before load.
The load-file is checked with `check-load-file' before proceeding with the load."
(check-load-file file must-suffix))
(defadvice require
(before safe-load (feature &optional filename noerror) disable preactivate)
"Check if require needs load of old byte-compiled file.
The file is checked with `check-load-file' before proceeding with require."
(and (symbolp feature)
(or (memq feature features)
(check-load-file (or filename (symbol-name feature))))))
;; If this file is on the load-path, do a self test
(if (check-load-file "safe-load")
(load "safe-load")
;; Check over, can go for activation
(ad-activate 'load)
(ad-activate 'require))
(provide 'safe-load)
;;; SAFE-LOAD.EL ends here
| true | ;;; SAFE-LOAD.EL --- Timestamp checking for loading byte-compiled files.
;; Copyright (C) 2004, 2005 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 14 Jul 2004
;; Version: 1.0
;; Keywords: load
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to PI:EMAIL:<EMAIL>END_PI)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; A common problem facing elisp developers (atleast me) concerns byte-compiling
;; of the files they are involved in developing. While byte-compiling does speed
;; up your packages, one invariably forgets to update the compiled file after
;; making a change in the source. Worse still, you forget that the byte-compiled
;; file is getting loaded and end up getting frustrated about a change you made
;; but never saw it getting effected. So, here is a function advising before
;; load to check if there is a more recent source file lying around and
;; byte-compile it after prompting the user.
;;; Bugs:
;; This package does not work for autoloads, loading seems to get
;; short-circuited through the C code.
;;; Installation:
;; Just load this file at initialisation time.
;; The earlier, the better, as all further loads are protected.
;;; Code:
(defvar safe-load-compile-start-prompt t
"*Prompt user before compilation on calling `check-load-file'.")
(defvar safe-load-compile-end-prompt t
"*Prompt user after compilation on calling `check-load-file'.")
(require 'help) ; For the `locate-library' function
(defun check-load-file (file &optional nofind)
"Update byte-compiled FILE based on filestamp of corresponding source file.
The corresponding source is the file with the same basename ( in the same
directory ) and with suffix .el. FILE should have an extension of .elc. Unless
NOFIND is non-nil, an attempt is made to locate the file using `locate-library'."
(and (stringp file)
(or nofind (setq file (locate-library file)))
(let (altfile)
(and (string= (file-name-extension file) "elc")
(setq altfile
(substitute-in-file-name
(concat (file-name-sans-extension file) ".el")))
(file-newer-than-file-p altfile file)
(if (file-writable-p file)
(when
(or (not safe-load-compile-start-prompt)
(y-or-n-p (format "Source %s is newer, byte-compile "
altfile)))
(setq nofind (condition-case nil
(byte-compile-file altfile)
(error nil)))
(and safe-load-compile-end-prompt
(read-event
(format "%s byte-compiling file %s, press any key..."
(if nofind "Success" "Error") altfile)))
nofind)
(message "File %s needs byte-compilation, but is not writable."
altfile) nil)))))
(require 'advice)
(defadvice load
(before safe-load (file &optional noerror nomessage nosuffix must-suffix)
disable preactivate)
"Check load file if byte-compiled and old, before load.
The load-file is checked with `check-load-file' before proceeding with the load."
(check-load-file file must-suffix))
(defadvice require
(before safe-load (feature &optional filename noerror) disable preactivate)
"Check if require needs load of old byte-compiled file.
The file is checked with `check-load-file' before proceeding with require."
(and (symbolp feature)
(or (memq feature features)
(check-load-file (or filename (symbol-name feature))))))
;; If this file is on the load-path, do a self test
(if (check-load-file "safe-load")
(load "safe-load")
;; Check over, can go for activation
(ad-activate 'load)
(ad-activate 'require))
(provide 'safe-load)
;;; SAFE-LOAD.EL ends here
|
[
{
"context": "m-version \"0.2.2 (July 26, 2006)\")\n;;\n;; Author: Naoto Morishima <naoto@morishima.net>\n;; Created: August 6, 2004",
"end": 140,
"score": 0.9998912811279297,
"start": 125,
"tag": "NAME",
"value": "Naoto Morishima"
},
{
"context": "July 26, 2006)\")\n;;\n;; Author: Naoto Morishima <naoto@morishima.net>\n;; Created: August 6, 2004\n;; Revised: July 26",
"end": 161,
"score": 0.9999306201934814,
"start": 142,
"tag": "EMAIL",
"value": "naoto@morishima.net"
}
] | elpa/elscreen-20140421.414/elscreen-w3m.el | MauroCalderara/emacs_config | 19 | ;; -*- Mode: Emacs-Lisp -*-
;;
;; elscreen-w3m.el
;;
(defconst elscreen-w3m-version "0.2.2 (July 26, 2006)")
;;
;; Author: Naoto Morishima <naoto@morishima.net>
;; Created: August 6, 2004
;; Revised: July 26, 2006
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
(provide 'elscreen-w3m)
(require 'elscreen)
;; Code:
(defconst elscreen-w3m-mode-to-nickname-alist
'(("^w3m-mode" .
(lambda (buf)
(with-current-buffer buf
(let ((graphic (and window-system
w3m-show-graphic-icons-in-header-line)))
(concat
(when (and graphic w3m-use-favicon w3m-favicon-image)
(concat
(propertize
" "
'display w3m-favicon-image)
(propertize
" "
'display '(space :width 0.5))))
(w3m-current-title)))))))
"*Alist composed of the pair of mode-name and corresponding screen-name.")
(elscreen-set-mode-to-nickname-alist 'elscreen-w3m-mode-to-nickname-alist)
(defun elscreen-w3m-mailto-url-popup-function (buffer)
(elscreen-find-and-goto-by-buffer buffer 'create))
(defadvice w3m-copy-buffer (around elscreen-w3m-copy-buffer activate)
(let ((current-buffer (current-buffer)))
(if (< (elscreen-get-number-of-screens) 10)
(elscreen-create)
(split-window)
(other-window 1))
(unless (ad-get-arg 0)
(ad-set-arg 0 current-buffer))
ad-do-it))
(defadvice w3m-favicon-retrieve (around elscreen-w3m-favicon-retrieve activate)
ad-do-it
(run-at-time 1 nil 'elscreen-notify-screen-modification 'force-immediately))
(defun elscreen-w3m-initialize ()
(setq w3m-pop-up-frames nil)
(setq w3m-pop-up-windows nil)
(setq w3m-use-tab nil)
(setq w3m-use-tab-menubar nil)
(setq w3m-use-header-line nil)
(setq w3m-mailto-url-popup-function-alist
'((cmail-mail-mode . elscreen-w3m-mailto-url-popup-function)
(mail-mode . elscreen-w3m-mailto-url-popup-function)
(message-mode . elscreen-w3m-mailto-url-popup-function)
(mew-draft-mode . elscreen-w3m-mailto-url-popup-function)
(mh-letter-mode . elscreen-w3m-mailto-url-popup-function)
(wl-draft-mode . elscreen-w3m-mailto-url-popup-function)))
(elscreen-screen-modified-hook-setup
(w3m-fontify-after-hook 'force-immediately)))
(add-hook 'w3m-load-hook 'elscreen-w3m-initialize)
| 12572 | ;; -*- Mode: Emacs-Lisp -*-
;;
;; elscreen-w3m.el
;;
(defconst elscreen-w3m-version "0.2.2 (July 26, 2006)")
;;
;; Author: <NAME> <<EMAIL>>
;; Created: August 6, 2004
;; Revised: July 26, 2006
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
(provide 'elscreen-w3m)
(require 'elscreen)
;; Code:
(defconst elscreen-w3m-mode-to-nickname-alist
'(("^w3m-mode" .
(lambda (buf)
(with-current-buffer buf
(let ((graphic (and window-system
w3m-show-graphic-icons-in-header-line)))
(concat
(when (and graphic w3m-use-favicon w3m-favicon-image)
(concat
(propertize
" "
'display w3m-favicon-image)
(propertize
" "
'display '(space :width 0.5))))
(w3m-current-title)))))))
"*Alist composed of the pair of mode-name and corresponding screen-name.")
(elscreen-set-mode-to-nickname-alist 'elscreen-w3m-mode-to-nickname-alist)
(defun elscreen-w3m-mailto-url-popup-function (buffer)
(elscreen-find-and-goto-by-buffer buffer 'create))
(defadvice w3m-copy-buffer (around elscreen-w3m-copy-buffer activate)
(let ((current-buffer (current-buffer)))
(if (< (elscreen-get-number-of-screens) 10)
(elscreen-create)
(split-window)
(other-window 1))
(unless (ad-get-arg 0)
(ad-set-arg 0 current-buffer))
ad-do-it))
(defadvice w3m-favicon-retrieve (around elscreen-w3m-favicon-retrieve activate)
ad-do-it
(run-at-time 1 nil 'elscreen-notify-screen-modification 'force-immediately))
(defun elscreen-w3m-initialize ()
(setq w3m-pop-up-frames nil)
(setq w3m-pop-up-windows nil)
(setq w3m-use-tab nil)
(setq w3m-use-tab-menubar nil)
(setq w3m-use-header-line nil)
(setq w3m-mailto-url-popup-function-alist
'((cmail-mail-mode . elscreen-w3m-mailto-url-popup-function)
(mail-mode . elscreen-w3m-mailto-url-popup-function)
(message-mode . elscreen-w3m-mailto-url-popup-function)
(mew-draft-mode . elscreen-w3m-mailto-url-popup-function)
(mh-letter-mode . elscreen-w3m-mailto-url-popup-function)
(wl-draft-mode . elscreen-w3m-mailto-url-popup-function)))
(elscreen-screen-modified-hook-setup
(w3m-fontify-after-hook 'force-immediately)))
(add-hook 'w3m-load-hook 'elscreen-w3m-initialize)
| true | ;; -*- Mode: Emacs-Lisp -*-
;;
;; elscreen-w3m.el
;;
(defconst elscreen-w3m-version "0.2.2 (July 26, 2006)")
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: August 6, 2004
;; Revised: July 26, 2006
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
(provide 'elscreen-w3m)
(require 'elscreen)
;; Code:
(defconst elscreen-w3m-mode-to-nickname-alist
'(("^w3m-mode" .
(lambda (buf)
(with-current-buffer buf
(let ((graphic (and window-system
w3m-show-graphic-icons-in-header-line)))
(concat
(when (and graphic w3m-use-favicon w3m-favicon-image)
(concat
(propertize
" "
'display w3m-favicon-image)
(propertize
" "
'display '(space :width 0.5))))
(w3m-current-title)))))))
"*Alist composed of the pair of mode-name and corresponding screen-name.")
(elscreen-set-mode-to-nickname-alist 'elscreen-w3m-mode-to-nickname-alist)
(defun elscreen-w3m-mailto-url-popup-function (buffer)
(elscreen-find-and-goto-by-buffer buffer 'create))
(defadvice w3m-copy-buffer (around elscreen-w3m-copy-buffer activate)
(let ((current-buffer (current-buffer)))
(if (< (elscreen-get-number-of-screens) 10)
(elscreen-create)
(split-window)
(other-window 1))
(unless (ad-get-arg 0)
(ad-set-arg 0 current-buffer))
ad-do-it))
(defadvice w3m-favicon-retrieve (around elscreen-w3m-favicon-retrieve activate)
ad-do-it
(run-at-time 1 nil 'elscreen-notify-screen-modification 'force-immediately))
(defun elscreen-w3m-initialize ()
(setq w3m-pop-up-frames nil)
(setq w3m-pop-up-windows nil)
(setq w3m-use-tab nil)
(setq w3m-use-tab-menubar nil)
(setq w3m-use-header-line nil)
(setq w3m-mailto-url-popup-function-alist
'((cmail-mail-mode . elscreen-w3m-mailto-url-popup-function)
(mail-mode . elscreen-w3m-mailto-url-popup-function)
(message-mode . elscreen-w3m-mailto-url-popup-function)
(mew-draft-mode . elscreen-w3m-mailto-url-popup-function)
(mh-letter-mode . elscreen-w3m-mailto-url-popup-function)
(wl-draft-mode . elscreen-w3m-mailto-url-popup-function)))
(elscreen-screen-modified-hook-setup
(w3m-fontify-after-hook 'force-immediately)))
(add-hook 'w3m-load-hook 'elscreen-w3m-initialize)
|
[
{
"context": "o core prelude layer\n;;\n;; Copyright (c) 2018-2021 Jade Michael Thornton\n;;\n;; This file is not part of GNU Emacs\n;;\n;; Pe",
"end": 111,
"score": 0.9998144507408142,
"start": 90,
"tag": "NAME",
"value": "Jade Michael Thornton"
},
{
"context": "use-package pomp\n :straight (:host gitlab :repo \"thornjad/pomp\")\n :after (general evil)\n :commands (pomp)",
"end": 23690,
"score": 0.948215663433075,
"start": 23682,
"tag": "USERNAME",
"value": "thornjad"
}
] | lib/aero-prelude.el | thornjad/aero | 1 | ;; -*- lexical-binding: t -*-
;;
;; Aero core prelude layer
;;
;; Copyright (c) 2018-2021 Jade Michael Thornton
;;
;; This file is not part of GNU Emacs
;;
;; Permission to use, copy, modify, and/or distribute this software for any
;; purpose with or without fee is hereby granted, provided that the above
;; copyright notice and this permission notice appear in all copies.
;;
;; The software is provided "as is" and the author disclaims all warranties with
;; regard to this software including all implied warranties of merchantability
;; and fitness. In no event shall the author be liable for any special, direct,
;; indirect, or consequential damages or any damages whatsoever resulting from
;; loss of use, data or profits, whether in an action of contract, negligence or
;; other tortious action, arising out of or in connection with the use or
;; performance of this software.
;;
(require 'cl-lib)
(require 'straight)
(require 'use-package)
(require 'aero-lib)
;;; Code:
;;; Set up core packages
(use-package gnu-elpa-keyring-update :straight t)
(use-package exec-path-from-shell :straight t :defer 1
:config
(when (or (window-system) (daemonp))
(dolist (var '("SSH_AUTH_SOCK" "SSH_AGENT_PID" "GPG_AGENT_INFO" "LANG" "LC_CTYPE" "NIX_SSL_CERT_FILE" "NIX_PATH"))
(add-to-list 'exec-path-from-shell-variables var))
(exec-path-from-shell-initialize)))
(use-package no-littering :defer 5
:after recentf
:straight (:host github :repo "emacscollective/no-littering")
:defines (no-littering-var-directory
no-littering-etc-directory)
:config
(add-to-list 'recentf-exclude no-littering-var-directory)
(add-to-list 'recentf-exclude no-littering-etc-directory))
;;; get ready to patch at any time
(use-package el-patch :straight t
:init (setq el-patch-enable-use-package-integration t))
;; Only needed at compile time
(eval-when-compile
(require 'el-patch))
;;; used in several places
(use-package ripgrep :straight t :defer 3)
;;; the general is here
(use-package general :straight t
:functions (general-define-key)
:init
(setq-default general-override-states
'(insert hybrid normal visual motion operator replace))
:config
(general-create-definer aero-leader-def
:states '(normal visual emacs motion)
:prefix "SPC"
:non-normal-prefix "C-SPC")
(general-create-definer aero-mode-leader-def
:states '(normal visual emacs motion)
:prefix ",")
(general-define-key
:states '(normal visual motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil)
;; Main configuration
(general-def
;; Emacs chose ^? for the help system for some despicable reason. Fuck that.
(kbd "C-h") 'delete-backward-char
(kbd "C-w") 'aero/smarter-backward-kill-word
(kbd "C-TAB") 'insert-tab
(kbd "M-TAB") 'aero/alternate-buffer)
(general-define-key
:states 'normal
:prefix "SPC"
"fW" 'evil-write-all
"w/" '(evil-window-vsplit :wk "split vertical")
"w-" '(evil-window-split :wk "split horizontal")
"cm" 'evil-make)
(global-set-key [remap keyboard-quit] #'aero/keyboard-quit-context)
;; mode-specific overrides
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix ","
"" nil)
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil
;; independent keys
"TAB" '(aero/alternate-buffer :wk "alternate buffer")
(kbd "ESC") 'keyboard-quit
(kbd "C-g") 'keyboard-quit
"'" 'eshell
"\"" '(aero/eshell-new :wk "eshell-new")
":" 'eval-expression
";" 'comment-or-uncomment-region
"!" 'shell-command
"=" 'quick-calc
;; NOTE deprecated, use the top-level "," prefix instead
"," '(:ignore t :wk "mode") ; reserved for mode-specific
"U" 'universal-argument
"z" 'repeat
"q" '(:ignore t :wk "quoted insert")
"qq" 'quoted-insert
"ql" 'insert-lambda
"f" '(:ignore t :wk "files")
"fw" '(save-buffer :wk "write buffer")
"fW" '(aero/async-write-buffer :wk "async write buffer (experimental)")
"fC" '(:ignore t :wk "convert")
"fCd" '(aero/unix2dos :wk "unix2dos")
"fCu" '(aero/dos2unix :wk "dos2unix")
"fD" '(aero/delete-this-file :wk "delete this file")
"fE" '(aero/sudo-edit :wk "sudo edit")
"fR" '(aero/rename-this-file-and-buffer :wk "rename this file")
"fx" '(aero/xdg-open :wk "xdg-open")
"fo" '(:ignore t :wk "open special files")
"fot" '(:ignore t :wk "thornlog")
"fott" '(aero/thornlog-dir :wk "thornlog all")
"fotl" '(aero/thornlog-today :wk "thornlog log")
"fotd" '(aero/thornlog-todo :wk "thornlog todo")
"foP" 'aero/open-emacs-problems
"fof" 'aero/open-local-init
"o" '(:ignore t :wk "org")
"oa" 'org-agenda
"ot" 'aero/task
"oe" '(:ignore t :wk "org edit")
"oet" '(:ignore t :wk "org table")
"oets" 'org-table-sort-lines
"h" '(:ignore t :wk "help/manual")
"hM" 'woman
"hm" 'man
"hi" 'info
"hI" 'info-apropos
"hd" '(:ignore t :wk "describe")
"hw" '(:ignore t :wk "which-key")
"hwm" '(which-key-show-major-mode :wk "major mode map")
"b" '(:ignore t :wk "buffers")
"bn" 'next-buffer
"bp" 'previous-buffer
"bl" 'ibuffer
"bL" 'list-buffers
"bm" 'switch-to-messages-buffer
"br" '(aero/reopen-file-at-buffer :wk "reopen file")
"bs" 'switch-to-scratch-buffer
"bS" 'switch-to-new-scratch-buffer
"bd" 'kill-this-buffer
"bx" 'kill-buffer-and-window
"bw" '(whitespace-mode :wk "whitespace")
"bt" '(:ignore t :wk "tabify")
"btu" 'untabify-buffer
"btt" 'tabify-buffer
"bi" 'indent-buffer
"bP" 'aero/toggle-prettify-this-buffer
"E" '(:ignore t :wk "emacs")
"Et" 'counsel-load-theme
"Ea" 'aero/apologize-to-emacs
"Ed" '(:ignore t :wk "debug")
"Ede" 'toggle-debug-on-error
"Edq" 'toggle-debug-on-quit
"a" '(:ignore t :wk "applications")
"ad" 'counsel-dired
"ag" '(:ignore t :wk "games")
"agt" 'tetris
"agd" 'dunnet
"c" '(:ignore t :wk "compile")
"cc" 'compile
"cC" '(aero/byte-recompile-file-at-buffer :wk "byte recompile file at buffer")
"ck" 'kill-compilation
"cr" 'recompile
"cR" 'byte-recompile-file
"ce" '(:ignore t :wk "elisp")
"cei" '(ielm :wk "ielm repl")
"cer" 'eval-region
"ceb" 'eval-buffer
"ced" 'eval-defun
"cec" '(:ignore t :wk "compile")
"cecb" '(aero/native-compile-file-at-buffer :wk "file at buffer")
"ceB" '(:ignore t :wk "byte compile")
"ceBb" '(aero/byte-compile-file-at-buffer :wk "file at buffer")
"ceBr" '(aero/byte-recompile-file-at-buffer :wk "file at buffer (recompile)")
"ceBf" '(byte-compile-file :wk "other file")
"ceBF" '(async-byte-compile-file :wk "other file async")
"ceBd" '(byte-recompile-directory :wk "directory")
"e" '(:ignore t :wk "errors")
"en" 'next-error
"ep" 'previous-error
"F" '(:ignore t :wk "frame")
"Fd" 'delete-frame
"Fo" 'other-frame
"FF" 'find-file-other-frame
"Fn" 'make-frame
"Fm" 'toggle-frame-maximized
"Ff" 'toggle-frame-fullscreen
"g" '(:ignore t :wk "git")
"gf" '(:ignore t :wk "files")
"l" '(:ignore t :wk "lsp")
"L" '(:ignore t :wk "local")
"j" '(:ignore t :wk "jump")
"s" '(:ignore t :wk "sexp")
"m" '(:ignore t :wk "mode")
"d" '(:ignore t :wk "debug")
"p" '(:ignore t :wk "project")
"pr" '(xref-find-definitions :wk "find ref")
"P" '(:ignore t :wk "packages/perspective")
"PP" '(:ignore t :wk "packages")
"PPp" 'straight-pull-package-and-deps
"PPF" 'straight-fetch-all
"PPP" 'straight-pull-all
"PPg" 'straight-get-recipe
"PPC" 'straight-check-all
"PPr" 'straight-rebuild-package
"PPR" 'straight-rebuild-all
"PPx" 'straight-prune-build
"u" 'undo-tree-visualize
"S" '(:ignore t :wk "shell/sql")
"Se" 'eshell
"SE" '(:ignore t :wk "eshell")
"St" '(:ignore t :wk "term")
"T" '(:ignore t :wk "tab")
"TT" 'tab-bar-mode
"Tj" 'tab-next
"Tk" 'tab-previous
"Tc" '(tab-new :wk "create tab")
"TL" 'tab-list
"TL" 'tab-last
"T TAB" 'tab-recent
"T," 'tab-rename
"Ts" '(tab-duplicate :wk "tab duplicate split")
"Td" 'tab-close
"Tu" 'tab-undo
"Tg" '(tab-select :wk "tab go")
"Tb" 'switch-to-buffer-other-tab
"Tf" 'find-file-other-tab
"w" '(:ignore t :wk "window/web")
"ww" 'eww
"wp" 'browse-url-at-point
"ws" '(eww-search-words :which-key "web search")
"w=" 'balance-windows
"wB" '(aero/switch-to-minibuffer-window :wk "switch to minibuffer")
"wd" 'delete-window
"wF" 'make-frame
"w{" 'shrink-window
"w}" 'enlarge-window
"wm" 'maximize-window
"wi" 'minimize-window
"wo" 'browse-url-xdg-open
"wb" '(:ignore t :wk "browse")
"wbm" 'eww-list-bookmarks
"wbb" 'eww-list-buffers
"wbh" 'eww-list-histories
"wL" '(:ignore t :wk "layout")
"wL2" 'aero/layout-two-columns
"wL3" 'aero/layout-three-columns
"t" '(:ignore t :wk "tabs/text")
"tf" 'fill-paragraph
"tU" 'upcase-dwim
"tD" 'downcase-dwim
"ts" 'sort-lines
"tn" '(:ignore t :wk "number")
"tni" 'increment-number-at-point
"tnd" 'decrement-number-at-point))
(use-package which-key :straight t
:defines which-key-mode
:config
(which-key-mode)
(setq which-key-special-keys '("SPC" "TAB" "RET" "ESC" "DEL")))
;; we descend to hell
(use-package evil :straight t
:init
(setq evil-want-keybinding nil ; handled by evil-collection
;; to change undo-system without restart, use SPC-: `evil-set-undo-system'
evil-undo-system 'undo-tree
evil-want-fine-undo t
evil-want-C-i-jump nil
evil-want-C-u-scroll t)
:config
(use-package evil-collection
:config (evil-collection-init))
(define-key evil-motion-state-map " " nil)
;; default states
(setq evil-default-state 'normal)
(evil-set-initial-state 'dired-mode 'emacs)
(evil-set-initial-state 'message-mode 'motion)
;; Make movement keys work like they should by remapping next to next-visual, etc.
(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
;; Ensure horizontal movement doesn't cross lines
(setq-default evil-cross-lines nil)
(defun aero/evil-shift-right ()
(interactive)
(evil-shift-right evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(defun aero/evil-shift-left ()
(interactive)
(evil-shift-left evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(evil-define-key 'visual global-map (kbd ">") 'aero/evil-shift-right)
(evil-define-key 'visual global-map (kbd "<") 'aero/evil-shift-left)
;; :q should kill the current buffer rather than quitting emacs entirely
(evil-ex-define-cmd "q" 'kill-this-buffer)
;; Need to type out :quit to close emacs
(evil-ex-define-cmd "quit" 'evil-quit)
(evil-define-key '(normal visual motion) global-map
(kbd "C-e") #'evil-backward-word-end)
(evil-define-key '(normal visual motion) global-map
(kbd "C-M-e") #'evil-backward-WORD-end)
(evil-define-key '(insert) global-map
(kbd "C-y") #'evil-paste-after)
(evil-define-key '(insert) global-map
(kbd "C-S-y") #'evil-paste-before)
(evil-define-key 'normal 'global
;; Run macro in register q
"Q" "@q")
(evil-define-key 'visual 'global
;; run macro in register q on region
"Q" (kbd ":norm @q RET")
;; repeat on region
"." (kbd ":norm . RET"))
(evil-mode 1))
;; Doesn't do anything for GUI, so don't bother
(unless (display-graphic-p)
(use-package evil-terminal-cursor-changer
:after evil
:functions (evil-terminal-cursor-changer-activate)
:config (evil-terminal-cursor-changer-activate)))
(use-package evil-matchit :straight t :defer 5
:after evil
:defines global-evil-matchit-mode
:config (global-evil-matchit-mode 1))
(use-package evil-visualstar :straight t :defer 5
:after evil
:defines global-evil-visualstar-mode
:config
(global-evil-visualstar-mode t))
;; abo-abo!
(use-package counsel :straight t
:after general
:init/el-patch ; remove bindings which we use `helpful' for
(defvar counsel-mode-map
(let ((map (make-sparse-keymap)))
(dolist (binding
'((execute-extended-command . counsel-M-x)
(describe-bindings . counsel-descbinds)
(el-patch-remove
(describe-function . counsel-describe-function)
(describe-variable . counsel-describe-variable))
(apropos-command . counsel-apropos)
(describe-face . counsel-describe-face)
(list-faces-display . counsel-faces)
(find-file . counsel-find-file)
(find-library . counsel-find-library)
(imenu . counsel-imenu)
(load-library . counsel-load-library)
(load-theme . counsel-load-theme)
(yank-pop . counsel-yank-pop)
(info-lookup-symbol . counsel-info-lookup-symbol)
(pop-to-mark-command . counsel-mark-ring)
(bookmark-jump . counsel-bookmark)))
(define-key map (vector 'remap (car binding)) (cdr binding)))
map)
(el-patch-concat
"Map for `counsel-mode'.
Remaps built-in functions to counsel replacements."
(el-patch-add
"\n\nBindings that are remapped by `helpful' have been removed.")))
(defcustom counsel-mode-override-describe-bindings nil
"Whether to override `describe-bindings' when `counsel-mode' is active."
:type 'boolean
:group 'counsel)
(define-minor-mode counsel-mode
"Toggle Counsel mode on or off.
Turn Counsel mode on if ARG is positive, off otherwise. Counsel mode remaps
built-in emacs functions that have counsel replacements.
Local bindings (`counsel-mode-map'):
\\{counsel-mode-map}"
:global t
:keymap counsel-mode-map
:group 'counsel
(if counsel-mode
(progn
(when (and (fboundp 'advice-add)
counsel-mode-override-describe-bindings)
(advice-add #'describe-bindings :override #'counsel-descbinds))
(define-key minibuffer-local-map (kbd "C-r")
'counsel-minibuffer-history))
(when (fboundp 'advice-remove)
(advice-remove #'describe-bindings #'counsel-descbinds))))
:config
(setq counsel-find-file-ignore-regexp
(concat "\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)"
"\\|\\.x\\'\\|\\.d\\'\\|\\.o\\'"
"\\|\\.aux\\'"))
(defun aero/counsel-unicode-char-after ()
"Like `counsel-unicode-char', but insert after point"
(interactive)
(save-excursion
(right-char)
(counsel-unicode-char)))
(setq counsel-grep-base-command "rg -i -M 120 --no-heading --line-number --color never '%s' %s"
counsel-git-cmd "rg --files"
counsel-rg-base-command "rg --with-filename --smart-case --no-heading --line-number --color never %s")
(aero-leader-def
"SPC" 'counsel-M-x
"ff" 'counsel-find-file
"fl" 'counsel-locate
"fr" 'counsel-recentf
"?" 'counsel-rg
"gg" '(counsel-git-grep :wk "git grep")
"gff" '(counsel-git :wk "find git file")
"ry" '(counsel-yank-pop :wk "search kill ring")
"hda" '(counsel-apropos :wk "apropos")
"qu" '(aero/counsel-unicode-char-after :wk "unicode char")
"qU" 'counsel-unicode-char))
(use-package recentf :defer t
:defines (recentf-mode)
:config
(defvar aero-etc-dir)
(setq recentf-save-file (expand-file-name "recentf" aero-etc-dir)
recentf-max-saved-items 500
;; never cleanup, this will get rid of tramp files
recentf-auto-cleanup 'never)
(recentf-mode 1))
(use-package ivy :straight t
:after general
:functions ivy-mode
:config
(use-package flx :straight t)
(ivy-mode 1)
(setq ivy-initial-inputs-alist nil ; screw the regex
ivy-use-virtual-buffers t ; add recentf to `ivy-switch-buffer'
ivy-virtual-abbreviate 'full
ivy-wrap t
ivy-height 12
ivy-fixed-height-minibuffer t
;; ne pas quitter le minibuffer en cas de `delete-error`
ivy-on-del-error-function #'ignore
;; don't bother counting candidates
ivy-count-format ""
;; use fuzzy by default, but some searching is impossible without
;; stricter regex's
ivy-re-builders-alist '((t . ivy--regex-plus)))
(aero-leader-def
"bb" 'ivy-switch-buffer))
;; Currently disabled but preserved because I can't decide whether I want it or not. Using it means
;; the mode line doesn't jump up on every M-x but also takes some character away from Emacs.
(use-package ivy-posframe :straight t :disabled t
:after (ivy)
:config
(setq ivy-posframe-display-functions-alist
'((swiper . ivy-display-function-fallback)
(complete-symbol . ivy-posframe-display-at-point)
(t . ivy-posframe-display)))
;; Fix atrocious width jumping
(defun aero/ivy-posframe-get-size ()
"Set the ivy-posframe size according to the current frame."
(let ((height (or ivy-posframe-height (or ivy-height 10)))
(width (min (or ivy-posframe-width 200) (round (* .75 (frame-width))))))
(list :height height :width width :min-height height :min-width width)))
(setq ivy-posframe-size-function 'aero/ivy-posframe-get-size)
(ivy-posframe-mode +1))
(use-package ivy-rich :straight t
:after (counsel ivy)
:defines (ivy-rich-path-style)
:functions (ivy-rich-mode)
:config
(setq ivy-rich-path-style 'abbrev)
(setcdr (assq t ivy-format-functions-alist) #'ivy-format-function-line)
(ivy-rich-mode +1)
(ivy-rich-project-root-cache-mode +1))
(use-package all-the-icons :straight t)
(use-package all-the-icons-ivy-rich :straight t
:after (all-the-icons ivy-rich)
:functions (all-the-icons-ivy-rich-mode)
:init (all-the-icons-ivy-rich-mode +1))
(use-package swiper :straight t
:after (general counsel)
:commands (swiper counsel-grep-or-swiper swiper-thing-at-point)
:init
(aero-leader-def
"/" '(counsel-grep-or-swiper :wk "search")
"?" '(swiper-thing-at-point :wk "search thing at point"))
:config
(setq swiper-action-recenter t))
(use-package avy :straight t
:commands (avy-goto-line avy-goto-char avy-goto-word-1)
:init
(general-define-key
:states '(normal visual)
:prefix "SPC"
"jl" '(avy-goto-line :wk "jump to line")
"jc" '(avy-goto-char :wk "jump to char")
"jw" '(avy-goto-word-1 :wk "jump to word")))
(use-package ace-link :straight (:host github :repo "abo-abo/ace-link")
:after (avy)
:functions (ace-link-setup-default)
:init (ace-link-setup-default))
;;; system
(use-package undo-tree :straight t
:config
(global-undo-tree-mode +1)
;; Disable undo-in-region. It sounds like a cool feature, but
;; unfortunately the implementation is very buggy and usually causes
;; you to lose your undo history if you use it by accident.
(setq undo-tree-enable-undo-in-region nil))
(use-package winner
:after (general)
:defines winner-boring-buffers
:config
(setq winner-boring-buffers
'("*Completions*"
"*Compile-Log*"
"*inferior-lisp*"
"*Fuzzy Completions*"
"*Apropos*"
"*Help*"
"*cvs*"
"*Buffer List*"
"*Ibuffer*"
"*esh command on file*"))
(winner-mode 1)
(declare-function general-define-key "general.el")
(general-define-key
:states '(normal)
:prefix "SPC"
:non-normal-prefix "C-SPC"
"wu" 'winner-undo
"wU" 'winner-redo
"wh" 'windmove-left
"wj" 'windmove-down
"wk" 'windmove-up
"wl" 'windmove-right)
;; windmove
(global-set-key (kbd "M-h") #'windmove-left)
(global-set-key (kbd "M-j") #'windmove-down)
(global-set-key (kbd "M-k") #'windmove-up)
(global-set-key (kbd "M-l") #'windmove-right))
(use-package winum :straight t :defer 5
:after (general)
:init
(winum-mode)
:config
(aero-leader-def
"1" '(winum-select-window-1 :wk "window-1")
"2" '(winum-select-window-2 :wk "window-2")
"3" '(winum-select-window-3 :wk "window-3")
"4" '(winum-select-window-4 :wk "window-4")
"5" '(winum-select-window-5 :wk "window-5")
"6" '(winum-select-window-6 :wk "window-6")
"7" '(winum-select-window-7 :wk "window-7")
"8" '(winum-select-window-8 :wk "window-8")
"9" '(winum-select-window-9 :wk "window-9")
"wg" '(winum-select-window-by-number :wk "select window by number"))
;; collapse all those window commands to one summary
(push '(("\\(.*\\) 0" . "winum-select-window-0") . ("\\1 0..9" . "window 0..9"))
which-key-replacement-alist)
(push '((nil . "select-window-[1-9]") . t) which-key-replacement-alist))
(use-package helpful :straight t
:commands (helpful-function
helpful-variable
helpful-macro
helpful-key
helpful-callable)
:after (evil general)
:init
(general-define-key
:states 'normal
:prefix "SPC"
"hdf" 'helpful-function
"hdF" 'counsel-describe-face
"hdb" 'describe-bindings
"hdv" 'helpful-variable
"hdm" 'helpful-macro
"hdM" 'describe-mode
"hdk" 'helpful-key
"hdK" 'describe-keymap
"hdc" 'helpful-callable
"hdC" 'describe-char
"hdp" 'describe-package)
:config
(evil-define-key 'normal helpful-mode-map
"q" 'kill-this-buffer
"?" 'describe-mode))
;;; System-specifics
;; Mac needs some extra hand-holding to connect the kill-ring to the system
;; clipboard.
(when (system-is-mac)
(declare-function aero/pbcopier-select-text "aero-lib.el")
(declare-function aero/pbcopier-selection-value "aero-lib.el")
(setq interprogram-cut-function #'aero/pbcopier-select-text)
(setq interprogram-paste-function #'aero/pbcopier-selection-value)
(setq-default ns-use-native-fullscreen nil)
(if (executable-find "gls")
(progn
(setq insert-directory-program "gls")
(setq dired-listing-switches "-lFaGh1v --group-directories-first"))
(setq dired-listing-switches "-ahlF")))
(when (system-is-linux)
(setq select-enable-clipboard t
interprogram-paste-function #'gui-selection-value
x-gtk-use-system-tooltips t
dired-listing-switches "-lFaGh1v --group-directories-first"))
;; TTY also needs some clipboard help. Only works in certain term emulators,
;; Alacritty is my preferred.
(unless (display-graphic-p)
(use-package xclip :straight t
:config (xclip-mode +1)))
;; File navigation
(use-package tramp
:straight (tramp :host nil :repo "git://git.savannah.gnu.org/tramp.git")
:defer t
:functions tramp-cleanup-all-connection
:config
(setq tramp-auto-save-directory "~/.cache/emacs/backups"
tramp-persistency-file-name "~/.config/emacs/data/tramp"
tramp-use-ssh-controlmaster-options nil ; use system settings instead
tramp-default-method "rsync"
tramp-terminal-type "tramp")
;; push projectile in the right direction
(defadvice projectile-project-root (around ignore-remote first activate)
(unless (file-remote-p default-directory) ad-do-it)))
(use-package ranger :straight t
:commands (deer)
:after general
:init
(setq ranger-show-hidden t
find-directory-functions 'deer)
(general-define-key
:states 'normal
:prefix "SPC"
"fd" 'deer))
;;; General crap
(use-package pomp
:straight (:host gitlab :repo "thornjad/pomp")
:after (general evil)
:commands (pomp)
:init
(evil-set-initial-state 'pomp-mode 'emacs)
(global-set-key (kbd "<f12>") 'pomp)
(general-define-key
:states 'normal
:prefix "SPC"
"ap" 'pomp))
(use-package editorconfig :straight t :defer 5
:functions (editorconfig-mode)
:config (editorconfig-mode +1))
;; Ensure emacsclient frames open with focus
(add-hook 'server-switch-hook (lambda () (select-frame-set-input-focus (selected-frame))))
(provide 'aero-prelude)
| 25197 | ;; -*- lexical-binding: t -*-
;;
;; Aero core prelude layer
;;
;; Copyright (c) 2018-2021 <NAME>
;;
;; This file is not part of GNU Emacs
;;
;; Permission to use, copy, modify, and/or distribute this software for any
;; purpose with or without fee is hereby granted, provided that the above
;; copyright notice and this permission notice appear in all copies.
;;
;; The software is provided "as is" and the author disclaims all warranties with
;; regard to this software including all implied warranties of merchantability
;; and fitness. In no event shall the author be liable for any special, direct,
;; indirect, or consequential damages or any damages whatsoever resulting from
;; loss of use, data or profits, whether in an action of contract, negligence or
;; other tortious action, arising out of or in connection with the use or
;; performance of this software.
;;
(require 'cl-lib)
(require 'straight)
(require 'use-package)
(require 'aero-lib)
;;; Code:
;;; Set up core packages
(use-package gnu-elpa-keyring-update :straight t)
(use-package exec-path-from-shell :straight t :defer 1
:config
(when (or (window-system) (daemonp))
(dolist (var '("SSH_AUTH_SOCK" "SSH_AGENT_PID" "GPG_AGENT_INFO" "LANG" "LC_CTYPE" "NIX_SSL_CERT_FILE" "NIX_PATH"))
(add-to-list 'exec-path-from-shell-variables var))
(exec-path-from-shell-initialize)))
(use-package no-littering :defer 5
:after recentf
:straight (:host github :repo "emacscollective/no-littering")
:defines (no-littering-var-directory
no-littering-etc-directory)
:config
(add-to-list 'recentf-exclude no-littering-var-directory)
(add-to-list 'recentf-exclude no-littering-etc-directory))
;;; get ready to patch at any time
(use-package el-patch :straight t
:init (setq el-patch-enable-use-package-integration t))
;; Only needed at compile time
(eval-when-compile
(require 'el-patch))
;;; used in several places
(use-package ripgrep :straight t :defer 3)
;;; the general is here
(use-package general :straight t
:functions (general-define-key)
:init
(setq-default general-override-states
'(insert hybrid normal visual motion operator replace))
:config
(general-create-definer aero-leader-def
:states '(normal visual emacs motion)
:prefix "SPC"
:non-normal-prefix "C-SPC")
(general-create-definer aero-mode-leader-def
:states '(normal visual emacs motion)
:prefix ",")
(general-define-key
:states '(normal visual motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil)
;; Main configuration
(general-def
;; Emacs chose ^? for the help system for some despicable reason. Fuck that.
(kbd "C-h") 'delete-backward-char
(kbd "C-w") 'aero/smarter-backward-kill-word
(kbd "C-TAB") 'insert-tab
(kbd "M-TAB") 'aero/alternate-buffer)
(general-define-key
:states 'normal
:prefix "SPC"
"fW" 'evil-write-all
"w/" '(evil-window-vsplit :wk "split vertical")
"w-" '(evil-window-split :wk "split horizontal")
"cm" 'evil-make)
(global-set-key [remap keyboard-quit] #'aero/keyboard-quit-context)
;; mode-specific overrides
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix ","
"" nil)
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil
;; independent keys
"TAB" '(aero/alternate-buffer :wk "alternate buffer")
(kbd "ESC") 'keyboard-quit
(kbd "C-g") 'keyboard-quit
"'" 'eshell
"\"" '(aero/eshell-new :wk "eshell-new")
":" 'eval-expression
";" 'comment-or-uncomment-region
"!" 'shell-command
"=" 'quick-calc
;; NOTE deprecated, use the top-level "," prefix instead
"," '(:ignore t :wk "mode") ; reserved for mode-specific
"U" 'universal-argument
"z" 'repeat
"q" '(:ignore t :wk "quoted insert")
"qq" 'quoted-insert
"ql" 'insert-lambda
"f" '(:ignore t :wk "files")
"fw" '(save-buffer :wk "write buffer")
"fW" '(aero/async-write-buffer :wk "async write buffer (experimental)")
"fC" '(:ignore t :wk "convert")
"fCd" '(aero/unix2dos :wk "unix2dos")
"fCu" '(aero/dos2unix :wk "dos2unix")
"fD" '(aero/delete-this-file :wk "delete this file")
"fE" '(aero/sudo-edit :wk "sudo edit")
"fR" '(aero/rename-this-file-and-buffer :wk "rename this file")
"fx" '(aero/xdg-open :wk "xdg-open")
"fo" '(:ignore t :wk "open special files")
"fot" '(:ignore t :wk "thornlog")
"fott" '(aero/thornlog-dir :wk "thornlog all")
"fotl" '(aero/thornlog-today :wk "thornlog log")
"fotd" '(aero/thornlog-todo :wk "thornlog todo")
"foP" 'aero/open-emacs-problems
"fof" 'aero/open-local-init
"o" '(:ignore t :wk "org")
"oa" 'org-agenda
"ot" 'aero/task
"oe" '(:ignore t :wk "org edit")
"oet" '(:ignore t :wk "org table")
"oets" 'org-table-sort-lines
"h" '(:ignore t :wk "help/manual")
"hM" 'woman
"hm" 'man
"hi" 'info
"hI" 'info-apropos
"hd" '(:ignore t :wk "describe")
"hw" '(:ignore t :wk "which-key")
"hwm" '(which-key-show-major-mode :wk "major mode map")
"b" '(:ignore t :wk "buffers")
"bn" 'next-buffer
"bp" 'previous-buffer
"bl" 'ibuffer
"bL" 'list-buffers
"bm" 'switch-to-messages-buffer
"br" '(aero/reopen-file-at-buffer :wk "reopen file")
"bs" 'switch-to-scratch-buffer
"bS" 'switch-to-new-scratch-buffer
"bd" 'kill-this-buffer
"bx" 'kill-buffer-and-window
"bw" '(whitespace-mode :wk "whitespace")
"bt" '(:ignore t :wk "tabify")
"btu" 'untabify-buffer
"btt" 'tabify-buffer
"bi" 'indent-buffer
"bP" 'aero/toggle-prettify-this-buffer
"E" '(:ignore t :wk "emacs")
"Et" 'counsel-load-theme
"Ea" 'aero/apologize-to-emacs
"Ed" '(:ignore t :wk "debug")
"Ede" 'toggle-debug-on-error
"Edq" 'toggle-debug-on-quit
"a" '(:ignore t :wk "applications")
"ad" 'counsel-dired
"ag" '(:ignore t :wk "games")
"agt" 'tetris
"agd" 'dunnet
"c" '(:ignore t :wk "compile")
"cc" 'compile
"cC" '(aero/byte-recompile-file-at-buffer :wk "byte recompile file at buffer")
"ck" 'kill-compilation
"cr" 'recompile
"cR" 'byte-recompile-file
"ce" '(:ignore t :wk "elisp")
"cei" '(ielm :wk "ielm repl")
"cer" 'eval-region
"ceb" 'eval-buffer
"ced" 'eval-defun
"cec" '(:ignore t :wk "compile")
"cecb" '(aero/native-compile-file-at-buffer :wk "file at buffer")
"ceB" '(:ignore t :wk "byte compile")
"ceBb" '(aero/byte-compile-file-at-buffer :wk "file at buffer")
"ceBr" '(aero/byte-recompile-file-at-buffer :wk "file at buffer (recompile)")
"ceBf" '(byte-compile-file :wk "other file")
"ceBF" '(async-byte-compile-file :wk "other file async")
"ceBd" '(byte-recompile-directory :wk "directory")
"e" '(:ignore t :wk "errors")
"en" 'next-error
"ep" 'previous-error
"F" '(:ignore t :wk "frame")
"Fd" 'delete-frame
"Fo" 'other-frame
"FF" 'find-file-other-frame
"Fn" 'make-frame
"Fm" 'toggle-frame-maximized
"Ff" 'toggle-frame-fullscreen
"g" '(:ignore t :wk "git")
"gf" '(:ignore t :wk "files")
"l" '(:ignore t :wk "lsp")
"L" '(:ignore t :wk "local")
"j" '(:ignore t :wk "jump")
"s" '(:ignore t :wk "sexp")
"m" '(:ignore t :wk "mode")
"d" '(:ignore t :wk "debug")
"p" '(:ignore t :wk "project")
"pr" '(xref-find-definitions :wk "find ref")
"P" '(:ignore t :wk "packages/perspective")
"PP" '(:ignore t :wk "packages")
"PPp" 'straight-pull-package-and-deps
"PPF" 'straight-fetch-all
"PPP" 'straight-pull-all
"PPg" 'straight-get-recipe
"PPC" 'straight-check-all
"PPr" 'straight-rebuild-package
"PPR" 'straight-rebuild-all
"PPx" 'straight-prune-build
"u" 'undo-tree-visualize
"S" '(:ignore t :wk "shell/sql")
"Se" 'eshell
"SE" '(:ignore t :wk "eshell")
"St" '(:ignore t :wk "term")
"T" '(:ignore t :wk "tab")
"TT" 'tab-bar-mode
"Tj" 'tab-next
"Tk" 'tab-previous
"Tc" '(tab-new :wk "create tab")
"TL" 'tab-list
"TL" 'tab-last
"T TAB" 'tab-recent
"T," 'tab-rename
"Ts" '(tab-duplicate :wk "tab duplicate split")
"Td" 'tab-close
"Tu" 'tab-undo
"Tg" '(tab-select :wk "tab go")
"Tb" 'switch-to-buffer-other-tab
"Tf" 'find-file-other-tab
"w" '(:ignore t :wk "window/web")
"ww" 'eww
"wp" 'browse-url-at-point
"ws" '(eww-search-words :which-key "web search")
"w=" 'balance-windows
"wB" '(aero/switch-to-minibuffer-window :wk "switch to minibuffer")
"wd" 'delete-window
"wF" 'make-frame
"w{" 'shrink-window
"w}" 'enlarge-window
"wm" 'maximize-window
"wi" 'minimize-window
"wo" 'browse-url-xdg-open
"wb" '(:ignore t :wk "browse")
"wbm" 'eww-list-bookmarks
"wbb" 'eww-list-buffers
"wbh" 'eww-list-histories
"wL" '(:ignore t :wk "layout")
"wL2" 'aero/layout-two-columns
"wL3" 'aero/layout-three-columns
"t" '(:ignore t :wk "tabs/text")
"tf" 'fill-paragraph
"tU" 'upcase-dwim
"tD" 'downcase-dwim
"ts" 'sort-lines
"tn" '(:ignore t :wk "number")
"tni" 'increment-number-at-point
"tnd" 'decrement-number-at-point))
(use-package which-key :straight t
:defines which-key-mode
:config
(which-key-mode)
(setq which-key-special-keys '("SPC" "TAB" "RET" "ESC" "DEL")))
;; we descend to hell
(use-package evil :straight t
:init
(setq evil-want-keybinding nil ; handled by evil-collection
;; to change undo-system without restart, use SPC-: `evil-set-undo-system'
evil-undo-system 'undo-tree
evil-want-fine-undo t
evil-want-C-i-jump nil
evil-want-C-u-scroll t)
:config
(use-package evil-collection
:config (evil-collection-init))
(define-key evil-motion-state-map " " nil)
;; default states
(setq evil-default-state 'normal)
(evil-set-initial-state 'dired-mode 'emacs)
(evil-set-initial-state 'message-mode 'motion)
;; Make movement keys work like they should by remapping next to next-visual, etc.
(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
;; Ensure horizontal movement doesn't cross lines
(setq-default evil-cross-lines nil)
(defun aero/evil-shift-right ()
(interactive)
(evil-shift-right evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(defun aero/evil-shift-left ()
(interactive)
(evil-shift-left evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(evil-define-key 'visual global-map (kbd ">") 'aero/evil-shift-right)
(evil-define-key 'visual global-map (kbd "<") 'aero/evil-shift-left)
;; :q should kill the current buffer rather than quitting emacs entirely
(evil-ex-define-cmd "q" 'kill-this-buffer)
;; Need to type out :quit to close emacs
(evil-ex-define-cmd "quit" 'evil-quit)
(evil-define-key '(normal visual motion) global-map
(kbd "C-e") #'evil-backward-word-end)
(evil-define-key '(normal visual motion) global-map
(kbd "C-M-e") #'evil-backward-WORD-end)
(evil-define-key '(insert) global-map
(kbd "C-y") #'evil-paste-after)
(evil-define-key '(insert) global-map
(kbd "C-S-y") #'evil-paste-before)
(evil-define-key 'normal 'global
;; Run macro in register q
"Q" "@q")
(evil-define-key 'visual 'global
;; run macro in register q on region
"Q" (kbd ":norm @q RET")
;; repeat on region
"." (kbd ":norm . RET"))
(evil-mode 1))
;; Doesn't do anything for GUI, so don't bother
(unless (display-graphic-p)
(use-package evil-terminal-cursor-changer
:after evil
:functions (evil-terminal-cursor-changer-activate)
:config (evil-terminal-cursor-changer-activate)))
(use-package evil-matchit :straight t :defer 5
:after evil
:defines global-evil-matchit-mode
:config (global-evil-matchit-mode 1))
(use-package evil-visualstar :straight t :defer 5
:after evil
:defines global-evil-visualstar-mode
:config
(global-evil-visualstar-mode t))
;; abo-abo!
(use-package counsel :straight t
:after general
:init/el-patch ; remove bindings which we use `helpful' for
(defvar counsel-mode-map
(let ((map (make-sparse-keymap)))
(dolist (binding
'((execute-extended-command . counsel-M-x)
(describe-bindings . counsel-descbinds)
(el-patch-remove
(describe-function . counsel-describe-function)
(describe-variable . counsel-describe-variable))
(apropos-command . counsel-apropos)
(describe-face . counsel-describe-face)
(list-faces-display . counsel-faces)
(find-file . counsel-find-file)
(find-library . counsel-find-library)
(imenu . counsel-imenu)
(load-library . counsel-load-library)
(load-theme . counsel-load-theme)
(yank-pop . counsel-yank-pop)
(info-lookup-symbol . counsel-info-lookup-symbol)
(pop-to-mark-command . counsel-mark-ring)
(bookmark-jump . counsel-bookmark)))
(define-key map (vector 'remap (car binding)) (cdr binding)))
map)
(el-patch-concat
"Map for `counsel-mode'.
Remaps built-in functions to counsel replacements."
(el-patch-add
"\n\nBindings that are remapped by `helpful' have been removed.")))
(defcustom counsel-mode-override-describe-bindings nil
"Whether to override `describe-bindings' when `counsel-mode' is active."
:type 'boolean
:group 'counsel)
(define-minor-mode counsel-mode
"Toggle Counsel mode on or off.
Turn Counsel mode on if ARG is positive, off otherwise. Counsel mode remaps
built-in emacs functions that have counsel replacements.
Local bindings (`counsel-mode-map'):
\\{counsel-mode-map}"
:global t
:keymap counsel-mode-map
:group 'counsel
(if counsel-mode
(progn
(when (and (fboundp 'advice-add)
counsel-mode-override-describe-bindings)
(advice-add #'describe-bindings :override #'counsel-descbinds))
(define-key minibuffer-local-map (kbd "C-r")
'counsel-minibuffer-history))
(when (fboundp 'advice-remove)
(advice-remove #'describe-bindings #'counsel-descbinds))))
:config
(setq counsel-find-file-ignore-regexp
(concat "\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)"
"\\|\\.x\\'\\|\\.d\\'\\|\\.o\\'"
"\\|\\.aux\\'"))
(defun aero/counsel-unicode-char-after ()
"Like `counsel-unicode-char', but insert after point"
(interactive)
(save-excursion
(right-char)
(counsel-unicode-char)))
(setq counsel-grep-base-command "rg -i -M 120 --no-heading --line-number --color never '%s' %s"
counsel-git-cmd "rg --files"
counsel-rg-base-command "rg --with-filename --smart-case --no-heading --line-number --color never %s")
(aero-leader-def
"SPC" 'counsel-M-x
"ff" 'counsel-find-file
"fl" 'counsel-locate
"fr" 'counsel-recentf
"?" 'counsel-rg
"gg" '(counsel-git-grep :wk "git grep")
"gff" '(counsel-git :wk "find git file")
"ry" '(counsel-yank-pop :wk "search kill ring")
"hda" '(counsel-apropos :wk "apropos")
"qu" '(aero/counsel-unicode-char-after :wk "unicode char")
"qU" 'counsel-unicode-char))
(use-package recentf :defer t
:defines (recentf-mode)
:config
(defvar aero-etc-dir)
(setq recentf-save-file (expand-file-name "recentf" aero-etc-dir)
recentf-max-saved-items 500
;; never cleanup, this will get rid of tramp files
recentf-auto-cleanup 'never)
(recentf-mode 1))
(use-package ivy :straight t
:after general
:functions ivy-mode
:config
(use-package flx :straight t)
(ivy-mode 1)
(setq ivy-initial-inputs-alist nil ; screw the regex
ivy-use-virtual-buffers t ; add recentf to `ivy-switch-buffer'
ivy-virtual-abbreviate 'full
ivy-wrap t
ivy-height 12
ivy-fixed-height-minibuffer t
;; ne pas quitter le minibuffer en cas de `delete-error`
ivy-on-del-error-function #'ignore
;; don't bother counting candidates
ivy-count-format ""
;; use fuzzy by default, but some searching is impossible without
;; stricter regex's
ivy-re-builders-alist '((t . ivy--regex-plus)))
(aero-leader-def
"bb" 'ivy-switch-buffer))
;; Currently disabled but preserved because I can't decide whether I want it or not. Using it means
;; the mode line doesn't jump up on every M-x but also takes some character away from Emacs.
(use-package ivy-posframe :straight t :disabled t
:after (ivy)
:config
(setq ivy-posframe-display-functions-alist
'((swiper . ivy-display-function-fallback)
(complete-symbol . ivy-posframe-display-at-point)
(t . ivy-posframe-display)))
;; Fix atrocious width jumping
(defun aero/ivy-posframe-get-size ()
"Set the ivy-posframe size according to the current frame."
(let ((height (or ivy-posframe-height (or ivy-height 10)))
(width (min (or ivy-posframe-width 200) (round (* .75 (frame-width))))))
(list :height height :width width :min-height height :min-width width)))
(setq ivy-posframe-size-function 'aero/ivy-posframe-get-size)
(ivy-posframe-mode +1))
(use-package ivy-rich :straight t
:after (counsel ivy)
:defines (ivy-rich-path-style)
:functions (ivy-rich-mode)
:config
(setq ivy-rich-path-style 'abbrev)
(setcdr (assq t ivy-format-functions-alist) #'ivy-format-function-line)
(ivy-rich-mode +1)
(ivy-rich-project-root-cache-mode +1))
(use-package all-the-icons :straight t)
(use-package all-the-icons-ivy-rich :straight t
:after (all-the-icons ivy-rich)
:functions (all-the-icons-ivy-rich-mode)
:init (all-the-icons-ivy-rich-mode +1))
(use-package swiper :straight t
:after (general counsel)
:commands (swiper counsel-grep-or-swiper swiper-thing-at-point)
:init
(aero-leader-def
"/" '(counsel-grep-or-swiper :wk "search")
"?" '(swiper-thing-at-point :wk "search thing at point"))
:config
(setq swiper-action-recenter t))
(use-package avy :straight t
:commands (avy-goto-line avy-goto-char avy-goto-word-1)
:init
(general-define-key
:states '(normal visual)
:prefix "SPC"
"jl" '(avy-goto-line :wk "jump to line")
"jc" '(avy-goto-char :wk "jump to char")
"jw" '(avy-goto-word-1 :wk "jump to word")))
(use-package ace-link :straight (:host github :repo "abo-abo/ace-link")
:after (avy)
:functions (ace-link-setup-default)
:init (ace-link-setup-default))
;;; system
(use-package undo-tree :straight t
:config
(global-undo-tree-mode +1)
;; Disable undo-in-region. It sounds like a cool feature, but
;; unfortunately the implementation is very buggy and usually causes
;; you to lose your undo history if you use it by accident.
(setq undo-tree-enable-undo-in-region nil))
(use-package winner
:after (general)
:defines winner-boring-buffers
:config
(setq winner-boring-buffers
'("*Completions*"
"*Compile-Log*"
"*inferior-lisp*"
"*Fuzzy Completions*"
"*Apropos*"
"*Help*"
"*cvs*"
"*Buffer List*"
"*Ibuffer*"
"*esh command on file*"))
(winner-mode 1)
(declare-function general-define-key "general.el")
(general-define-key
:states '(normal)
:prefix "SPC"
:non-normal-prefix "C-SPC"
"wu" 'winner-undo
"wU" 'winner-redo
"wh" 'windmove-left
"wj" 'windmove-down
"wk" 'windmove-up
"wl" 'windmove-right)
;; windmove
(global-set-key (kbd "M-h") #'windmove-left)
(global-set-key (kbd "M-j") #'windmove-down)
(global-set-key (kbd "M-k") #'windmove-up)
(global-set-key (kbd "M-l") #'windmove-right))
(use-package winum :straight t :defer 5
:after (general)
:init
(winum-mode)
:config
(aero-leader-def
"1" '(winum-select-window-1 :wk "window-1")
"2" '(winum-select-window-2 :wk "window-2")
"3" '(winum-select-window-3 :wk "window-3")
"4" '(winum-select-window-4 :wk "window-4")
"5" '(winum-select-window-5 :wk "window-5")
"6" '(winum-select-window-6 :wk "window-6")
"7" '(winum-select-window-7 :wk "window-7")
"8" '(winum-select-window-8 :wk "window-8")
"9" '(winum-select-window-9 :wk "window-9")
"wg" '(winum-select-window-by-number :wk "select window by number"))
;; collapse all those window commands to one summary
(push '(("\\(.*\\) 0" . "winum-select-window-0") . ("\\1 0..9" . "window 0..9"))
which-key-replacement-alist)
(push '((nil . "select-window-[1-9]") . t) which-key-replacement-alist))
(use-package helpful :straight t
:commands (helpful-function
helpful-variable
helpful-macro
helpful-key
helpful-callable)
:after (evil general)
:init
(general-define-key
:states 'normal
:prefix "SPC"
"hdf" 'helpful-function
"hdF" 'counsel-describe-face
"hdb" 'describe-bindings
"hdv" 'helpful-variable
"hdm" 'helpful-macro
"hdM" 'describe-mode
"hdk" 'helpful-key
"hdK" 'describe-keymap
"hdc" 'helpful-callable
"hdC" 'describe-char
"hdp" 'describe-package)
:config
(evil-define-key 'normal helpful-mode-map
"q" 'kill-this-buffer
"?" 'describe-mode))
;;; System-specifics
;; Mac needs some extra hand-holding to connect the kill-ring to the system
;; clipboard.
(when (system-is-mac)
(declare-function aero/pbcopier-select-text "aero-lib.el")
(declare-function aero/pbcopier-selection-value "aero-lib.el")
(setq interprogram-cut-function #'aero/pbcopier-select-text)
(setq interprogram-paste-function #'aero/pbcopier-selection-value)
(setq-default ns-use-native-fullscreen nil)
(if (executable-find "gls")
(progn
(setq insert-directory-program "gls")
(setq dired-listing-switches "-lFaGh1v --group-directories-first"))
(setq dired-listing-switches "-ahlF")))
(when (system-is-linux)
(setq select-enable-clipboard t
interprogram-paste-function #'gui-selection-value
x-gtk-use-system-tooltips t
dired-listing-switches "-lFaGh1v --group-directories-first"))
;; TTY also needs some clipboard help. Only works in certain term emulators,
;; Alacritty is my preferred.
(unless (display-graphic-p)
(use-package xclip :straight t
:config (xclip-mode +1)))
;; File navigation
(use-package tramp
:straight (tramp :host nil :repo "git://git.savannah.gnu.org/tramp.git")
:defer t
:functions tramp-cleanup-all-connection
:config
(setq tramp-auto-save-directory "~/.cache/emacs/backups"
tramp-persistency-file-name "~/.config/emacs/data/tramp"
tramp-use-ssh-controlmaster-options nil ; use system settings instead
tramp-default-method "rsync"
tramp-terminal-type "tramp")
;; push projectile in the right direction
(defadvice projectile-project-root (around ignore-remote first activate)
(unless (file-remote-p default-directory) ad-do-it)))
(use-package ranger :straight t
:commands (deer)
:after general
:init
(setq ranger-show-hidden t
find-directory-functions 'deer)
(general-define-key
:states 'normal
:prefix "SPC"
"fd" 'deer))
;;; General crap
(use-package pomp
:straight (:host gitlab :repo "thornjad/pomp")
:after (general evil)
:commands (pomp)
:init
(evil-set-initial-state 'pomp-mode 'emacs)
(global-set-key (kbd "<f12>") 'pomp)
(general-define-key
:states 'normal
:prefix "SPC"
"ap" 'pomp))
(use-package editorconfig :straight t :defer 5
:functions (editorconfig-mode)
:config (editorconfig-mode +1))
;; Ensure emacsclient frames open with focus
(add-hook 'server-switch-hook (lambda () (select-frame-set-input-focus (selected-frame))))
(provide 'aero-prelude)
| true | ;; -*- lexical-binding: t -*-
;;
;; Aero core prelude layer
;;
;; Copyright (c) 2018-2021 PI:NAME:<NAME>END_PI
;;
;; This file is not part of GNU Emacs
;;
;; Permission to use, copy, modify, and/or distribute this software for any
;; purpose with or without fee is hereby granted, provided that the above
;; copyright notice and this permission notice appear in all copies.
;;
;; The software is provided "as is" and the author disclaims all warranties with
;; regard to this software including all implied warranties of merchantability
;; and fitness. In no event shall the author be liable for any special, direct,
;; indirect, or consequential damages or any damages whatsoever resulting from
;; loss of use, data or profits, whether in an action of contract, negligence or
;; other tortious action, arising out of or in connection with the use or
;; performance of this software.
;;
(require 'cl-lib)
(require 'straight)
(require 'use-package)
(require 'aero-lib)
;;; Code:
;;; Set up core packages
(use-package gnu-elpa-keyring-update :straight t)
(use-package exec-path-from-shell :straight t :defer 1
:config
(when (or (window-system) (daemonp))
(dolist (var '("SSH_AUTH_SOCK" "SSH_AGENT_PID" "GPG_AGENT_INFO" "LANG" "LC_CTYPE" "NIX_SSL_CERT_FILE" "NIX_PATH"))
(add-to-list 'exec-path-from-shell-variables var))
(exec-path-from-shell-initialize)))
(use-package no-littering :defer 5
:after recentf
:straight (:host github :repo "emacscollective/no-littering")
:defines (no-littering-var-directory
no-littering-etc-directory)
:config
(add-to-list 'recentf-exclude no-littering-var-directory)
(add-to-list 'recentf-exclude no-littering-etc-directory))
;;; get ready to patch at any time
(use-package el-patch :straight t
:init (setq el-patch-enable-use-package-integration t))
;; Only needed at compile time
(eval-when-compile
(require 'el-patch))
;;; used in several places
(use-package ripgrep :straight t :defer 3)
;;; the general is here
(use-package general :straight t
:functions (general-define-key)
:init
(setq-default general-override-states
'(insert hybrid normal visual motion operator replace))
:config
(general-create-definer aero-leader-def
:states '(normal visual emacs motion)
:prefix "SPC"
:non-normal-prefix "C-SPC")
(general-create-definer aero-mode-leader-def
:states '(normal visual emacs motion)
:prefix ",")
(general-define-key
:states '(normal visual motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil)
;; Main configuration
(general-def
;; Emacs chose ^? for the help system for some despicable reason. Fuck that.
(kbd "C-h") 'delete-backward-char
(kbd "C-w") 'aero/smarter-backward-kill-word
(kbd "C-TAB") 'insert-tab
(kbd "M-TAB") 'aero/alternate-buffer)
(general-define-key
:states 'normal
:prefix "SPC"
"fW" 'evil-write-all
"w/" '(evil-window-vsplit :wk "split vertical")
"w-" '(evil-window-split :wk "split horizontal")
"cm" 'evil-make)
(global-set-key [remap keyboard-quit] #'aero/keyboard-quit-context)
;; mode-specific overrides
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix ","
"" nil)
(general-define-key
:states '(normal insert motion)
:keymaps 'override
:prefix "SPC"
:non-normal-prefix "C-SPC"
"" nil
;; independent keys
"TAB" '(aero/alternate-buffer :wk "alternate buffer")
(kbd "ESC") 'keyboard-quit
(kbd "C-g") 'keyboard-quit
"'" 'eshell
"\"" '(aero/eshell-new :wk "eshell-new")
":" 'eval-expression
";" 'comment-or-uncomment-region
"!" 'shell-command
"=" 'quick-calc
;; NOTE deprecated, use the top-level "," prefix instead
"," '(:ignore t :wk "mode") ; reserved for mode-specific
"U" 'universal-argument
"z" 'repeat
"q" '(:ignore t :wk "quoted insert")
"qq" 'quoted-insert
"ql" 'insert-lambda
"f" '(:ignore t :wk "files")
"fw" '(save-buffer :wk "write buffer")
"fW" '(aero/async-write-buffer :wk "async write buffer (experimental)")
"fC" '(:ignore t :wk "convert")
"fCd" '(aero/unix2dos :wk "unix2dos")
"fCu" '(aero/dos2unix :wk "dos2unix")
"fD" '(aero/delete-this-file :wk "delete this file")
"fE" '(aero/sudo-edit :wk "sudo edit")
"fR" '(aero/rename-this-file-and-buffer :wk "rename this file")
"fx" '(aero/xdg-open :wk "xdg-open")
"fo" '(:ignore t :wk "open special files")
"fot" '(:ignore t :wk "thornlog")
"fott" '(aero/thornlog-dir :wk "thornlog all")
"fotl" '(aero/thornlog-today :wk "thornlog log")
"fotd" '(aero/thornlog-todo :wk "thornlog todo")
"foP" 'aero/open-emacs-problems
"fof" 'aero/open-local-init
"o" '(:ignore t :wk "org")
"oa" 'org-agenda
"ot" 'aero/task
"oe" '(:ignore t :wk "org edit")
"oet" '(:ignore t :wk "org table")
"oets" 'org-table-sort-lines
"h" '(:ignore t :wk "help/manual")
"hM" 'woman
"hm" 'man
"hi" 'info
"hI" 'info-apropos
"hd" '(:ignore t :wk "describe")
"hw" '(:ignore t :wk "which-key")
"hwm" '(which-key-show-major-mode :wk "major mode map")
"b" '(:ignore t :wk "buffers")
"bn" 'next-buffer
"bp" 'previous-buffer
"bl" 'ibuffer
"bL" 'list-buffers
"bm" 'switch-to-messages-buffer
"br" '(aero/reopen-file-at-buffer :wk "reopen file")
"bs" 'switch-to-scratch-buffer
"bS" 'switch-to-new-scratch-buffer
"bd" 'kill-this-buffer
"bx" 'kill-buffer-and-window
"bw" '(whitespace-mode :wk "whitespace")
"bt" '(:ignore t :wk "tabify")
"btu" 'untabify-buffer
"btt" 'tabify-buffer
"bi" 'indent-buffer
"bP" 'aero/toggle-prettify-this-buffer
"E" '(:ignore t :wk "emacs")
"Et" 'counsel-load-theme
"Ea" 'aero/apologize-to-emacs
"Ed" '(:ignore t :wk "debug")
"Ede" 'toggle-debug-on-error
"Edq" 'toggle-debug-on-quit
"a" '(:ignore t :wk "applications")
"ad" 'counsel-dired
"ag" '(:ignore t :wk "games")
"agt" 'tetris
"agd" 'dunnet
"c" '(:ignore t :wk "compile")
"cc" 'compile
"cC" '(aero/byte-recompile-file-at-buffer :wk "byte recompile file at buffer")
"ck" 'kill-compilation
"cr" 'recompile
"cR" 'byte-recompile-file
"ce" '(:ignore t :wk "elisp")
"cei" '(ielm :wk "ielm repl")
"cer" 'eval-region
"ceb" 'eval-buffer
"ced" 'eval-defun
"cec" '(:ignore t :wk "compile")
"cecb" '(aero/native-compile-file-at-buffer :wk "file at buffer")
"ceB" '(:ignore t :wk "byte compile")
"ceBb" '(aero/byte-compile-file-at-buffer :wk "file at buffer")
"ceBr" '(aero/byte-recompile-file-at-buffer :wk "file at buffer (recompile)")
"ceBf" '(byte-compile-file :wk "other file")
"ceBF" '(async-byte-compile-file :wk "other file async")
"ceBd" '(byte-recompile-directory :wk "directory")
"e" '(:ignore t :wk "errors")
"en" 'next-error
"ep" 'previous-error
"F" '(:ignore t :wk "frame")
"Fd" 'delete-frame
"Fo" 'other-frame
"FF" 'find-file-other-frame
"Fn" 'make-frame
"Fm" 'toggle-frame-maximized
"Ff" 'toggle-frame-fullscreen
"g" '(:ignore t :wk "git")
"gf" '(:ignore t :wk "files")
"l" '(:ignore t :wk "lsp")
"L" '(:ignore t :wk "local")
"j" '(:ignore t :wk "jump")
"s" '(:ignore t :wk "sexp")
"m" '(:ignore t :wk "mode")
"d" '(:ignore t :wk "debug")
"p" '(:ignore t :wk "project")
"pr" '(xref-find-definitions :wk "find ref")
"P" '(:ignore t :wk "packages/perspective")
"PP" '(:ignore t :wk "packages")
"PPp" 'straight-pull-package-and-deps
"PPF" 'straight-fetch-all
"PPP" 'straight-pull-all
"PPg" 'straight-get-recipe
"PPC" 'straight-check-all
"PPr" 'straight-rebuild-package
"PPR" 'straight-rebuild-all
"PPx" 'straight-prune-build
"u" 'undo-tree-visualize
"S" '(:ignore t :wk "shell/sql")
"Se" 'eshell
"SE" '(:ignore t :wk "eshell")
"St" '(:ignore t :wk "term")
"T" '(:ignore t :wk "tab")
"TT" 'tab-bar-mode
"Tj" 'tab-next
"Tk" 'tab-previous
"Tc" '(tab-new :wk "create tab")
"TL" 'tab-list
"TL" 'tab-last
"T TAB" 'tab-recent
"T," 'tab-rename
"Ts" '(tab-duplicate :wk "tab duplicate split")
"Td" 'tab-close
"Tu" 'tab-undo
"Tg" '(tab-select :wk "tab go")
"Tb" 'switch-to-buffer-other-tab
"Tf" 'find-file-other-tab
"w" '(:ignore t :wk "window/web")
"ww" 'eww
"wp" 'browse-url-at-point
"ws" '(eww-search-words :which-key "web search")
"w=" 'balance-windows
"wB" '(aero/switch-to-minibuffer-window :wk "switch to minibuffer")
"wd" 'delete-window
"wF" 'make-frame
"w{" 'shrink-window
"w}" 'enlarge-window
"wm" 'maximize-window
"wi" 'minimize-window
"wo" 'browse-url-xdg-open
"wb" '(:ignore t :wk "browse")
"wbm" 'eww-list-bookmarks
"wbb" 'eww-list-buffers
"wbh" 'eww-list-histories
"wL" '(:ignore t :wk "layout")
"wL2" 'aero/layout-two-columns
"wL3" 'aero/layout-three-columns
"t" '(:ignore t :wk "tabs/text")
"tf" 'fill-paragraph
"tU" 'upcase-dwim
"tD" 'downcase-dwim
"ts" 'sort-lines
"tn" '(:ignore t :wk "number")
"tni" 'increment-number-at-point
"tnd" 'decrement-number-at-point))
(use-package which-key :straight t
:defines which-key-mode
:config
(which-key-mode)
(setq which-key-special-keys '("SPC" "TAB" "RET" "ESC" "DEL")))
;; we descend to hell
(use-package evil :straight t
:init
(setq evil-want-keybinding nil ; handled by evil-collection
;; to change undo-system without restart, use SPC-: `evil-set-undo-system'
evil-undo-system 'undo-tree
evil-want-fine-undo t
evil-want-C-i-jump nil
evil-want-C-u-scroll t)
:config
(use-package evil-collection
:config (evil-collection-init))
(define-key evil-motion-state-map " " nil)
;; default states
(setq evil-default-state 'normal)
(evil-set-initial-state 'dired-mode 'emacs)
(evil-set-initial-state 'message-mode 'motion)
;; Make movement keys work like they should by remapping next to next-visual, etc.
(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-motion-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
;; Ensure horizontal movement doesn't cross lines
(setq-default evil-cross-lines nil)
(defun aero/evil-shift-right ()
(interactive)
(evil-shift-right evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(defun aero/evil-shift-left ()
(interactive)
(evil-shift-left evil-visual-beginning evil-visual-end)
(evil-normal-state)
(evil-visual-restore))
(evil-define-key 'visual global-map (kbd ">") 'aero/evil-shift-right)
(evil-define-key 'visual global-map (kbd "<") 'aero/evil-shift-left)
;; :q should kill the current buffer rather than quitting emacs entirely
(evil-ex-define-cmd "q" 'kill-this-buffer)
;; Need to type out :quit to close emacs
(evil-ex-define-cmd "quit" 'evil-quit)
(evil-define-key '(normal visual motion) global-map
(kbd "C-e") #'evil-backward-word-end)
(evil-define-key '(normal visual motion) global-map
(kbd "C-M-e") #'evil-backward-WORD-end)
(evil-define-key '(insert) global-map
(kbd "C-y") #'evil-paste-after)
(evil-define-key '(insert) global-map
(kbd "C-S-y") #'evil-paste-before)
(evil-define-key 'normal 'global
;; Run macro in register q
"Q" "@q")
(evil-define-key 'visual 'global
;; run macro in register q on region
"Q" (kbd ":norm @q RET")
;; repeat on region
"." (kbd ":norm . RET"))
(evil-mode 1))
;; Doesn't do anything for GUI, so don't bother
(unless (display-graphic-p)
(use-package evil-terminal-cursor-changer
:after evil
:functions (evil-terminal-cursor-changer-activate)
:config (evil-terminal-cursor-changer-activate)))
(use-package evil-matchit :straight t :defer 5
:after evil
:defines global-evil-matchit-mode
:config (global-evil-matchit-mode 1))
(use-package evil-visualstar :straight t :defer 5
:after evil
:defines global-evil-visualstar-mode
:config
(global-evil-visualstar-mode t))
;; abo-abo!
(use-package counsel :straight t
:after general
:init/el-patch ; remove bindings which we use `helpful' for
(defvar counsel-mode-map
(let ((map (make-sparse-keymap)))
(dolist (binding
'((execute-extended-command . counsel-M-x)
(describe-bindings . counsel-descbinds)
(el-patch-remove
(describe-function . counsel-describe-function)
(describe-variable . counsel-describe-variable))
(apropos-command . counsel-apropos)
(describe-face . counsel-describe-face)
(list-faces-display . counsel-faces)
(find-file . counsel-find-file)
(find-library . counsel-find-library)
(imenu . counsel-imenu)
(load-library . counsel-load-library)
(load-theme . counsel-load-theme)
(yank-pop . counsel-yank-pop)
(info-lookup-symbol . counsel-info-lookup-symbol)
(pop-to-mark-command . counsel-mark-ring)
(bookmark-jump . counsel-bookmark)))
(define-key map (vector 'remap (car binding)) (cdr binding)))
map)
(el-patch-concat
"Map for `counsel-mode'.
Remaps built-in functions to counsel replacements."
(el-patch-add
"\n\nBindings that are remapped by `helpful' have been removed.")))
(defcustom counsel-mode-override-describe-bindings nil
"Whether to override `describe-bindings' when `counsel-mode' is active."
:type 'boolean
:group 'counsel)
(define-minor-mode counsel-mode
"Toggle Counsel mode on or off.
Turn Counsel mode on if ARG is positive, off otherwise. Counsel mode remaps
built-in emacs functions that have counsel replacements.
Local bindings (`counsel-mode-map'):
\\{counsel-mode-map}"
:global t
:keymap counsel-mode-map
:group 'counsel
(if counsel-mode
(progn
(when (and (fboundp 'advice-add)
counsel-mode-override-describe-bindings)
(advice-add #'describe-bindings :override #'counsel-descbinds))
(define-key minibuffer-local-map (kbd "C-r")
'counsel-minibuffer-history))
(when (fboundp 'advice-remove)
(advice-remove #'describe-bindings #'counsel-descbinds))))
:config
(setq counsel-find-file-ignore-regexp
(concat "\\(?:\\`[#.]\\)\\|\\(?:[#~]\\'\\)"
"\\|\\.x\\'\\|\\.d\\'\\|\\.o\\'"
"\\|\\.aux\\'"))
(defun aero/counsel-unicode-char-after ()
"Like `counsel-unicode-char', but insert after point"
(interactive)
(save-excursion
(right-char)
(counsel-unicode-char)))
(setq counsel-grep-base-command "rg -i -M 120 --no-heading --line-number --color never '%s' %s"
counsel-git-cmd "rg --files"
counsel-rg-base-command "rg --with-filename --smart-case --no-heading --line-number --color never %s")
(aero-leader-def
"SPC" 'counsel-M-x
"ff" 'counsel-find-file
"fl" 'counsel-locate
"fr" 'counsel-recentf
"?" 'counsel-rg
"gg" '(counsel-git-grep :wk "git grep")
"gff" '(counsel-git :wk "find git file")
"ry" '(counsel-yank-pop :wk "search kill ring")
"hda" '(counsel-apropos :wk "apropos")
"qu" '(aero/counsel-unicode-char-after :wk "unicode char")
"qU" 'counsel-unicode-char))
(use-package recentf :defer t
:defines (recentf-mode)
:config
(defvar aero-etc-dir)
(setq recentf-save-file (expand-file-name "recentf" aero-etc-dir)
recentf-max-saved-items 500
;; never cleanup, this will get rid of tramp files
recentf-auto-cleanup 'never)
(recentf-mode 1))
(use-package ivy :straight t
:after general
:functions ivy-mode
:config
(use-package flx :straight t)
(ivy-mode 1)
(setq ivy-initial-inputs-alist nil ; screw the regex
ivy-use-virtual-buffers t ; add recentf to `ivy-switch-buffer'
ivy-virtual-abbreviate 'full
ivy-wrap t
ivy-height 12
ivy-fixed-height-minibuffer t
;; ne pas quitter le minibuffer en cas de `delete-error`
ivy-on-del-error-function #'ignore
;; don't bother counting candidates
ivy-count-format ""
;; use fuzzy by default, but some searching is impossible without
;; stricter regex's
ivy-re-builders-alist '((t . ivy--regex-plus)))
(aero-leader-def
"bb" 'ivy-switch-buffer))
;; Currently disabled but preserved because I can't decide whether I want it or not. Using it means
;; the mode line doesn't jump up on every M-x but also takes some character away from Emacs.
(use-package ivy-posframe :straight t :disabled t
:after (ivy)
:config
(setq ivy-posframe-display-functions-alist
'((swiper . ivy-display-function-fallback)
(complete-symbol . ivy-posframe-display-at-point)
(t . ivy-posframe-display)))
;; Fix atrocious width jumping
(defun aero/ivy-posframe-get-size ()
"Set the ivy-posframe size according to the current frame."
(let ((height (or ivy-posframe-height (or ivy-height 10)))
(width (min (or ivy-posframe-width 200) (round (* .75 (frame-width))))))
(list :height height :width width :min-height height :min-width width)))
(setq ivy-posframe-size-function 'aero/ivy-posframe-get-size)
(ivy-posframe-mode +1))
(use-package ivy-rich :straight t
:after (counsel ivy)
:defines (ivy-rich-path-style)
:functions (ivy-rich-mode)
:config
(setq ivy-rich-path-style 'abbrev)
(setcdr (assq t ivy-format-functions-alist) #'ivy-format-function-line)
(ivy-rich-mode +1)
(ivy-rich-project-root-cache-mode +1))
(use-package all-the-icons :straight t)
(use-package all-the-icons-ivy-rich :straight t
:after (all-the-icons ivy-rich)
:functions (all-the-icons-ivy-rich-mode)
:init (all-the-icons-ivy-rich-mode +1))
(use-package swiper :straight t
:after (general counsel)
:commands (swiper counsel-grep-or-swiper swiper-thing-at-point)
:init
(aero-leader-def
"/" '(counsel-grep-or-swiper :wk "search")
"?" '(swiper-thing-at-point :wk "search thing at point"))
:config
(setq swiper-action-recenter t))
(use-package avy :straight t
:commands (avy-goto-line avy-goto-char avy-goto-word-1)
:init
(general-define-key
:states '(normal visual)
:prefix "SPC"
"jl" '(avy-goto-line :wk "jump to line")
"jc" '(avy-goto-char :wk "jump to char")
"jw" '(avy-goto-word-1 :wk "jump to word")))
(use-package ace-link :straight (:host github :repo "abo-abo/ace-link")
:after (avy)
:functions (ace-link-setup-default)
:init (ace-link-setup-default))
;;; system
(use-package undo-tree :straight t
:config
(global-undo-tree-mode +1)
;; Disable undo-in-region. It sounds like a cool feature, but
;; unfortunately the implementation is very buggy and usually causes
;; you to lose your undo history if you use it by accident.
(setq undo-tree-enable-undo-in-region nil))
(use-package winner
:after (general)
:defines winner-boring-buffers
:config
(setq winner-boring-buffers
'("*Completions*"
"*Compile-Log*"
"*inferior-lisp*"
"*Fuzzy Completions*"
"*Apropos*"
"*Help*"
"*cvs*"
"*Buffer List*"
"*Ibuffer*"
"*esh command on file*"))
(winner-mode 1)
(declare-function general-define-key "general.el")
(general-define-key
:states '(normal)
:prefix "SPC"
:non-normal-prefix "C-SPC"
"wu" 'winner-undo
"wU" 'winner-redo
"wh" 'windmove-left
"wj" 'windmove-down
"wk" 'windmove-up
"wl" 'windmove-right)
;; windmove
(global-set-key (kbd "M-h") #'windmove-left)
(global-set-key (kbd "M-j") #'windmove-down)
(global-set-key (kbd "M-k") #'windmove-up)
(global-set-key (kbd "M-l") #'windmove-right))
(use-package winum :straight t :defer 5
:after (general)
:init
(winum-mode)
:config
(aero-leader-def
"1" '(winum-select-window-1 :wk "window-1")
"2" '(winum-select-window-2 :wk "window-2")
"3" '(winum-select-window-3 :wk "window-3")
"4" '(winum-select-window-4 :wk "window-4")
"5" '(winum-select-window-5 :wk "window-5")
"6" '(winum-select-window-6 :wk "window-6")
"7" '(winum-select-window-7 :wk "window-7")
"8" '(winum-select-window-8 :wk "window-8")
"9" '(winum-select-window-9 :wk "window-9")
"wg" '(winum-select-window-by-number :wk "select window by number"))
;; collapse all those window commands to one summary
(push '(("\\(.*\\) 0" . "winum-select-window-0") . ("\\1 0..9" . "window 0..9"))
which-key-replacement-alist)
(push '((nil . "select-window-[1-9]") . t) which-key-replacement-alist))
(use-package helpful :straight t
:commands (helpful-function
helpful-variable
helpful-macro
helpful-key
helpful-callable)
:after (evil general)
:init
(general-define-key
:states 'normal
:prefix "SPC"
"hdf" 'helpful-function
"hdF" 'counsel-describe-face
"hdb" 'describe-bindings
"hdv" 'helpful-variable
"hdm" 'helpful-macro
"hdM" 'describe-mode
"hdk" 'helpful-key
"hdK" 'describe-keymap
"hdc" 'helpful-callable
"hdC" 'describe-char
"hdp" 'describe-package)
:config
(evil-define-key 'normal helpful-mode-map
"q" 'kill-this-buffer
"?" 'describe-mode))
;;; System-specifics
;; Mac needs some extra hand-holding to connect the kill-ring to the system
;; clipboard.
(when (system-is-mac)
(declare-function aero/pbcopier-select-text "aero-lib.el")
(declare-function aero/pbcopier-selection-value "aero-lib.el")
(setq interprogram-cut-function #'aero/pbcopier-select-text)
(setq interprogram-paste-function #'aero/pbcopier-selection-value)
(setq-default ns-use-native-fullscreen nil)
(if (executable-find "gls")
(progn
(setq insert-directory-program "gls")
(setq dired-listing-switches "-lFaGh1v --group-directories-first"))
(setq dired-listing-switches "-ahlF")))
(when (system-is-linux)
(setq select-enable-clipboard t
interprogram-paste-function #'gui-selection-value
x-gtk-use-system-tooltips t
dired-listing-switches "-lFaGh1v --group-directories-first"))
;; TTY also needs some clipboard help. Only works in certain term emulators,
;; Alacritty is my preferred.
(unless (display-graphic-p)
(use-package xclip :straight t
:config (xclip-mode +1)))
;; File navigation
(use-package tramp
:straight (tramp :host nil :repo "git://git.savannah.gnu.org/tramp.git")
:defer t
:functions tramp-cleanup-all-connection
:config
(setq tramp-auto-save-directory "~/.cache/emacs/backups"
tramp-persistency-file-name "~/.config/emacs/data/tramp"
tramp-use-ssh-controlmaster-options nil ; use system settings instead
tramp-default-method "rsync"
tramp-terminal-type "tramp")
;; push projectile in the right direction
(defadvice projectile-project-root (around ignore-remote first activate)
(unless (file-remote-p default-directory) ad-do-it)))
(use-package ranger :straight t
:commands (deer)
:after general
:init
(setq ranger-show-hidden t
find-directory-functions 'deer)
(general-define-key
:states 'normal
:prefix "SPC"
"fd" 'deer))
;;; General crap
(use-package pomp
:straight (:host gitlab :repo "thornjad/pomp")
:after (general evil)
:commands (pomp)
:init
(evil-set-initial-state 'pomp-mode 'emacs)
(global-set-key (kbd "<f12>") 'pomp)
(general-define-key
:states 'normal
:prefix "SPC"
"ap" 'pomp))
(use-package editorconfig :straight t :defer 5
:functions (editorconfig-mode)
:config (editorconfig-mode +1))
;; Ensure emacsclient frames open with focus
(add-hook 'server-switch-hook (lambda () (select-frame-set-input-focus (selected-frame))))
(provide 'aero-prelude)
|
[
{
"context": "014-2016 Free Software Foundation, Inc\n\n;; Author: Rocky Bernstein <rocky@gnu.org>\n;; This program is free software;",
"end": 91,
"score": 0.9998688697814941,
"start": 76,
"tag": "NAME",
"value": "Rocky Bernstein"
},
{
"context": "ware Foundation, Inc\n\n;; Author: Rocky Bernstein <rocky@gnu.org>\n;; This program is free software; you can redist",
"end": 106,
"score": 0.9999189972877502,
"start": 93,
"tag": "EMAIL",
"value": "rocky@gnu.org"
}
] | elpa/realgud-20190415.227/realgud/debugger/perldb/init.el | llacom/emacs.d | 0 | ;;; Copyright (C) 2011, 2014-2016 Free Software Foundation, Inc
;; Author: Rocky Bernstein <rocky@gnu.org>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Regular expressions for nodejs Javascript debugger.
;;; Stock Perl debugger perldb
(eval-when-compile (require 'cl-lib)) ;For setf.
(require 'load-relative)
(require-relative-list '("../../common/regexp" "../../common/loc") "realgud-")
(require-relative-list '("../../lang/perl") "realgud-lang-")
(defvar realgud-pat-hash)
(declare-function make-realgud-loc-pat (realgud-loc))
(defvar realgud:perldb-pat-hash (make-hash-table :test 'equal)
"Hash key is the what kind of pattern we want to match:
lang-backtrace, prompt, etc. The values of a hash entry is a
realgud-loc-pat struct")
(declare-function make-realgud-loc "realgud-loc" (a b c d e f))
;; Program-location lines look like these:
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284):
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284): my $path;
;; main::(/usr/bin/latex2html:102):
;; main::(/usr/bin/latex2html:102): @ARGV=2;
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
;; main::((eval 8)[/tmp/eval.pl:2]:1):
;;
;; And what are complications MS Windows adds?
;; Hnadle eval form first, e.g.:
;; main::((eval 8)[/tmp/eval.pl:2]:1):
(defconst realgud:perldb-loc-eval-regexp
(format "(eval [0-9]+)\\[\\(.+\\):%s\\]"
realgud:regexp-captured-num))
;; Hnadle non eval form
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
(defconst realgud:perldb-loc-noeval-regexp
(format "\\(?:CODE(0x[0-9a-h]+)\\)?(\\(.+\\):%s):\\(?:\t\\(.*\\)\\)?\n"
realgud:regexp-captured-num))
;; Note that eval form has to come before non-eval form as the non-eval
;; form encompases the eval form. The two clauses makes it hard
;; to match file and line positions, so we ned to result to the
;; "alt" forms of file and lines as well as the non-alt formes
(defconst realgud:perldb-loc-regexp
(format "\\(?:%s\\)\\|\\(?:%s\\)"
realgud:perldb-loc-eval-regexp realgud:perldb-loc-noeval-regexp))
;; Regular expression that describes a perldb location generally shown
;; before a command prompt. We include matching the source text so we
;; can save that.
(setf (gethash "loc" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp realgud:perldb-loc-regexp
:alt-file-group 1
:alt-line-group 2
:file-group 3
:line-group 4
:text-group 5))
;; perldb debugger prompt.
;; Examples:
;; DB<4>
;; [pid=6489->6502] DB<1>
;;
(setf (gethash "prompt" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\\(?:\\[pid=[0-9]+->[0-9]+\\]\\)? DB<\\([0-9]+\\)> "
:num 1
))
;; Regular expression that describes a Perl debugger backtrace line.
;; $ = main::top_navigation_panel called from file `./latex2html' line 7400
;; $ = main::BEGIN() called from file `(eval 19)[/usr/bin/latex2html:126]' line 2
(setf (gethash "debugger-backtrace" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
:file-group 1
:line-group 2))
;; Regular expression that describes location in a Perl errmsg
(setf (gethash "perl-errmsg" realgud:perldb-pat-hash)
realgud-perl-errmsg-loc-pat)
;; Regular expression that describes a Perl Carp backtrace line.
;; at /tmp/foo.pl line 7
;; main::__ANON__('Illegal division by zero at /tmp/foo.pl line 4.\x{a}') called at /tmp/foo.pl line 4
;; main::foo(3) called at /tmp/foo.pl line 8
(setf (gethash "lang-backtrace" realgud:perldb-pat-hash)
realgud-perl-carp-loc-pat)
(defvar realgud:perldb-command-hash (make-hash-table :test 'equal)
"Hash key is command name like 'quit' and the value is
the perldb command to use, like 'q'")
(setf (gethash "font-lock-keywords" realgud:perldb-pat-hash)
'(
("\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
(1 realgud-file-name-face)
(2 realgud-line-number-face))
))
(setf (gethash "perldb" realgud-pat-hash) realgud:perldb-pat-hash)
(setf (gethash "backtrace" realgud:perldb-command-hash) "T")
(setf (gethash "break" realgud:perldb-command-hash) "b %l")
(setf (gethash "clear" realgud:perldb-command-hash) "B %l")
(setf (gethash "continue" realgud:perldb-command-hash) "c")
(setf (gethash "eval" realgud:perldb-command-hash) "x %s")
(setf (gethash "quit" realgud:perldb-command-hash) "q")
(setf (gethash "restart" realgud:perldb-command-hash) "R")
(setf (gethash "run" realgud:perldb-command-hash) "R")
(setf (gethash "step" realgud:perldb-command-hash) "s")
(setf (gethash "next" realgud:perldb-command-hash) "n")
(setf (gethash "until" realgud:perldb-command-hash) "c %l")
(setf (gethash "perldb" realgud-command-hash) realgud:perldb-command-hash)
;; Unsupported features:
(setf (gethash "frame" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "shell" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "up" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "down" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "jump" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "kill" realgud:perldb-command-hash) "*not-implemented*")
(provide-me "realgud:perldb-")
| 12603 | ;;; Copyright (C) 2011, 2014-2016 Free Software Foundation, Inc
;; Author: <NAME> <<EMAIL>>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Regular expressions for nodejs Javascript debugger.
;;; Stock Perl debugger perldb
(eval-when-compile (require 'cl-lib)) ;For setf.
(require 'load-relative)
(require-relative-list '("../../common/regexp" "../../common/loc") "realgud-")
(require-relative-list '("../../lang/perl") "realgud-lang-")
(defvar realgud-pat-hash)
(declare-function make-realgud-loc-pat (realgud-loc))
(defvar realgud:perldb-pat-hash (make-hash-table :test 'equal)
"Hash key is the what kind of pattern we want to match:
lang-backtrace, prompt, etc. The values of a hash entry is a
realgud-loc-pat struct")
(declare-function make-realgud-loc "realgud-loc" (a b c d e f))
;; Program-location lines look like these:
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284):
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284): my $path;
;; main::(/usr/bin/latex2html:102):
;; main::(/usr/bin/latex2html:102): @ARGV=2;
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
;; main::((eval 8)[/tmp/eval.pl:2]:1):
;;
;; And what are complications MS Windows adds?
;; Hnadle eval form first, e.g.:
;; main::((eval 8)[/tmp/eval.pl:2]:1):
(defconst realgud:perldb-loc-eval-regexp
(format "(eval [0-9]+)\\[\\(.+\\):%s\\]"
realgud:regexp-captured-num))
;; Hnadle non eval form
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
(defconst realgud:perldb-loc-noeval-regexp
(format "\\(?:CODE(0x[0-9a-h]+)\\)?(\\(.+\\):%s):\\(?:\t\\(.*\\)\\)?\n"
realgud:regexp-captured-num))
;; Note that eval form has to come before non-eval form as the non-eval
;; form encompases the eval form. The two clauses makes it hard
;; to match file and line positions, so we ned to result to the
;; "alt" forms of file and lines as well as the non-alt formes
(defconst realgud:perldb-loc-regexp
(format "\\(?:%s\\)\\|\\(?:%s\\)"
realgud:perldb-loc-eval-regexp realgud:perldb-loc-noeval-regexp))
;; Regular expression that describes a perldb location generally shown
;; before a command prompt. We include matching the source text so we
;; can save that.
(setf (gethash "loc" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp realgud:perldb-loc-regexp
:alt-file-group 1
:alt-line-group 2
:file-group 3
:line-group 4
:text-group 5))
;; perldb debugger prompt.
;; Examples:
;; DB<4>
;; [pid=6489->6502] DB<1>
;;
(setf (gethash "prompt" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\\(?:\\[pid=[0-9]+->[0-9]+\\]\\)? DB<\\([0-9]+\\)> "
:num 1
))
;; Regular expression that describes a Perl debugger backtrace line.
;; $ = main::top_navigation_panel called from file `./latex2html' line 7400
;; $ = main::BEGIN() called from file `(eval 19)[/usr/bin/latex2html:126]' line 2
(setf (gethash "debugger-backtrace" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
:file-group 1
:line-group 2))
;; Regular expression that describes location in a Perl errmsg
(setf (gethash "perl-errmsg" realgud:perldb-pat-hash)
realgud-perl-errmsg-loc-pat)
;; Regular expression that describes a Perl Carp backtrace line.
;; at /tmp/foo.pl line 7
;; main::__ANON__('Illegal division by zero at /tmp/foo.pl line 4.\x{a}') called at /tmp/foo.pl line 4
;; main::foo(3) called at /tmp/foo.pl line 8
(setf (gethash "lang-backtrace" realgud:perldb-pat-hash)
realgud-perl-carp-loc-pat)
(defvar realgud:perldb-command-hash (make-hash-table :test 'equal)
"Hash key is command name like 'quit' and the value is
the perldb command to use, like 'q'")
(setf (gethash "font-lock-keywords" realgud:perldb-pat-hash)
'(
("\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
(1 realgud-file-name-face)
(2 realgud-line-number-face))
))
(setf (gethash "perldb" realgud-pat-hash) realgud:perldb-pat-hash)
(setf (gethash "backtrace" realgud:perldb-command-hash) "T")
(setf (gethash "break" realgud:perldb-command-hash) "b %l")
(setf (gethash "clear" realgud:perldb-command-hash) "B %l")
(setf (gethash "continue" realgud:perldb-command-hash) "c")
(setf (gethash "eval" realgud:perldb-command-hash) "x %s")
(setf (gethash "quit" realgud:perldb-command-hash) "q")
(setf (gethash "restart" realgud:perldb-command-hash) "R")
(setf (gethash "run" realgud:perldb-command-hash) "R")
(setf (gethash "step" realgud:perldb-command-hash) "s")
(setf (gethash "next" realgud:perldb-command-hash) "n")
(setf (gethash "until" realgud:perldb-command-hash) "c %l")
(setf (gethash "perldb" realgud-command-hash) realgud:perldb-command-hash)
;; Unsupported features:
(setf (gethash "frame" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "shell" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "up" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "down" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "jump" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "kill" realgud:perldb-command-hash) "*not-implemented*")
(provide-me "realgud:perldb-")
| true | ;;; Copyright (C) 2011, 2014-2016 Free Software Foundation, Inc
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Regular expressions for nodejs Javascript debugger.
;;; Stock Perl debugger perldb
(eval-when-compile (require 'cl-lib)) ;For setf.
(require 'load-relative)
(require-relative-list '("../../common/regexp" "../../common/loc") "realgud-")
(require-relative-list '("../../lang/perl") "realgud-lang-")
(defvar realgud-pat-hash)
(declare-function make-realgud-loc-pat (realgud-loc))
(defvar realgud:perldb-pat-hash (make-hash-table :test 'equal)
"Hash key is the what kind of pattern we want to match:
lang-backtrace, prompt, etc. The values of a hash entry is a
realgud-loc-pat struct")
(declare-function make-realgud-loc "realgud-loc" (a b c d e f))
;; Program-location lines look like these:
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284):
;; File::Basename::dirname(/usr/share/perl/5.16.0/File/Basename.pm:284): my $path;
;; main::(/usr/bin/latex2html:102):
;; main::(/usr/bin/latex2html:102): @ARGV=2;
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
;; main::((eval 8)[/tmp/eval.pl:2]:1):
;;
;; And what are complications MS Windows adds?
;; Hnadle eval form first, e.g.:
;; main::((eval 8)[/tmp/eval.pl:2]:1):
(defconst realgud:perldb-loc-eval-regexp
(format "(eval [0-9]+)\\[\\(.+\\):%s\\]"
realgud:regexp-captured-num))
;; Hnadle non eval form
;; main::CODE(0x9407ac8)(l2hconf.pm:6):;;
(defconst realgud:perldb-loc-noeval-regexp
(format "\\(?:CODE(0x[0-9a-h]+)\\)?(\\(.+\\):%s):\\(?:\t\\(.*\\)\\)?\n"
realgud:regexp-captured-num))
;; Note that eval form has to come before non-eval form as the non-eval
;; form encompases the eval form. The two clauses makes it hard
;; to match file and line positions, so we ned to result to the
;; "alt" forms of file and lines as well as the non-alt formes
(defconst realgud:perldb-loc-regexp
(format "\\(?:%s\\)\\|\\(?:%s\\)"
realgud:perldb-loc-eval-regexp realgud:perldb-loc-noeval-regexp))
;; Regular expression that describes a perldb location generally shown
;; before a command prompt. We include matching the source text so we
;; can save that.
(setf (gethash "loc" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp realgud:perldb-loc-regexp
:alt-file-group 1
:alt-line-group 2
:file-group 3
:line-group 4
:text-group 5))
;; perldb debugger prompt.
;; Examples:
;; DB<4>
;; [pid=6489->6502] DB<1>
;;
(setf (gethash "prompt" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\\(?:\\[pid=[0-9]+->[0-9]+\\]\\)? DB<\\([0-9]+\\)> "
:num 1
))
;; Regular expression that describes a Perl debugger backtrace line.
;; $ = main::top_navigation_panel called from file `./latex2html' line 7400
;; $ = main::BEGIN() called from file `(eval 19)[/usr/bin/latex2html:126]' line 2
(setf (gethash "debugger-backtrace" realgud:perldb-pat-hash)
(make-realgud-loc-pat
:regexp "\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
:file-group 1
:line-group 2))
;; Regular expression that describes location in a Perl errmsg
(setf (gethash "perl-errmsg" realgud:perldb-pat-hash)
realgud-perl-errmsg-loc-pat)
;; Regular expression that describes a Perl Carp backtrace line.
;; at /tmp/foo.pl line 7
;; main::__ANON__('Illegal division by zero at /tmp/foo.pl line 4.\x{a}') called at /tmp/foo.pl line 4
;; main::foo(3) called at /tmp/foo.pl line 8
(setf (gethash "lang-backtrace" realgud:perldb-pat-hash)
realgud-perl-carp-loc-pat)
(defvar realgud:perldb-command-hash (make-hash-table :test 'equal)
"Hash key is command name like 'quit' and the value is
the perldb command to use, like 'q'")
(setf (gethash "font-lock-keywords" realgud:perldb-pat-hash)
'(
("\s+called from file `\\(.+\\)' line \\([0-9]+\\)"
(1 realgud-file-name-face)
(2 realgud-line-number-face))
))
(setf (gethash "perldb" realgud-pat-hash) realgud:perldb-pat-hash)
(setf (gethash "backtrace" realgud:perldb-command-hash) "T")
(setf (gethash "break" realgud:perldb-command-hash) "b %l")
(setf (gethash "clear" realgud:perldb-command-hash) "B %l")
(setf (gethash "continue" realgud:perldb-command-hash) "c")
(setf (gethash "eval" realgud:perldb-command-hash) "x %s")
(setf (gethash "quit" realgud:perldb-command-hash) "q")
(setf (gethash "restart" realgud:perldb-command-hash) "R")
(setf (gethash "run" realgud:perldb-command-hash) "R")
(setf (gethash "step" realgud:perldb-command-hash) "s")
(setf (gethash "next" realgud:perldb-command-hash) "n")
(setf (gethash "until" realgud:perldb-command-hash) "c %l")
(setf (gethash "perldb" realgud-command-hash) realgud:perldb-command-hash)
;; Unsupported features:
(setf (gethash "frame" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "shell" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "up" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "down" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "jump" realgud:perldb-command-hash) "*not-implemented*")
(setf (gethash "kill" realgud:perldb-command-hash) "*not-implemented*")
(provide-me "realgud:perldb-")
|
[
{
"context": " *- lexical-binding: t; -*-\n\n;; Copyright (C) 2019 David Landell <david.landell@sunnyhill.email>\n;;\n;; Author: Dav",
"end": 133,
"score": 0.9998695850372314,
"start": 120,
"tag": "NAME",
"value": "David Landell"
},
{
"context": "ing: t; -*-\n\n;; Copyright (C) 2019 David Landell <david.landell@sunnyhill.email>\n;;\n;; Author: David Landell <david.landell@sunny",
"end": 164,
"score": 0.9999328255653381,
"start": 135,
"tag": "EMAIL",
"value": "david.landell@sunnyhill.email"
},
{
"context": "dell <david.landell@sunnyhill.email>\n;;\n;; Author: David Landell <david.landell@sunnyhill.email>\n;; URL: https://g",
"end": 193,
"score": 0.9996384978294373,
"start": 180,
"tag": "NAME",
"value": "David Landell"
},
{
"context": "ell@sunnyhill.email>\n;;\n;; Author: David Landell <david.landell@sunnyhill.email>\n;; URL: https://github.com/dajva/rg.el\n\n;; This ",
"end": 224,
"score": 0.9999338984489441,
"start": 195,
"tag": "EMAIL",
"value": "david.landell@sunnyhill.email"
},
{
"context": "ndell@sunnyhill.email>\n;; URL: https://github.com/dajva/rg.el\n\n;; This file is not part of GNU Emacs.\n\n;;",
"end": 258,
"score": 0.9965811371803284,
"start": 253,
"tag": "USERNAME",
"value": "dajva"
}
] | elpa/rg-20200703.1250/rg-info-hack.el | micolore/.emacs.d | 0 | ;;; rg-info-hack.el --- Make sure rg.el info documentation looks good *- lexical-binding: t; -*-
;; Copyright (C) 2019 David Landell <david.landell@sunnyhill.email>
;;
;; Author: David Landell <david.landell@sunnyhill.email>
;; URL: https://github.com/dajva/rg.el
;; This file is not part of GNU Emacs.
;; 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 3
;; of the License, 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., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;;; Code:
(defadvice info-insert-file-contents (after
sphinx-info-insert-file-contents
activate)
"Hack to hide \"See\" in references.
This makes `Info-hide-note-references' buffer-local and
automatically set to `hide' iff it can be determined that this file
is the rg.el documentation and was created from a Texinfo file
generated by Sphinx."
(set (make-local-variable
'Info-hide-note-references)
(default-value 'Info-hide-note-references))
(save-excursion
(save-restriction
(widen) (goto-char (point-min))
(when (and (search-forward "* rgel:" nil t)
(search-forward
"Generated by Sphinx"
(save-excursion (search-forward "\x1f" nil t)) t))
(set (make-local-variable 'Info-hide-note-references)
'hide)))))
(provide 'rg-info-hack)
;;; rg-info-hack.el ends here
| 8528 | ;;; rg-info-hack.el --- Make sure rg.el info documentation looks good *- lexical-binding: t; -*-
;; Copyright (C) 2019 <NAME> <<EMAIL>>
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/dajva/rg.el
;; This file is not part of GNU Emacs.
;; 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 3
;; of the License, 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., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;;; Code:
(defadvice info-insert-file-contents (after
sphinx-info-insert-file-contents
activate)
"Hack to hide \"See\" in references.
This makes `Info-hide-note-references' buffer-local and
automatically set to `hide' iff it can be determined that this file
is the rg.el documentation and was created from a Texinfo file
generated by Sphinx."
(set (make-local-variable
'Info-hide-note-references)
(default-value 'Info-hide-note-references))
(save-excursion
(save-restriction
(widen) (goto-char (point-min))
(when (and (search-forward "* rgel:" nil t)
(search-forward
"Generated by Sphinx"
(save-excursion (search-forward "\x1f" nil t)) t))
(set (make-local-variable 'Info-hide-note-references)
'hide)))))
(provide 'rg-info-hack)
;;; rg-info-hack.el ends here
| true | ;;; rg-info-hack.el --- Make sure rg.el info documentation looks good *- lexical-binding: t; -*-
;; Copyright (C) 2019 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/dajva/rg.el
;; This file is not part of GNU Emacs.
;; 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 3
;; of the License, 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., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301, USA.
;;; Commentary:
;;; Code:
(defadvice info-insert-file-contents (after
sphinx-info-insert-file-contents
activate)
"Hack to hide \"See\" in references.
This makes `Info-hide-note-references' buffer-local and
automatically set to `hide' iff it can be determined that this file
is the rg.el documentation and was created from a Texinfo file
generated by Sphinx."
(set (make-local-variable
'Info-hide-note-references)
(default-value 'Info-hide-note-references))
(save-excursion
(save-restriction
(widen) (goto-char (point-min))
(when (and (search-forward "* rgel:" nil t)
(search-forward
"Generated by Sphinx"
(save-excursion (search-forward "\x1f" nil t)) t))
(set (make-local-variable 'Info-hide-note-references)
'hide)))))
(provide 'rg-info-hack)
;;; rg-info-hack.el ends here
|
[
{
"context": "*- lexical-binding: t; -*-\n\n;; Copyright (C) 2022 ingtshan\n\n;; Author: ingtshan <rongcanyo@gmail.com>\n;; Key",
"end": 113,
"score": 0.9958047866821289,
"start": 105,
"tag": "USERNAME",
"value": "ingtshan"
},
{
"context": "; -*-\n\n;; Copyright (C) 2022 ingtshan\n\n;; Author: ingtshan <rongcanyo@gmail.com>\n;; Keywords: i18n\n\n;; This ",
"end": 134,
"score": 0.999519407749176,
"start": 126,
"tag": "USERNAME",
"value": "ingtshan"
},
{
"context": "opyright (C) 2022 ingtshan\n\n;; Author: ingtshan <rongcanyo@gmail.com>\n;; Keywords: i18n\n\n;; This program is free softw",
"end": 155,
"score": 0.9999182820320129,
"start": 136,
"tag": "EMAIL",
"value": "rongcanyo@gmail.com"
}
] | modules/tools/lsp-bridge/config.el | ingtshan/doom-emacs-private | 0 | ;;; config.el --- i18n -*- lexical-binding: t; -*-
;; Copyright (C) 2022 ingtshan
;; Author: ingtshan <rongcanyo@gmail.com>
;; Keywords: i18n
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
;; corfu
;; lsp-bridge
(add-to-list 'load-path "~/.emacs.d/.local/straight/repos/lsp-bridge")
(require 'lsp-bridge)
;; (require 'lsp-bridge-jdtls)
(global-lsp-bridge-mode)
(defun lsp-bridge-jump ()
(interactive)
(cond
((eq major-mode 'emacs-lisp-mode)
(let ((symb (function-called-at-point)))
(when symb
(find-function symb))))
(lsp-bridge-mode
(lsp-bridge-find-def))
(t
(require 'dumb-jump)
(dumb-jump-go))))
(defun lsp-bridge-jump-back ()
(interactive)
(cond
(lsp-bridge-mode
(lsp-bridge-return-from-def))
(t
(require 'dumb-jump)
(dumb-jump-back))))
;;; config.el ends here
| 22432 | ;;; config.el --- i18n -*- lexical-binding: t; -*-
;; Copyright (C) 2022 ingtshan
;; Author: ingtshan <<EMAIL>>
;; Keywords: i18n
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
;; corfu
;; lsp-bridge
(add-to-list 'load-path "~/.emacs.d/.local/straight/repos/lsp-bridge")
(require 'lsp-bridge)
;; (require 'lsp-bridge-jdtls)
(global-lsp-bridge-mode)
(defun lsp-bridge-jump ()
(interactive)
(cond
((eq major-mode 'emacs-lisp-mode)
(let ((symb (function-called-at-point)))
(when symb
(find-function symb))))
(lsp-bridge-mode
(lsp-bridge-find-def))
(t
(require 'dumb-jump)
(dumb-jump-go))))
(defun lsp-bridge-jump-back ()
(interactive)
(cond
(lsp-bridge-mode
(lsp-bridge-return-from-def))
(t
(require 'dumb-jump)
(dumb-jump-back))))
;;; config.el ends here
| true | ;;; config.el --- i18n -*- lexical-binding: t; -*-
;; Copyright (C) 2022 ingtshan
;; Author: ingtshan <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: i18n
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
;; corfu
;; lsp-bridge
(add-to-list 'load-path "~/.emacs.d/.local/straight/repos/lsp-bridge")
(require 'lsp-bridge)
;; (require 'lsp-bridge-jdtls)
(global-lsp-bridge-mode)
(defun lsp-bridge-jump ()
(interactive)
(cond
((eq major-mode 'emacs-lisp-mode)
(let ((symb (function-called-at-point)))
(when symb
(find-function symb))))
(lsp-bridge-mode
(lsp-bridge-find-def))
(t
(require 'dumb-jump)
(dumb-jump-go))))
(defun lsp-bridge-jump-back ()
(interactive)
(cond
(lsp-bridge-mode
(lsp-bridge-return-from-def))
(t
(require 'dumb-jump)
(dumb-jump-back))))
;;; config.el ends here
|
[
{
"context": " the \"black\" formatter\n\n;; Copyright (C) 2018-2019 Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>",
"end": 113,
"score": 0.9998928904533386,
"start": 99,
"tag": "NAME",
"value": "Artem Malyshev"
},
{
"context": "Copyright (C) 2018-2019 Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>\n;; Homepage: https://githu",
"end": 140,
"score": 0.9998981356620789,
"start": 126,
"tag": "NAME",
"value": "Artem Malyshev"
},
{
"context": "8-2019 Artem Malyshev\n\n;; Author: Artem Malyshev <proofit404@gmail.com>\n;; Homepage: https://github.com/proofit404/black",
"end": 162,
"score": 0.9999242424964905,
"start": 142,
"tag": "EMAIL",
"value": "proofit404@gmail.com"
},
{
"context": "fit404@gmail.com>\n;; Homepage: https://github.com/proofit404/blacken\n;; Version: 0.0.1\n;; Package-Requires: ((",
"end": 206,
"score": 0.9889141321182251,
"start": 196,
"tag": "USERNAME",
"value": "proofit404"
}
] | core/blacken.el | ovnicraft/emacs.d | 0 | ;;; blacken.el --- Reformat python buffers using the "black" formatter
;; Copyright (C) 2018-2019 Artem Malyshev
;; Author: Artem Malyshev <proofit404@gmail.com>
;; Homepage: https://github.com/proofit404/blacken
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.2"))
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Blacken uses black to format a Python buffer. It can be called
;; explicitly on a certain buffer, but more conveniently, a minor-mode
;; 'blacken-mode' is provided that turns on automatically running
;; black on a buffer before saving.
;;
;; Installation:
;;
;; Add blacken.el to your load-path.
;;
;; To automatically format all Python buffers before saving, add the
;; function blacken-mode to python-mode-hook:
;;
;; (add-hook 'python-mode-hook 'blacken-mode)
;;
;;; Code:
(require 'cl-lib)
(defgroup blacken nil
"Reformat Python code with \"black\"."
:group 'python)
(defcustom blacken-executable "black"
"Name of the executable to run."
:type 'string)
(defcustom blacken-line-length nil
"Line length to enforce.
It must be an integer, nil or `fill'.
If `fill', the `fill-column' variable value is used."
:type '(choice :tag "Line Length Limit"
(const :tag "Use default" nil)
(const :tag "Use fill-column" fill)
(integer :tag "Line Length"))
:safe 'integerp)
(defcustom blacken-allow-py36 nil
"Allow using Python 3.6-only syntax on all input files."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-skip-string-normalization nil
"Don't normalize string quotes or prefixes."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-fast-unsafe nil
"Skips temporary sanity checks."
:type 'boolean
:safe 'booleanp)
(defun blacken-call-bin (input-buffer output-buffer error-buffer)
"Call process black.
Send INPUT-BUFFER content to the process stdin. Saving the
output to OUTPUT-BUFFER. Saving process stderr to ERROR-BUFFER.
Return black process the exit code."
(with-current-buffer input-buffer
(let ((process (make-process :name "blacken"
:command `(,blacken-executable ,@(blacken-call-args))
:buffer output-buffer
:stderr error-buffer
:noquery t
:sentinel (lambda (process event)))))
(set-process-query-on-exit-flag (get-buffer-process error-buffer) nil)
(set-process-sentinel (get-buffer-process error-buffer) (lambda (process event)))
(save-restriction
(widen)
(process-send-region process (point-min) (point-max)))
(process-send-eof process)
(accept-process-output process nil nil t)
(while (process-live-p process)
(accept-process-output process nil nil t))
(process-exit-status process))))
(defun blacken-call-args ()
"Build black process call arguments."
(append
(when blacken-line-length
(list "--line-length"
(number-to-string (cl-case blacken-line-length
('fill fill-column)
(t blacken-line-length)))))
(when blacken-allow-py36
(list "--py36"))
(when blacken-fast-unsafe
(list "--fast"))
(when blacken-skip-string-normalization
(list "--skip-string-normalization"))
'("-")))
;;;###autoload
(defun blacken-buffer (&optional display)
"Try to blacken the current buffer.
Show black output, if black exit abnormally and DISPLAY is t."
(interactive (list t))
(let* ((original-buffer (current-buffer))
(original-point (point))
(original-window-pos (window-start))
(tmpbuf (get-buffer-create "*blacken*"))
(errbuf (get-buffer-create "*blacken-error*")))
;; This buffer can be left after previous black invocation. It
;; can contain error message of the previous run.
(dolist (buf (list tmpbuf errbuf))
(with-current-buffer buf
(erase-buffer)))
(condition-case err
(if (not (zerop (blacken-call-bin original-buffer tmpbuf errbuf)))
(error "Black failed, see %s buffer for details" (buffer-name errbuf))
(unless (eq (compare-buffer-substrings tmpbuf nil nil original-buffer nil nil) 0)
(with-current-buffer tmpbuf
(copy-to-buffer original-buffer (point-min) (point-max)))
(goto-char original-point)
(set-window-start (selected-window) original-window-pos))
(mapc 'kill-buffer (list tmpbuf errbuf)))
(error (message "%s" (error-message-string err))
(when display
(pop-to-buffer errbuf))))))
;;;###autoload
(define-minor-mode blacken-mode
"Automatically run black before saving."
:lighter " Black"
(if blacken-mode
(add-hook 'before-save-hook 'blacken-buffer nil t)
(remove-hook 'before-save-hook 'blacken-buffer t)))
(provide 'blacken)
;;; blacken.el ends here
| 47883 | ;;; blacken.el --- Reformat python buffers using the "black" formatter
;; Copyright (C) 2018-2019 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Homepage: https://github.com/proofit404/blacken
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.2"))
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Blacken uses black to format a Python buffer. It can be called
;; explicitly on a certain buffer, but more conveniently, a minor-mode
;; 'blacken-mode' is provided that turns on automatically running
;; black on a buffer before saving.
;;
;; Installation:
;;
;; Add blacken.el to your load-path.
;;
;; To automatically format all Python buffers before saving, add the
;; function blacken-mode to python-mode-hook:
;;
;; (add-hook 'python-mode-hook 'blacken-mode)
;;
;;; Code:
(require 'cl-lib)
(defgroup blacken nil
"Reformat Python code with \"black\"."
:group 'python)
(defcustom blacken-executable "black"
"Name of the executable to run."
:type 'string)
(defcustom blacken-line-length nil
"Line length to enforce.
It must be an integer, nil or `fill'.
If `fill', the `fill-column' variable value is used."
:type '(choice :tag "Line Length Limit"
(const :tag "Use default" nil)
(const :tag "Use fill-column" fill)
(integer :tag "Line Length"))
:safe 'integerp)
(defcustom blacken-allow-py36 nil
"Allow using Python 3.6-only syntax on all input files."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-skip-string-normalization nil
"Don't normalize string quotes or prefixes."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-fast-unsafe nil
"Skips temporary sanity checks."
:type 'boolean
:safe 'booleanp)
(defun blacken-call-bin (input-buffer output-buffer error-buffer)
"Call process black.
Send INPUT-BUFFER content to the process stdin. Saving the
output to OUTPUT-BUFFER. Saving process stderr to ERROR-BUFFER.
Return black process the exit code."
(with-current-buffer input-buffer
(let ((process (make-process :name "blacken"
:command `(,blacken-executable ,@(blacken-call-args))
:buffer output-buffer
:stderr error-buffer
:noquery t
:sentinel (lambda (process event)))))
(set-process-query-on-exit-flag (get-buffer-process error-buffer) nil)
(set-process-sentinel (get-buffer-process error-buffer) (lambda (process event)))
(save-restriction
(widen)
(process-send-region process (point-min) (point-max)))
(process-send-eof process)
(accept-process-output process nil nil t)
(while (process-live-p process)
(accept-process-output process nil nil t))
(process-exit-status process))))
(defun blacken-call-args ()
"Build black process call arguments."
(append
(when blacken-line-length
(list "--line-length"
(number-to-string (cl-case blacken-line-length
('fill fill-column)
(t blacken-line-length)))))
(when blacken-allow-py36
(list "--py36"))
(when blacken-fast-unsafe
(list "--fast"))
(when blacken-skip-string-normalization
(list "--skip-string-normalization"))
'("-")))
;;;###autoload
(defun blacken-buffer (&optional display)
"Try to blacken the current buffer.
Show black output, if black exit abnormally and DISPLAY is t."
(interactive (list t))
(let* ((original-buffer (current-buffer))
(original-point (point))
(original-window-pos (window-start))
(tmpbuf (get-buffer-create "*blacken*"))
(errbuf (get-buffer-create "*blacken-error*")))
;; This buffer can be left after previous black invocation. It
;; can contain error message of the previous run.
(dolist (buf (list tmpbuf errbuf))
(with-current-buffer buf
(erase-buffer)))
(condition-case err
(if (not (zerop (blacken-call-bin original-buffer tmpbuf errbuf)))
(error "Black failed, see %s buffer for details" (buffer-name errbuf))
(unless (eq (compare-buffer-substrings tmpbuf nil nil original-buffer nil nil) 0)
(with-current-buffer tmpbuf
(copy-to-buffer original-buffer (point-min) (point-max)))
(goto-char original-point)
(set-window-start (selected-window) original-window-pos))
(mapc 'kill-buffer (list tmpbuf errbuf)))
(error (message "%s" (error-message-string err))
(when display
(pop-to-buffer errbuf))))))
;;;###autoload
(define-minor-mode blacken-mode
"Automatically run black before saving."
:lighter " Black"
(if blacken-mode
(add-hook 'before-save-hook 'blacken-buffer nil t)
(remove-hook 'before-save-hook 'blacken-buffer t)))
(provide 'blacken)
;;; blacken.el ends here
| true | ;;; blacken.el --- Reformat python buffers using the "black" formatter
;; Copyright (C) 2018-2019 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Homepage: https://github.com/proofit404/blacken
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.2"))
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Blacken uses black to format a Python buffer. It can be called
;; explicitly on a certain buffer, but more conveniently, a minor-mode
;; 'blacken-mode' is provided that turns on automatically running
;; black on a buffer before saving.
;;
;; Installation:
;;
;; Add blacken.el to your load-path.
;;
;; To automatically format all Python buffers before saving, add the
;; function blacken-mode to python-mode-hook:
;;
;; (add-hook 'python-mode-hook 'blacken-mode)
;;
;;; Code:
(require 'cl-lib)
(defgroup blacken nil
"Reformat Python code with \"black\"."
:group 'python)
(defcustom blacken-executable "black"
"Name of the executable to run."
:type 'string)
(defcustom blacken-line-length nil
"Line length to enforce.
It must be an integer, nil or `fill'.
If `fill', the `fill-column' variable value is used."
:type '(choice :tag "Line Length Limit"
(const :tag "Use default" nil)
(const :tag "Use fill-column" fill)
(integer :tag "Line Length"))
:safe 'integerp)
(defcustom blacken-allow-py36 nil
"Allow using Python 3.6-only syntax on all input files."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-skip-string-normalization nil
"Don't normalize string quotes or prefixes."
:type 'boolean
:safe 'booleanp)
(defcustom blacken-fast-unsafe nil
"Skips temporary sanity checks."
:type 'boolean
:safe 'booleanp)
(defun blacken-call-bin (input-buffer output-buffer error-buffer)
"Call process black.
Send INPUT-BUFFER content to the process stdin. Saving the
output to OUTPUT-BUFFER. Saving process stderr to ERROR-BUFFER.
Return black process the exit code."
(with-current-buffer input-buffer
(let ((process (make-process :name "blacken"
:command `(,blacken-executable ,@(blacken-call-args))
:buffer output-buffer
:stderr error-buffer
:noquery t
:sentinel (lambda (process event)))))
(set-process-query-on-exit-flag (get-buffer-process error-buffer) nil)
(set-process-sentinel (get-buffer-process error-buffer) (lambda (process event)))
(save-restriction
(widen)
(process-send-region process (point-min) (point-max)))
(process-send-eof process)
(accept-process-output process nil nil t)
(while (process-live-p process)
(accept-process-output process nil nil t))
(process-exit-status process))))
(defun blacken-call-args ()
"Build black process call arguments."
(append
(when blacken-line-length
(list "--line-length"
(number-to-string (cl-case blacken-line-length
('fill fill-column)
(t blacken-line-length)))))
(when blacken-allow-py36
(list "--py36"))
(when blacken-fast-unsafe
(list "--fast"))
(when blacken-skip-string-normalization
(list "--skip-string-normalization"))
'("-")))
;;;###autoload
(defun blacken-buffer (&optional display)
"Try to blacken the current buffer.
Show black output, if black exit abnormally and DISPLAY is t."
(interactive (list t))
(let* ((original-buffer (current-buffer))
(original-point (point))
(original-window-pos (window-start))
(tmpbuf (get-buffer-create "*blacken*"))
(errbuf (get-buffer-create "*blacken-error*")))
;; This buffer can be left after previous black invocation. It
;; can contain error message of the previous run.
(dolist (buf (list tmpbuf errbuf))
(with-current-buffer buf
(erase-buffer)))
(condition-case err
(if (not (zerop (blacken-call-bin original-buffer tmpbuf errbuf)))
(error "Black failed, see %s buffer for details" (buffer-name errbuf))
(unless (eq (compare-buffer-substrings tmpbuf nil nil original-buffer nil nil) 0)
(with-current-buffer tmpbuf
(copy-to-buffer original-buffer (point-min) (point-max)))
(goto-char original-point)
(set-window-start (selected-window) original-window-pos))
(mapc 'kill-buffer (list tmpbuf errbuf)))
(error (message "%s" (error-message-string err))
(when display
(pop-to-buffer errbuf))))))
;;;###autoload
(define-minor-mode blacken-mode
"Automatically run black before saving."
:lighter " Black"
(if blacken-mode
(add-hook 'before-save-hook 'blacken-buffer nil t)
(remove-hook 'before-save-hook 'blacken-buffer t)))
(provide 'blacken)
;;; blacken.el ends here
|
[
{
"context": "cs-w3m ml\n\n;; Copyright (C) 2001, 2002, 2003, 2004 Akihiro Arisawa <ari@mbf.sphere.ne.jp>\n\n;; Author: Akihiro Arisa",
"end": 113,
"score": 0.9998732805252075,
"start": 98,
"tag": "NAME",
"value": "Akihiro Arisawa"
},
{
"context": "ight (C) 2001, 2002, 2003, 2004 Akihiro Arisawa <ari@mbf.sphere.ne.jp>\n\n;; Author: Akihiro Arisawa <ari@mbf.sphere.ne.j",
"end": 136,
"score": 0.9999361038208008,
"start": 116,
"tag": "EMAIL",
"value": "ari@mbf.sphere.ne.jp"
},
{
"context": "kihiro Arisawa <ari@mbf.sphere.ne.jp>\n\n;; Author: Akihiro Arisawa <ari@mbf.sphere.ne.jp>\n;; Keywords: news\n\n;; This",
"end": 165,
"score": 0.9998779892921448,
"start": 150,
"tag": "NAME",
"value": "Akihiro Arisawa"
},
{
"context": "ri@mbf.sphere.ne.jp>\n\n;; Author: Akihiro Arisawa <ari@mbf.sphere.ne.jp>\n;; Keywords: news\n\n;; This file is a part of shi",
"end": 187,
"score": 0.999936580657959,
"start": 167,
"tag": "EMAIL",
"value": "ari@mbf.sphere.ne.jp"
},
{
"context": "shimbun-reply-to ((shimbun shimbun-emacs-w3m))\n \"emacs-w3m@namazu.org\")\n\n(luna-define-method shimbun-get-headers ((shim",
"end": 1528,
"score": 0.9999263286590576,
"start": 1508,
"tag": "EMAIL",
"value": "emacs-w3m@namazu.org"
}
] | site-lisp/shimbun/sb-emacs-w3m.el | colorfulsky/.emacs.d | 1 | ;;; sb-emacs-w3m.el --- shimbun backend for emacs-w3m ml
;; Copyright (C) 2001, 2002, 2003, 2004 Akihiro Arisawa <ari@mbf.sphere.ne.jp>
;; Author: Akihiro Arisawa <ari@mbf.sphere.ne.jp>
;; Keywords: news
;; This file is a part of shimbun.
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Code:
(eval-when-compile
(require 'cl))
(require 'shimbun)
(require 'sb-mhonarc)
(luna-define-class shimbun-emacs-w3m (shimbun-mhonarc) ())
(defvar shimbun-emacs-w3m-url "http://emacs-w3m.namazu.org/ml/")
(defvar shimbun-emacs-w3m-groups '("emacs-w3m"))
(defvar shimbun-emacs-w3m-reverse-flag t)
(defvar shimbun-emacs-w3m-litemplate-regexp
"<Strong><A NAME=\"\\([0-9]+\\)\" HREF=\"\\(msg[0-9]+.html\\)\"> \\([^<]+\\)</a></Strong> <EM>\\([^<]+\\)</EM>")
(luna-define-method shimbun-reply-to ((shimbun shimbun-emacs-w3m))
"emacs-w3m@namazu.org")
(luna-define-method shimbun-get-headers ((shimbun shimbun-emacs-w3m)
&optional range)
(let ((url (shimbun-index-url shimbun))
(pages (shimbun-header-index-pages range))
(count 0)
headers aux)
(catch 'stop
(shimbun-mhonarc-get-headers shimbun url headers)
(while (and (if pages (< (incf count) pages) t)
(re-search-forward
"<A \\(REL=\"next\" \\)?href=\"\\(mail[0-9]+.html\\)\">Next Index</A>"
nil t)
(not (string-equal (match-string 2) aux)))
(setq aux (match-string 2)
url (shimbun-expand-url aux url))
(erase-buffer)
(shimbun-retrieve-url url)
(shimbun-mhonarc-get-headers shimbun url headers))
headers)))
(provide 'sb-emacs-w3m)
;;; sb-emacs-w3m.el ends here
| 13255 | ;;; sb-emacs-w3m.el --- shimbun backend for emacs-w3m ml
;; Copyright (C) 2001, 2002, 2003, 2004 <NAME> <<EMAIL>>
;; Author: <NAME> <<EMAIL>>
;; Keywords: news
;; This file is a part of shimbun.
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Code:
(eval-when-compile
(require 'cl))
(require 'shimbun)
(require 'sb-mhonarc)
(luna-define-class shimbun-emacs-w3m (shimbun-mhonarc) ())
(defvar shimbun-emacs-w3m-url "http://emacs-w3m.namazu.org/ml/")
(defvar shimbun-emacs-w3m-groups '("emacs-w3m"))
(defvar shimbun-emacs-w3m-reverse-flag t)
(defvar shimbun-emacs-w3m-litemplate-regexp
"<Strong><A NAME=\"\\([0-9]+\\)\" HREF=\"\\(msg[0-9]+.html\\)\"> \\([^<]+\\)</a></Strong> <EM>\\([^<]+\\)</EM>")
(luna-define-method shimbun-reply-to ((shimbun shimbun-emacs-w3m))
"<EMAIL>")
(luna-define-method shimbun-get-headers ((shimbun shimbun-emacs-w3m)
&optional range)
(let ((url (shimbun-index-url shimbun))
(pages (shimbun-header-index-pages range))
(count 0)
headers aux)
(catch 'stop
(shimbun-mhonarc-get-headers shimbun url headers)
(while (and (if pages (< (incf count) pages) t)
(re-search-forward
"<A \\(REL=\"next\" \\)?href=\"\\(mail[0-9]+.html\\)\">Next Index</A>"
nil t)
(not (string-equal (match-string 2) aux)))
(setq aux (match-string 2)
url (shimbun-expand-url aux url))
(erase-buffer)
(shimbun-retrieve-url url)
(shimbun-mhonarc-get-headers shimbun url headers))
headers)))
(provide 'sb-emacs-w3m)
;;; sb-emacs-w3m.el ends here
| true | ;;; sb-emacs-w3m.el --- shimbun backend for emacs-w3m ml
;; Copyright (C) 2001, 2002, 2003, 2004 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: news
;; This file is a part of shimbun.
;; 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Code:
(eval-when-compile
(require 'cl))
(require 'shimbun)
(require 'sb-mhonarc)
(luna-define-class shimbun-emacs-w3m (shimbun-mhonarc) ())
(defvar shimbun-emacs-w3m-url "http://emacs-w3m.namazu.org/ml/")
(defvar shimbun-emacs-w3m-groups '("emacs-w3m"))
(defvar shimbun-emacs-w3m-reverse-flag t)
(defvar shimbun-emacs-w3m-litemplate-regexp
"<Strong><A NAME=\"\\([0-9]+\\)\" HREF=\"\\(msg[0-9]+.html\\)\"> \\([^<]+\\)</a></Strong> <EM>\\([^<]+\\)</EM>")
(luna-define-method shimbun-reply-to ((shimbun shimbun-emacs-w3m))
"PI:EMAIL:<EMAIL>END_PI")
(luna-define-method shimbun-get-headers ((shimbun shimbun-emacs-w3m)
&optional range)
(let ((url (shimbun-index-url shimbun))
(pages (shimbun-header-index-pages range))
(count 0)
headers aux)
(catch 'stop
(shimbun-mhonarc-get-headers shimbun url headers)
(while (and (if pages (< (incf count) pages) t)
(re-search-forward
"<A \\(REL=\"next\" \\)?href=\"\\(mail[0-9]+.html\\)\">Next Index</A>"
nil t)
(not (string-equal (match-string 2) aux)))
(setq aux (match-string 2)
url (shimbun-expand-url aux url))
(erase-buffer)
(shimbun-retrieve-url url)
(shimbun-mhonarc-get-headers shimbun url headers))
headers)))
(provide 'sb-emacs-w3m)
;;; sb-emacs-w3m.el ends here
|
[
{
"context": " file for Spacemacs.\n;;\n;; Copyright (c) 2012-2016 Sylvain Benner & Contributors\n;;\n;; Author: Sam Thomas <samthoma",
"end": 106,
"score": 0.999876856803894,
"start": 92,
"tag": "NAME",
"value": "Sylvain Benner"
},
{
"context": "2-2016 Sylvain Benner & Contributors\n;;\n;; Author: Sam Thomas <samthomas@samthomas>\n;; URL: https://github.com/",
"end": 146,
"score": 0.9998608827590942,
"start": 136,
"tag": "NAME",
"value": "Sam Thomas"
},
{
"context": "n Benner & Contributors\n;;\n;; Author: Sam Thomas <samthomas@samthomas>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;",
"end": 167,
"score": 0.9996030926704407,
"start": 148,
"tag": "EMAIL",
"value": "samthomas@samthomas"
},
{
"context": " <samthomas@samthomas>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;\n;; This file is not part of GNU Emac",
"end": 204,
"score": 0.8739674687385559,
"start": 196,
"tag": "USERNAME",
"value": "syl20bnr"
}
] | tools/emacs/fuse-mode/fuse-mode.el | mewbak/seashell | 72 | ;;; packages.el --- custom layer packages file for Spacemacs.
;;
;; Copyright (c) 2012-2016 Sylvain Benner & Contributors
;;
;; Author: Sam Thomas <samthomas@samthomas>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;;; Commentary:
;; See the Spacemacs documentation and FAQs for instructions on how to implement
;; a new layer:
;;
;; SPC h SPC layers RET
;;
;;
;; Briefly, each package to be installed or configured by this layer should be
;; added to `custom-packages'. Then, for each package PACKAGE:
;;
;; - If PACKAGE is not referenced by any other Spacemacs layer, define a
;; function `custom/init-PACKAGE' to load and initialize the package.
;; - Otherwise, PACKAGE is already referenced by another Spacemacs layer, so
;; define the functions `custom/pre-init-PACKAGE' and/or
;; `custom/post-init-PACKAGE' to customize the package as it is loaded.
;;; Code:
(defvar fuse-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-j" 'newline-and-indent)
map)
"Keymap for `fuse-mode'.")
(defvar fuse-mode-syntax-table
(let ((st (make-syntax-table)))
;; comments
(modify-syntax-entry ?/ ". 12b" st)
(modify-syntax-entry ?* ". 23b" st)
(modify-syntax-entry ?\n "> b" st)
;; strings
;; (modify-syntax-entry ?' "\"" st)
(modify-syntax-entry ?\" "\"" st)
st)
"Syntax table for `fuse-mode'.")
(setq fuse-font-lock-keywords
(let* (
(fuse-keywords '("decl" "def" "extern" "bank" "unroll" "shrink" "record" "let"
"if" "else" "while" "combine" "for"))
(fuse-types '("bit" "float" "bool" "view"))
(fuse-bools '("true" "false" "null"))
(fuse-keywords-regexp (regexp-opt fuse-keywords 'words))
(fuse-types-regexp (regexp-opt fuse-types 'words))
(fuse-bools-regexp (regexp-opt fuse-bools 'word)))
`(
(,fuse-keywords-regexp . (1 font-lock-keyword-face))
(,fuse-types-regexp . (1 font-lock-type-face))
(,fuse-bools-regexp . (1 font-lock-constant-face))
)))
;;; Indentation
(defvar fuse-indent-level 2)
(defun fuse-count-back ()
(let ((count 0)
(not-top t))
(save-excursion
(end-of-line)
(forward-char -1)
(if (looking-at "{")
(forward-char -1))
(while not-top
(if (looking-at "}")
(setq count (- count 1)))
(if (looking-at "{")
(setq count (+ count 1)))
(forward-char -1)
(if (bobp)
(setq not-top nil)))
count)))
(defun fuse-print-back ()
(interactive)
(message "Back: %s" (fuse-count-back)))
(defun fuse-indent-line ()
(interactive)
(end-of-line)
(indent-line-to (* fuse-indent-level (fuse-count-back))))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.fuse\\'" . fuse-mode))
(add-to-list 'auto-mode-alist '("\\.ifuse\\'" . fuse-mode))
(define-derived-mode fuse-mode prog-mode "Fuse Mode"
"A major mode for editing Fuse source files."
:syntax-table fuse-mode-syntax-table
(setq-local comment-start "// ")
(setq-local comment-end "")
(setq-local comment-start-skip "//+\\s-*")
(setq-local font-lock-defaults
'((fuse-font-lock-keywords)))
(setq-local indent-line-function 'fuse-indent-line))
(provide 'fuse-mode)
;;; packages.el ends here
| 27754 | ;;; packages.el --- custom layer packages file for Spacemacs.
;;
;; Copyright (c) 2012-2016 <NAME> & Contributors
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;;; Commentary:
;; See the Spacemacs documentation and FAQs for instructions on how to implement
;; a new layer:
;;
;; SPC h SPC layers RET
;;
;;
;; Briefly, each package to be installed or configured by this layer should be
;; added to `custom-packages'. Then, for each package PACKAGE:
;;
;; - If PACKAGE is not referenced by any other Spacemacs layer, define a
;; function `custom/init-PACKAGE' to load and initialize the package.
;; - Otherwise, PACKAGE is already referenced by another Spacemacs layer, so
;; define the functions `custom/pre-init-PACKAGE' and/or
;; `custom/post-init-PACKAGE' to customize the package as it is loaded.
;;; Code:
(defvar fuse-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-j" 'newline-and-indent)
map)
"Keymap for `fuse-mode'.")
(defvar fuse-mode-syntax-table
(let ((st (make-syntax-table)))
;; comments
(modify-syntax-entry ?/ ". 12b" st)
(modify-syntax-entry ?* ". 23b" st)
(modify-syntax-entry ?\n "> b" st)
;; strings
;; (modify-syntax-entry ?' "\"" st)
(modify-syntax-entry ?\" "\"" st)
st)
"Syntax table for `fuse-mode'.")
(setq fuse-font-lock-keywords
(let* (
(fuse-keywords '("decl" "def" "extern" "bank" "unroll" "shrink" "record" "let"
"if" "else" "while" "combine" "for"))
(fuse-types '("bit" "float" "bool" "view"))
(fuse-bools '("true" "false" "null"))
(fuse-keywords-regexp (regexp-opt fuse-keywords 'words))
(fuse-types-regexp (regexp-opt fuse-types 'words))
(fuse-bools-regexp (regexp-opt fuse-bools 'word)))
`(
(,fuse-keywords-regexp . (1 font-lock-keyword-face))
(,fuse-types-regexp . (1 font-lock-type-face))
(,fuse-bools-regexp . (1 font-lock-constant-face))
)))
;;; Indentation
(defvar fuse-indent-level 2)
(defun fuse-count-back ()
(let ((count 0)
(not-top t))
(save-excursion
(end-of-line)
(forward-char -1)
(if (looking-at "{")
(forward-char -1))
(while not-top
(if (looking-at "}")
(setq count (- count 1)))
(if (looking-at "{")
(setq count (+ count 1)))
(forward-char -1)
(if (bobp)
(setq not-top nil)))
count)))
(defun fuse-print-back ()
(interactive)
(message "Back: %s" (fuse-count-back)))
(defun fuse-indent-line ()
(interactive)
(end-of-line)
(indent-line-to (* fuse-indent-level (fuse-count-back))))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.fuse\\'" . fuse-mode))
(add-to-list 'auto-mode-alist '("\\.ifuse\\'" . fuse-mode))
(define-derived-mode fuse-mode prog-mode "Fuse Mode"
"A major mode for editing Fuse source files."
:syntax-table fuse-mode-syntax-table
(setq-local comment-start "// ")
(setq-local comment-end "")
(setq-local comment-start-skip "//+\\s-*")
(setq-local font-lock-defaults
'((fuse-font-lock-keywords)))
(setq-local indent-line-function 'fuse-indent-line))
(provide 'fuse-mode)
;;; packages.el ends here
| true | ;;; packages.el --- custom layer packages file for Spacemacs.
;;
;; Copyright (c) 2012-2016 PI:NAME:<NAME>END_PI & Contributors
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;;; Commentary:
;; See the Spacemacs documentation and FAQs for instructions on how to implement
;; a new layer:
;;
;; SPC h SPC layers RET
;;
;;
;; Briefly, each package to be installed or configured by this layer should be
;; added to `custom-packages'. Then, for each package PACKAGE:
;;
;; - If PACKAGE is not referenced by any other Spacemacs layer, define a
;; function `custom/init-PACKAGE' to load and initialize the package.
;; - Otherwise, PACKAGE is already referenced by another Spacemacs layer, so
;; define the functions `custom/pre-init-PACKAGE' and/or
;; `custom/post-init-PACKAGE' to customize the package as it is loaded.
;;; Code:
(defvar fuse-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-j" 'newline-and-indent)
map)
"Keymap for `fuse-mode'.")
(defvar fuse-mode-syntax-table
(let ((st (make-syntax-table)))
;; comments
(modify-syntax-entry ?/ ". 12b" st)
(modify-syntax-entry ?* ". 23b" st)
(modify-syntax-entry ?\n "> b" st)
;; strings
;; (modify-syntax-entry ?' "\"" st)
(modify-syntax-entry ?\" "\"" st)
st)
"Syntax table for `fuse-mode'.")
(setq fuse-font-lock-keywords
(let* (
(fuse-keywords '("decl" "def" "extern" "bank" "unroll" "shrink" "record" "let"
"if" "else" "while" "combine" "for"))
(fuse-types '("bit" "float" "bool" "view"))
(fuse-bools '("true" "false" "null"))
(fuse-keywords-regexp (regexp-opt fuse-keywords 'words))
(fuse-types-regexp (regexp-opt fuse-types 'words))
(fuse-bools-regexp (regexp-opt fuse-bools 'word)))
`(
(,fuse-keywords-regexp . (1 font-lock-keyword-face))
(,fuse-types-regexp . (1 font-lock-type-face))
(,fuse-bools-regexp . (1 font-lock-constant-face))
)))
;;; Indentation
(defvar fuse-indent-level 2)
(defun fuse-count-back ()
(let ((count 0)
(not-top t))
(save-excursion
(end-of-line)
(forward-char -1)
(if (looking-at "{")
(forward-char -1))
(while not-top
(if (looking-at "}")
(setq count (- count 1)))
(if (looking-at "{")
(setq count (+ count 1)))
(forward-char -1)
(if (bobp)
(setq not-top nil)))
count)))
(defun fuse-print-back ()
(interactive)
(message "Back: %s" (fuse-count-back)))
(defun fuse-indent-line ()
(interactive)
(end-of-line)
(indent-line-to (* fuse-indent-level (fuse-count-back))))
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.fuse\\'" . fuse-mode))
(add-to-list 'auto-mode-alist '("\\.ifuse\\'" . fuse-mode))
(define-derived-mode fuse-mode prog-mode "Fuse Mode"
"A major mode for editing Fuse source files."
:syntax-table fuse-mode-syntax-table
(setq-local comment-start "// ")
(setq-local comment-end "")
(setq-local comment-start-skip "//+\\s-*")
(setq-local font-lock-defaults
'((fuse-font-lock-keywords)))
(setq-local indent-line-function 'fuse-indent-line))
(provide 'fuse-mode)
;;; packages.el ends here
|
[
{
"context": "97 Free Software Foundation, Inc.\n;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991\n\n;; Author: Mike Wi",
"end": 143,
"score": 0.9998943209648132,
"start": 130,
"tag": "NAME",
"value": "Mike Williams"
},
{
"context": " Foundation, Inc.\n;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991\n\n;; Author: Mike Williams <mike-w@cs.aukuni",
"end": 167,
"score": 0.999934732913971,
"start": 145,
"tag": "EMAIL",
"value": "mike-w@cs.aukuni.ac.nz"
},
{
"context": "Williams <mike-w@cs.aukuni.ac.nz> 1991\n\n;; Author: Mike Williams <mike-w@cs.aukuni.ac.nz>\n;; Maintainer: XEmacs De",
"end": 199,
"score": 0.9998952746391296,
"start": 186,
"tag": "NAME",
"value": "Mike Williams"
},
{
"context": "@cs.aukuni.ac.nz> 1991\n\n;; Author: Mike Williams <mike-w@cs.aukuni.ac.nz>\n;; Maintainer: XEmacs Development Team\n;; Keywor",
"end": 223,
"score": 0.9999334812164307,
"start": 201,
"tag": "EMAIL",
"value": "mike-w@cs.aukuni.ac.nz"
},
{
"context": " Completion on a search path\n;; Author : Mike Williams <mike-w@cs.aukuni.ac.nz>\n;; Created On : Sat",
"end": 1281,
"score": 0.9998964071273804,
"start": 1268,
"tag": "NAME",
"value": "Mike Williams"
},
{
"context": "a search path\n;; Author : Mike Williams <mike-w@cs.aukuni.ac.nz>\n;; Created On : Sat Apr 20 17:47:21 1991\n;;",
"end": 1305,
"score": 0.9999330043792725,
"start": 1283,
"tag": "EMAIL",
"value": "mike-w@cs.aukuni.ac.nz"
},
{
"context": " : Sat Apr 20 17:47:21 1991\n;; Last Modified By: Heiko M|nkel <muenkel@tnt.uni-hannover.de>\n;; Additional XEmac",
"end": 1386,
"score": 0.9998874664306641,
"start": 1374,
"tag": "NAME",
"value": "Heiko M|nkel"
},
{
"context": " 17:47:21 1991\n;; Last Modified By: Heiko M|nkel <muenkel@tnt.uni-hannover.de>\n;; Additional XEmacs integration By: Chuck Thomp",
"end": 1415,
"score": 0.9999257922172546,
"start": 1388,
"tag": "EMAIL",
"value": "muenkel@tnt.uni-hannover.de"
},
{
"context": "-hannover.de>\n;; Additional XEmacs integration By: Chuck Thompson <cthomp@cs.uiuc.edu>\n;; Last Modified On: Thu Jul",
"end": 1468,
"score": 0.9998947381973267,
"start": 1454,
"tag": "NAME",
"value": "Chuck Thompson"
},
{
"context": "Additional XEmacs integration By: Chuck Thompson <cthomp@cs.uiuc.edu>\n;; Last Modified On: Thu Jul 1 14:23:00 1994\n;; ",
"end": 1488,
"score": 0.9999305605888367,
"start": 1470,
"tag": "EMAIL",
"value": "cthomp@cs.uiuc.edu"
},
{
"context": "umped if this file is changed.\n;;\n;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991\n;;\n;; Keywords: uti",
"end": 1752,
"score": 0.9997992515563965,
"start": 1739,
"tag": "NAME",
"value": "Mike Williams"
},
{
"context": "le is changed.\n;;\n;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991\n;;\n;; Keywords: utility, lisp\n\n;; Many than",
"end": 1776,
"score": 0.9999355673789978,
"start": 1754,
"tag": "EMAIL",
"value": "mike-w@cs.aukuni.ac.nz"
},
{
"context": "1\n;;\n;; Keywords: utility, lisp\n\n;; Many thanks to Hallvard Furuseth <hallvard@ifi.uio.no> for his\n;; helpful suggesti",
"end": 1849,
"score": 0.9998778700828552,
"start": 1832,
"tag": "NAME",
"value": "Hallvard Furuseth"
},
{
"context": "ility, lisp\n\n;; Many thanks to Hallvard Furuseth <hallvard@ifi.uio.no> for his\n;; helpful suggestions.\n\n;; The function",
"end": 1870,
"score": 0.9999310374259949,
"start": 1851,
"tag": "EMAIL",
"value": "hallvard@ifi.uio.no"
},
{
"context": "ary))\n\n;;=== find-library with completion (Author: Heiko Muenkel) ===================\n\n(defun find-library (librar",
"end": 11561,
"score": 0.9998492002487183,
"start": 11548,
"tag": "NAME",
"value": "Heiko Muenkel"
}
] | emacs/lib-complete.el | mernst/plume-lib-check-index-upstream-jsantino | 0 | ;;; lib-complete.el --- Completion on the lisp search path
;; Copyright (C) 1997 Free Software Foundation, Inc.
;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991
;; Author: Mike Williams <mike-w@cs.aukuni.ac.nz>
;; Maintainer: XEmacs Development Team
;; Keywords: lisp, extensions
;; Created: Sat Apr 20 17:47:21 1991
;; This file is part of XEmacs.
;; XEmacs 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.
;; XEmacs 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 XEmacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Synched up with: Not in FSF.
;;; Commentary:
;; ========================================================================
;; lib-complete.el -- Completion on a search path
;; Author : Mike Williams <mike-w@cs.aukuni.ac.nz>
;; Created On : Sat Apr 20 17:47:21 1991
;; Last Modified By: Heiko M|nkel <muenkel@tnt.uni-hannover.de>
;; Additional XEmacs integration By: Chuck Thompson <cthomp@cs.uiuc.edu>
;; Last Modified On: Thu Jul 1 14:23:00 1994
;; RCS Info : $Revision: 1.2 $ $Locker: $
;; ========================================================================
;; NOTE: XEmacs must be redumped if this file is changed.
;;
;; Copyright (C) Mike Williams <mike-w@cs.aukuni.ac.nz> 1991
;;
;; Keywords: utility, lisp
;; Many thanks to Hallvard Furuseth <hallvard@ifi.uio.no> for his
;; helpful suggestions.
;; The function locate-file is removed, because of its incompatibility
;; with the buildin function of the lemacs 19.10 (Heiko M|nkel).
;; There is now the new function find-library in this package.
;;; ChangeLog:
;; 4/26/97: sb Mule-ize.
;;; Code:
;;=== Determine completions for filename in search path ===================
(defun library-all-completions (FILE SEARCH-PATH &optional FULL FAST)
"Return all completions for FILE in any directory on SEARCH-PATH.
If optional third argument FULL is non-nil, returned pathnames should be
absolute rather than relative to some directory on the SEARCH-PATH.
If optional fourth argument FAST is non-nil, don't sort the completions,
or remove duplicates."
(setq FILE (or FILE ""))
(if (file-name-absolute-p FILE)
;; It's an absolute file name, so don't need SEARCH-PATH
(progn
(setq FILE (expand-file-name FILE))
(file-name-all-completions
(file-name-nondirectory FILE) (file-name-directory FILE)))
(let ((subdir (file-name-directory FILE))
(file (file-name-nondirectory FILE))
all-completions)
;; Make list of completions in each directory on SEARCH-PATH
(while SEARCH-PATH
(let* ((dir (concat (file-name-as-directory
(expand-file-name (car SEARCH-PATH)))
subdir))
(dir-prefix (if FULL dir subdir)))
(if (file-directory-p dir)
(let ((subdir-completions
(file-name-all-completions file dir)))
(while subdir-completions
(setq all-completions
(cons (concat dir-prefix (car subdir-completions))
all-completions))
(setq subdir-completions (cdr subdir-completions))))))
(setq SEARCH-PATH (cdr SEARCH-PATH)))
(if FAST all-completions
(let ((sorted (nreverse (sort all-completions 'string<)))
compressed)
(while sorted
(if (equal (car sorted) (car compressed)) nil
(setq compressed (cons (car sorted) compressed)))
(setq sorted (cdr sorted)))
compressed)))))
;;=== Utilities ===========================================================
(defmacro progn-with-message (MESSAGE &rest FORMS)
"(progn-with-message MESSAGE FORMS ...)
Display MESSAGE and evaluate FORMS, returning value of the last one."
;; based on Hallvard Furuseth's funcall-with-message
`(if (eq (selected-window) (minibuffer-window))
(save-excursion
(goto-char (point-max))
(let ((orig-pmax (point-max)))
(unwind-protect
(progn
(insert " " (, MESSAGE)) (goto-char orig-pmax)
(sit-for 0) ; Redisplay
,@FORMS)
(delete-region orig-pmax (point-max)))))
(prog2
(message "%s" (, MESSAGE))
(progn ,@FORMS)
(message ""))))
;; #+infodock (defalias 'lib-funcall-with-msg 'progn-with-message)
(put 'progn-with-message 'lisp-indent-hook 1)
;; #+infodock (put 'lib-funcall-with-message 'lisp-indent-hook 1)
;;=== Completion caching ==================================================
(defconst lib-complete:cache nil
"Used within read-library and read-library-internal to prevent
costly repeated calls to library-all-completions.
Format is a list of lists of the form
([<path> <subdir>] <cache-record> <cache-record> ...)
where each <cache-record> has the form
(<root> <modtimes> <completion-table>)")
;; #+infodock (defvaralias 'lib-completions 'lib-complete:cache)
(defun lib-complete:better-root (ROOT1 ROOT2)
"Return non-nil if ROOT1 is a superset of ROOT2."
(and (equal (file-name-directory ROOT1) (file-name-directory ROOT2))
(string-match
(concat "^" (regexp-quote (file-name-nondirectory ROOT1)))
ROOT2)))
(defun lib-complete:get-completion-table (FILE PATH FILTER)
(let* ((subdir (file-name-directory FILE))
(root (file-name-nondirectory FILE))
(PATH
(mapcar
(function (lambda (dir) (file-name-as-directory
(expand-file-name (or dir "")))))
PATH))
(key (vector PATH subdir FILTER))
(real-dirs
(if subdir
(mapcar (function (lambda (dir) (concat dir subdir))) PATH)
PATH))
(path-modtimes
(mapcar
(function (lambda (fn) (if fn (nth 5 (file-attributes fn)))))
real-dirs))
(cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry)))
;; Look for cached entry
(catch 'table
(while cache-records
(if (and
(lib-complete:better-root (nth 0 (car cache-records)) root)
(equal (nth 1 (car cache-records)) path-modtimes))
(throw 'table (nth 2 (car cache-records))))
(setq cache-records (cdr cache-records)))
;; Otherwise build completions
(let ((completion-list
(progn-with-message "(building completion table...)"
(library-all-completions FILE PATH nil 'fast)))
(completion-table (make-vector 127 0)))
(while completion-list
(let ((completion
(if (or (not FILTER)
(file-directory-p (car completion-list)))
(car completion-list)
(funcall FILTER (car completion-list)))))
(if completion
(intern completion completion-table)))
(setq completion-list (cdr completion-list)))
;; Cache the completions
(lib-complete:cache-completions key root
path-modtimes completion-table)
completion-table))))
(defvar lib-complete:max-cache-size 40
"*Maximum number of search paths which are cached.")
(defun lib-complete:cache-completions (key root modtimes table)
(let* ((cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry))
(new-cache-records (list (list root modtimes table))))
(if (not cache-entry) nil
;; Remove old cache entry
(setq lib-complete:cache (delq cache-entry lib-complete:cache))
;; Copy non-redundant entries from old cache entry
(while cache-records
(if (or (equal root (nth 0 (car cache-records)))
(lib-complete:better-root root (nth 0 (car cache-records))))
nil
(setq new-cache-records
(cons (car cache-records) new-cache-records)))
(setq cache-records (cdr cache-records))))
;; Add entry to front of cache
(setq lib-complete:cache
(cons (cons key (nreverse new-cache-records)) lib-complete:cache))
;; Trim cache
(let ((tail (nthcdr lib-complete:max-cache-size lib-complete:cache)))
(if tail (setcdr tail nil)))))
;;=== Read a filename, with completion in a search path ===================
(defun read-library-internal (FILE FILTER FLAG)
"Don't call this."
;; Relies on read-library-internal-search-path being let-bound
(let ((completion-table
(lib-complete:get-completion-table
FILE read-library-internal-search-path FILTER)))
(cond
((not completion-table) nil)
;; Completion table is filtered before use, so the PREDICATE
;; argument is redundant.
((eq FLAG nil) (try-completion FILE completion-table nil))
((eq FLAG t) (all-completions FILE completion-table nil))
((eq FLAG 'lambda) (and (intern-soft FILE completion-table) t))
)))
(defun read-library (PROMPT SEARCH-PATH &optional DEFAULT MUST-MATCH
FULL FILTER)
"Read library name, prompting with PROMPT and completing in directories
from SEARCH-PATH. A nil in the search path represents the current
directory. Completions for a given search-path are cached, with the
cache being invalidated whenever one of the directories on the path changes.
Default to DEFAULT if user enters a null string.
Optional fourth arg MUST-MATCH non-nil means require existing file's name.
Non-nil and non-t means also require confirmation after completion.
Optional fifth argument FULL non-nil causes a full pathname, rather than a
relative pathname, to be returned. Note that FULL implies MUST-MATCH.
Optional sixth argument FILTER can be used to provide a function to
filter the completions. This function is passed the filename, and should
return a transformed filename (possibly a null transformation) or nil,
indicating that the filename should not be included in the completions."
(let* ((read-library-internal-search-path SEARCH-PATH)
(library (completing-read PROMPT 'read-library-internal
FILTER (or MUST-MATCH FULL) nil)))
(cond
((equal library "") DEFAULT)
(FULL (locate-file library read-library-internal-search-path
;; decompression doesn't work with Mule -slb
(if (featurep 'mule)
".el:.elc"
".el:.el.gz:.elc")))
(t library))))
;; NOTE: as a special case, read-library may be used to read a filename
;; relative to the current directory, returning a *relative* pathname
;; (read-file-name returns a full pathname).
;;
;; eg. (read-library "Local header: " '(nil) nil)
(defun get-library-path ()
"Front end to read-library"
(read-library "Find Library file: " load-path nil t t
(function (lambda (fn)
(cond
;; decompression doesn't work with mule -slb
((string-match (if (featurep 'mule)
"\\.el$"
"\\.el\\(\\.gz\\)?$") fn)
(substring fn 0 (match-beginning 0))))))
))
;; FSF Emacs version
(defun get-library-path ()
(let* ((short-lib (completing-read "Find Library file: " 'library-complete))
(full-path (locate-library short-lib)))
(if (string-match "\\.elc$" full-path)
(let ((non-elc (substring full-path 0 (1- (length full-path)))))
(if (file-exists-p non-elc)
non-elc
full-path))
full-path)))
;;=== Replacement for load-library with completion ========================
(defun load-library (library)
"Load the library named LIBRARY.
This is an interface to the function `load'."
(interactive
(list (read-library "Load Library: " load-path nil nil nil
(function (lambda (fn)
(cond
((string-match "\\.elc?$" fn)
(substring fn 0 (match-beginning 0))))))
)))
(load library))
;;=== find-library with completion (Author: Heiko Muenkel) ===================
(defun find-library (library &optional codesys)
"Find and edit the source for the library named LIBRARY.
The extension of the LIBRARY must be omitted.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file library codesys)
(find-file library)
)
(defun find-library-other-window (library &optional codesys)
"Load the library named LIBRARY in another window.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-window library codesys)
(find-file-other-window library)
)
;; #+infodock (defalias 'lib-edit-other-window 'find-library-other-window)
(defun find-library-other-frame (library &optional codesys)
"Load the library named LIBRARY in a newly-created frame.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-frame library codesys)
(find-file-other-frame library)
)
; This conflicts with an existing binding
;(define-key global-map "\C-xl" 'find-library)
(define-key global-map "\C-x4l" 'find-library-other-window)
(define-key global-map "\C-x5l" 'find-library-other-frame)
;; #+infodock (defalias 'lib-where-is 'locate-library)
;; #+infodock (provide 'lib)
(provide 'lib-complete)
;;; lib-complete.el ends here
| 8919 | ;;; lib-complete.el --- Completion on the lisp search path
;; Copyright (C) 1997 Free Software Foundation, Inc.
;; Copyright (C) <NAME> <<EMAIL>> 1991
;; Author: <NAME> <<EMAIL>>
;; Maintainer: XEmacs Development Team
;; Keywords: lisp, extensions
;; Created: Sat Apr 20 17:47:21 1991
;; This file is part of XEmacs.
;; XEmacs 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.
;; XEmacs 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 XEmacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Synched up with: Not in FSF.
;;; Commentary:
;; ========================================================================
;; lib-complete.el -- Completion on a search path
;; Author : <NAME> <<EMAIL>>
;; Created On : Sat Apr 20 17:47:21 1991
;; Last Modified By: <NAME> <<EMAIL>>
;; Additional XEmacs integration By: <NAME> <<EMAIL>>
;; Last Modified On: Thu Jul 1 14:23:00 1994
;; RCS Info : $Revision: 1.2 $ $Locker: $
;; ========================================================================
;; NOTE: XEmacs must be redumped if this file is changed.
;;
;; Copyright (C) <NAME> <<EMAIL>> 1991
;;
;; Keywords: utility, lisp
;; Many thanks to <NAME> <<EMAIL>> for his
;; helpful suggestions.
;; The function locate-file is removed, because of its incompatibility
;; with the buildin function of the lemacs 19.10 (Heiko M|nkel).
;; There is now the new function find-library in this package.
;;; ChangeLog:
;; 4/26/97: sb Mule-ize.
;;; Code:
;;=== Determine completions for filename in search path ===================
(defun library-all-completions (FILE SEARCH-PATH &optional FULL FAST)
"Return all completions for FILE in any directory on SEARCH-PATH.
If optional third argument FULL is non-nil, returned pathnames should be
absolute rather than relative to some directory on the SEARCH-PATH.
If optional fourth argument FAST is non-nil, don't sort the completions,
or remove duplicates."
(setq FILE (or FILE ""))
(if (file-name-absolute-p FILE)
;; It's an absolute file name, so don't need SEARCH-PATH
(progn
(setq FILE (expand-file-name FILE))
(file-name-all-completions
(file-name-nondirectory FILE) (file-name-directory FILE)))
(let ((subdir (file-name-directory FILE))
(file (file-name-nondirectory FILE))
all-completions)
;; Make list of completions in each directory on SEARCH-PATH
(while SEARCH-PATH
(let* ((dir (concat (file-name-as-directory
(expand-file-name (car SEARCH-PATH)))
subdir))
(dir-prefix (if FULL dir subdir)))
(if (file-directory-p dir)
(let ((subdir-completions
(file-name-all-completions file dir)))
(while subdir-completions
(setq all-completions
(cons (concat dir-prefix (car subdir-completions))
all-completions))
(setq subdir-completions (cdr subdir-completions))))))
(setq SEARCH-PATH (cdr SEARCH-PATH)))
(if FAST all-completions
(let ((sorted (nreverse (sort all-completions 'string<)))
compressed)
(while sorted
(if (equal (car sorted) (car compressed)) nil
(setq compressed (cons (car sorted) compressed)))
(setq sorted (cdr sorted)))
compressed)))))
;;=== Utilities ===========================================================
(defmacro progn-with-message (MESSAGE &rest FORMS)
"(progn-with-message MESSAGE FORMS ...)
Display MESSAGE and evaluate FORMS, returning value of the last one."
;; based on Hallvard Furuseth's funcall-with-message
`(if (eq (selected-window) (minibuffer-window))
(save-excursion
(goto-char (point-max))
(let ((orig-pmax (point-max)))
(unwind-protect
(progn
(insert " " (, MESSAGE)) (goto-char orig-pmax)
(sit-for 0) ; Redisplay
,@FORMS)
(delete-region orig-pmax (point-max)))))
(prog2
(message "%s" (, MESSAGE))
(progn ,@FORMS)
(message ""))))
;; #+infodock (defalias 'lib-funcall-with-msg 'progn-with-message)
(put 'progn-with-message 'lisp-indent-hook 1)
;; #+infodock (put 'lib-funcall-with-message 'lisp-indent-hook 1)
;;=== Completion caching ==================================================
(defconst lib-complete:cache nil
"Used within read-library and read-library-internal to prevent
costly repeated calls to library-all-completions.
Format is a list of lists of the form
([<path> <subdir>] <cache-record> <cache-record> ...)
where each <cache-record> has the form
(<root> <modtimes> <completion-table>)")
;; #+infodock (defvaralias 'lib-completions 'lib-complete:cache)
(defun lib-complete:better-root (ROOT1 ROOT2)
"Return non-nil if ROOT1 is a superset of ROOT2."
(and (equal (file-name-directory ROOT1) (file-name-directory ROOT2))
(string-match
(concat "^" (regexp-quote (file-name-nondirectory ROOT1)))
ROOT2)))
(defun lib-complete:get-completion-table (FILE PATH FILTER)
(let* ((subdir (file-name-directory FILE))
(root (file-name-nondirectory FILE))
(PATH
(mapcar
(function (lambda (dir) (file-name-as-directory
(expand-file-name (or dir "")))))
PATH))
(key (vector PATH subdir FILTER))
(real-dirs
(if subdir
(mapcar (function (lambda (dir) (concat dir subdir))) PATH)
PATH))
(path-modtimes
(mapcar
(function (lambda (fn) (if fn (nth 5 (file-attributes fn)))))
real-dirs))
(cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry)))
;; Look for cached entry
(catch 'table
(while cache-records
(if (and
(lib-complete:better-root (nth 0 (car cache-records)) root)
(equal (nth 1 (car cache-records)) path-modtimes))
(throw 'table (nth 2 (car cache-records))))
(setq cache-records (cdr cache-records)))
;; Otherwise build completions
(let ((completion-list
(progn-with-message "(building completion table...)"
(library-all-completions FILE PATH nil 'fast)))
(completion-table (make-vector 127 0)))
(while completion-list
(let ((completion
(if (or (not FILTER)
(file-directory-p (car completion-list)))
(car completion-list)
(funcall FILTER (car completion-list)))))
(if completion
(intern completion completion-table)))
(setq completion-list (cdr completion-list)))
;; Cache the completions
(lib-complete:cache-completions key root
path-modtimes completion-table)
completion-table))))
(defvar lib-complete:max-cache-size 40
"*Maximum number of search paths which are cached.")
(defun lib-complete:cache-completions (key root modtimes table)
(let* ((cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry))
(new-cache-records (list (list root modtimes table))))
(if (not cache-entry) nil
;; Remove old cache entry
(setq lib-complete:cache (delq cache-entry lib-complete:cache))
;; Copy non-redundant entries from old cache entry
(while cache-records
(if (or (equal root (nth 0 (car cache-records)))
(lib-complete:better-root root (nth 0 (car cache-records))))
nil
(setq new-cache-records
(cons (car cache-records) new-cache-records)))
(setq cache-records (cdr cache-records))))
;; Add entry to front of cache
(setq lib-complete:cache
(cons (cons key (nreverse new-cache-records)) lib-complete:cache))
;; Trim cache
(let ((tail (nthcdr lib-complete:max-cache-size lib-complete:cache)))
(if tail (setcdr tail nil)))))
;;=== Read a filename, with completion in a search path ===================
(defun read-library-internal (FILE FILTER FLAG)
"Don't call this."
;; Relies on read-library-internal-search-path being let-bound
(let ((completion-table
(lib-complete:get-completion-table
FILE read-library-internal-search-path FILTER)))
(cond
((not completion-table) nil)
;; Completion table is filtered before use, so the PREDICATE
;; argument is redundant.
((eq FLAG nil) (try-completion FILE completion-table nil))
((eq FLAG t) (all-completions FILE completion-table nil))
((eq FLAG 'lambda) (and (intern-soft FILE completion-table) t))
)))
(defun read-library (PROMPT SEARCH-PATH &optional DEFAULT MUST-MATCH
FULL FILTER)
"Read library name, prompting with PROMPT and completing in directories
from SEARCH-PATH. A nil in the search path represents the current
directory. Completions for a given search-path are cached, with the
cache being invalidated whenever one of the directories on the path changes.
Default to DEFAULT if user enters a null string.
Optional fourth arg MUST-MATCH non-nil means require existing file's name.
Non-nil and non-t means also require confirmation after completion.
Optional fifth argument FULL non-nil causes a full pathname, rather than a
relative pathname, to be returned. Note that FULL implies MUST-MATCH.
Optional sixth argument FILTER can be used to provide a function to
filter the completions. This function is passed the filename, and should
return a transformed filename (possibly a null transformation) or nil,
indicating that the filename should not be included in the completions."
(let* ((read-library-internal-search-path SEARCH-PATH)
(library (completing-read PROMPT 'read-library-internal
FILTER (or MUST-MATCH FULL) nil)))
(cond
((equal library "") DEFAULT)
(FULL (locate-file library read-library-internal-search-path
;; decompression doesn't work with Mule -slb
(if (featurep 'mule)
".el:.elc"
".el:.el.gz:.elc")))
(t library))))
;; NOTE: as a special case, read-library may be used to read a filename
;; relative to the current directory, returning a *relative* pathname
;; (read-file-name returns a full pathname).
;;
;; eg. (read-library "Local header: " '(nil) nil)
(defun get-library-path ()
"Front end to read-library"
(read-library "Find Library file: " load-path nil t t
(function (lambda (fn)
(cond
;; decompression doesn't work with mule -slb
((string-match (if (featurep 'mule)
"\\.el$"
"\\.el\\(\\.gz\\)?$") fn)
(substring fn 0 (match-beginning 0))))))
))
;; FSF Emacs version
(defun get-library-path ()
(let* ((short-lib (completing-read "Find Library file: " 'library-complete))
(full-path (locate-library short-lib)))
(if (string-match "\\.elc$" full-path)
(let ((non-elc (substring full-path 0 (1- (length full-path)))))
(if (file-exists-p non-elc)
non-elc
full-path))
full-path)))
;;=== Replacement for load-library with completion ========================
(defun load-library (library)
"Load the library named LIBRARY.
This is an interface to the function `load'."
(interactive
(list (read-library "Load Library: " load-path nil nil nil
(function (lambda (fn)
(cond
((string-match "\\.elc?$" fn)
(substring fn 0 (match-beginning 0))))))
)))
(load library))
;;=== find-library with completion (Author: <NAME>) ===================
(defun find-library (library &optional codesys)
"Find and edit the source for the library named LIBRARY.
The extension of the LIBRARY must be omitted.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file library codesys)
(find-file library)
)
(defun find-library-other-window (library &optional codesys)
"Load the library named LIBRARY in another window.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-window library codesys)
(find-file-other-window library)
)
;; #+infodock (defalias 'lib-edit-other-window 'find-library-other-window)
(defun find-library-other-frame (library &optional codesys)
"Load the library named LIBRARY in a newly-created frame.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-frame library codesys)
(find-file-other-frame library)
)
; This conflicts with an existing binding
;(define-key global-map "\C-xl" 'find-library)
(define-key global-map "\C-x4l" 'find-library-other-window)
(define-key global-map "\C-x5l" 'find-library-other-frame)
;; #+infodock (defalias 'lib-where-is 'locate-library)
;; #+infodock (provide 'lib)
(provide 'lib-complete)
;;; lib-complete.el ends here
| true | ;;; lib-complete.el --- Completion on the lisp search path
;; Copyright (C) 1997 Free Software Foundation, Inc.
;; Copyright (C) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> 1991
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: XEmacs Development Team
;; Keywords: lisp, extensions
;; Created: Sat Apr 20 17:47:21 1991
;; This file is part of XEmacs.
;; XEmacs 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.
;; XEmacs 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 XEmacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Synched up with: Not in FSF.
;;; Commentary:
;; ========================================================================
;; lib-complete.el -- Completion on a search path
;; Author : PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created On : Sat Apr 20 17:47:21 1991
;; Last Modified By: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Additional XEmacs integration By: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Last Modified On: Thu Jul 1 14:23:00 1994
;; RCS Info : $Revision: 1.2 $ $Locker: $
;; ========================================================================
;; NOTE: XEmacs must be redumped if this file is changed.
;;
;; Copyright (C) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> 1991
;;
;; Keywords: utility, lisp
;; Many thanks to PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> for his
;; helpful suggestions.
;; The function locate-file is removed, because of its incompatibility
;; with the buildin function of the lemacs 19.10 (Heiko M|nkel).
;; There is now the new function find-library in this package.
;;; ChangeLog:
;; 4/26/97: sb Mule-ize.
;;; Code:
;;=== Determine completions for filename in search path ===================
(defun library-all-completions (FILE SEARCH-PATH &optional FULL FAST)
"Return all completions for FILE in any directory on SEARCH-PATH.
If optional third argument FULL is non-nil, returned pathnames should be
absolute rather than relative to some directory on the SEARCH-PATH.
If optional fourth argument FAST is non-nil, don't sort the completions,
or remove duplicates."
(setq FILE (or FILE ""))
(if (file-name-absolute-p FILE)
;; It's an absolute file name, so don't need SEARCH-PATH
(progn
(setq FILE (expand-file-name FILE))
(file-name-all-completions
(file-name-nondirectory FILE) (file-name-directory FILE)))
(let ((subdir (file-name-directory FILE))
(file (file-name-nondirectory FILE))
all-completions)
;; Make list of completions in each directory on SEARCH-PATH
(while SEARCH-PATH
(let* ((dir (concat (file-name-as-directory
(expand-file-name (car SEARCH-PATH)))
subdir))
(dir-prefix (if FULL dir subdir)))
(if (file-directory-p dir)
(let ((subdir-completions
(file-name-all-completions file dir)))
(while subdir-completions
(setq all-completions
(cons (concat dir-prefix (car subdir-completions))
all-completions))
(setq subdir-completions (cdr subdir-completions))))))
(setq SEARCH-PATH (cdr SEARCH-PATH)))
(if FAST all-completions
(let ((sorted (nreverse (sort all-completions 'string<)))
compressed)
(while sorted
(if (equal (car sorted) (car compressed)) nil
(setq compressed (cons (car sorted) compressed)))
(setq sorted (cdr sorted)))
compressed)))))
;;=== Utilities ===========================================================
(defmacro progn-with-message (MESSAGE &rest FORMS)
"(progn-with-message MESSAGE FORMS ...)
Display MESSAGE and evaluate FORMS, returning value of the last one."
;; based on Hallvard Furuseth's funcall-with-message
`(if (eq (selected-window) (minibuffer-window))
(save-excursion
(goto-char (point-max))
(let ((orig-pmax (point-max)))
(unwind-protect
(progn
(insert " " (, MESSAGE)) (goto-char orig-pmax)
(sit-for 0) ; Redisplay
,@FORMS)
(delete-region orig-pmax (point-max)))))
(prog2
(message "%s" (, MESSAGE))
(progn ,@FORMS)
(message ""))))
;; #+infodock (defalias 'lib-funcall-with-msg 'progn-with-message)
(put 'progn-with-message 'lisp-indent-hook 1)
;; #+infodock (put 'lib-funcall-with-message 'lisp-indent-hook 1)
;;=== Completion caching ==================================================
(defconst lib-complete:cache nil
"Used within read-library and read-library-internal to prevent
costly repeated calls to library-all-completions.
Format is a list of lists of the form
([<path> <subdir>] <cache-record> <cache-record> ...)
where each <cache-record> has the form
(<root> <modtimes> <completion-table>)")
;; #+infodock (defvaralias 'lib-completions 'lib-complete:cache)
(defun lib-complete:better-root (ROOT1 ROOT2)
"Return non-nil if ROOT1 is a superset of ROOT2."
(and (equal (file-name-directory ROOT1) (file-name-directory ROOT2))
(string-match
(concat "^" (regexp-quote (file-name-nondirectory ROOT1)))
ROOT2)))
(defun lib-complete:get-completion-table (FILE PATH FILTER)
(let* ((subdir (file-name-directory FILE))
(root (file-name-nondirectory FILE))
(PATH
(mapcar
(function (lambda (dir) (file-name-as-directory
(expand-file-name (or dir "")))))
PATH))
(key (vector PATH subdir FILTER))
(real-dirs
(if subdir
(mapcar (function (lambda (dir) (concat dir subdir))) PATH)
PATH))
(path-modtimes
(mapcar
(function (lambda (fn) (if fn (nth 5 (file-attributes fn)))))
real-dirs))
(cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry)))
;; Look for cached entry
(catch 'table
(while cache-records
(if (and
(lib-complete:better-root (nth 0 (car cache-records)) root)
(equal (nth 1 (car cache-records)) path-modtimes))
(throw 'table (nth 2 (car cache-records))))
(setq cache-records (cdr cache-records)))
;; Otherwise build completions
(let ((completion-list
(progn-with-message "(building completion table...)"
(library-all-completions FILE PATH nil 'fast)))
(completion-table (make-vector 127 0)))
(while completion-list
(let ((completion
(if (or (not FILTER)
(file-directory-p (car completion-list)))
(car completion-list)
(funcall FILTER (car completion-list)))))
(if completion
(intern completion completion-table)))
(setq completion-list (cdr completion-list)))
;; Cache the completions
(lib-complete:cache-completions key root
path-modtimes completion-table)
completion-table))))
(defvar lib-complete:max-cache-size 40
"*Maximum number of search paths which are cached.")
(defun lib-complete:cache-completions (key root modtimes table)
(let* ((cache-entry (assoc key lib-complete:cache))
(cache-records (cdr cache-entry))
(new-cache-records (list (list root modtimes table))))
(if (not cache-entry) nil
;; Remove old cache entry
(setq lib-complete:cache (delq cache-entry lib-complete:cache))
;; Copy non-redundant entries from old cache entry
(while cache-records
(if (or (equal root (nth 0 (car cache-records)))
(lib-complete:better-root root (nth 0 (car cache-records))))
nil
(setq new-cache-records
(cons (car cache-records) new-cache-records)))
(setq cache-records (cdr cache-records))))
;; Add entry to front of cache
(setq lib-complete:cache
(cons (cons key (nreverse new-cache-records)) lib-complete:cache))
;; Trim cache
(let ((tail (nthcdr lib-complete:max-cache-size lib-complete:cache)))
(if tail (setcdr tail nil)))))
;;=== Read a filename, with completion in a search path ===================
(defun read-library-internal (FILE FILTER FLAG)
"Don't call this."
;; Relies on read-library-internal-search-path being let-bound
(let ((completion-table
(lib-complete:get-completion-table
FILE read-library-internal-search-path FILTER)))
(cond
((not completion-table) nil)
;; Completion table is filtered before use, so the PREDICATE
;; argument is redundant.
((eq FLAG nil) (try-completion FILE completion-table nil))
((eq FLAG t) (all-completions FILE completion-table nil))
((eq FLAG 'lambda) (and (intern-soft FILE completion-table) t))
)))
(defun read-library (PROMPT SEARCH-PATH &optional DEFAULT MUST-MATCH
FULL FILTER)
"Read library name, prompting with PROMPT and completing in directories
from SEARCH-PATH. A nil in the search path represents the current
directory. Completions for a given search-path are cached, with the
cache being invalidated whenever one of the directories on the path changes.
Default to DEFAULT if user enters a null string.
Optional fourth arg MUST-MATCH non-nil means require existing file's name.
Non-nil and non-t means also require confirmation after completion.
Optional fifth argument FULL non-nil causes a full pathname, rather than a
relative pathname, to be returned. Note that FULL implies MUST-MATCH.
Optional sixth argument FILTER can be used to provide a function to
filter the completions. This function is passed the filename, and should
return a transformed filename (possibly a null transformation) or nil,
indicating that the filename should not be included in the completions."
(let* ((read-library-internal-search-path SEARCH-PATH)
(library (completing-read PROMPT 'read-library-internal
FILTER (or MUST-MATCH FULL) nil)))
(cond
((equal library "") DEFAULT)
(FULL (locate-file library read-library-internal-search-path
;; decompression doesn't work with Mule -slb
(if (featurep 'mule)
".el:.elc"
".el:.el.gz:.elc")))
(t library))))
;; NOTE: as a special case, read-library may be used to read a filename
;; relative to the current directory, returning a *relative* pathname
;; (read-file-name returns a full pathname).
;;
;; eg. (read-library "Local header: " '(nil) nil)
(defun get-library-path ()
"Front end to read-library"
(read-library "Find Library file: " load-path nil t t
(function (lambda (fn)
(cond
;; decompression doesn't work with mule -slb
((string-match (if (featurep 'mule)
"\\.el$"
"\\.el\\(\\.gz\\)?$") fn)
(substring fn 0 (match-beginning 0))))))
))
;; FSF Emacs version
(defun get-library-path ()
(let* ((short-lib (completing-read "Find Library file: " 'library-complete))
(full-path (locate-library short-lib)))
(if (string-match "\\.elc$" full-path)
(let ((non-elc (substring full-path 0 (1- (length full-path)))))
(if (file-exists-p non-elc)
non-elc
full-path))
full-path)))
;;=== Replacement for load-library with completion ========================
(defun load-library (library)
"Load the library named LIBRARY.
This is an interface to the function `load'."
(interactive
(list (read-library "Load Library: " load-path nil nil nil
(function (lambda (fn)
(cond
((string-match "\\.elc?$" fn)
(substring fn 0 (match-beginning 0))))))
)))
(load library))
;;=== find-library with completion (Author: PI:NAME:<NAME>END_PI) ===================
(defun find-library (library &optional codesys)
"Find and edit the source for the library named LIBRARY.
The extension of the LIBRARY must be omitted.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file library codesys)
(find-file library)
)
(defun find-library-other-window (library &optional codesys)
"Load the library named LIBRARY in another window.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-window library codesys)
(find-file-other-window library)
)
;; #+infodock (defalias 'lib-edit-other-window 'find-library-other-window)
(defun find-library-other-frame (library &optional codesys)
"Load the library named LIBRARY in a newly-created frame.
Under XEmacs/Mule, the optional second argument specifies the
coding system to use when decoding the file. Interactively,
with a prefix argument, you will be prompted for the coding system."
(interactive
(list (get-library-path)
(if current-prefix-arg
(read-coding-system "Coding System: "))))
;; (find-file-other-frame library codesys)
(find-file-other-frame library)
)
; This conflicts with an existing binding
;(define-key global-map "\C-xl" 'find-library)
(define-key global-map "\C-x4l" 'find-library-other-window)
(define-key global-map "\C-x5l" 'find-library-other-frame)
;; #+infodock (defalias 'lib-where-is 'locate-library)
;; #+infodock (provide 'lib)
(provide 'lib-complete)
;;; lib-complete.el ends here
|
[
{
"context": "es\n\n;; Copyright (C) 2018 M-industries\n\n;; Author: Paul van Dam <pvandam@m-industries.com>\n;; Maintainer: Paul va",
"end": 128,
"score": 0.9998840093612671,
"start": 116,
"tag": "NAME",
"value": "Paul van Dam"
},
{
"context": "t (C) 2018 M-industries\n\n;; Author: Paul van Dam <pvandam@m-industries.com>\n;; Maintainer: Paul van Dam <pvandam@m-industrie",
"end": 154,
"score": 0.9999363422393799,
"start": 130,
"tag": "EMAIL",
"value": "pvandam@m-industries.com"
},
{
"context": " van Dam <pvandam@m-industries.com>\n;; Maintainer: Paul van Dam <pvandam@m-industries.com>\n;; Version: 1.0.0\n;; C",
"end": 183,
"score": 0.9998824596405029,
"start": 171,
"tag": "NAME",
"value": "Paul van Dam"
},
{
"context": "am@m-industries.com>\n;; Maintainer: Paul van Dam <pvandam@m-industries.com>\n;; Version: 1.0.0\n;; Created: 13 October 2017\n;;",
"end": 209,
"score": 0.9999370574951172,
"start": 185,
"tag": "EMAIL",
"value": "pvandam@m-industries.com"
}
] | alan-mode.el | purcell/AlanForEmacs | 0 | ;;; alan-mode.el --- Major mode for editing M-industries Alan files
;; Copyright (C) 2018 M-industries
;; Author: Paul van Dam <pvandam@m-industries.com>
;; Maintainer: Paul van Dam <pvandam@m-industries.com>
;; Version: 1.0.0
;; Created: 13 October 2017
;; URL: https://github.com/M-industries/AlanForEmacs
;; Homepage: https://alan-platform.com/
;; Keywords: alan, languages
;; Package-Requires: ((flycheck "32") (emacs "25.1") (s "1.12"))
;; MIT License
;; Copyright (c) 2017 M-industries
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; This file is not part of GNU Emacs.
;;; Commentary:
;; A major mode for editing Alan files.
(require 'flycheck)
(require 'timer)
(require 'xref)
(require 's)
;;; Code:
(add-to-list 'auto-mode-alist '("\\.alan$" . alan-mode))
(defgroup alan nil
"Alan mode."
:prefix "alan-"
:group 'tools)
(defcustom alan-xref-limit-to-project-scope t
"Limits symbol lookup to the open buffers in project scope.
Only available when projectile is loaded, because it is based on
the function `projectile-project-root'"
:group 'alan
:type '(boolean))
(defcustom alan-compiler "compiler-project"
"The alan compiler.
This one is used when the variable `alan-project-root' cannot be
resolved to an existing directory."
:group 'alan
:type '(string))
(defcustom alan-script "alan"
"The alan build script file."
:group 'alan
:type '(string))
(defcustom alan-language-definition nil
"The Alan language to use.
Setting this will try to use the `alan-compiler' instead of the `alan-script'."
:group 'alan
:safe 'stringp)
(make-variable-buffer-local 'alan-language-definition)
;;; Alan mode
(defvar-local alan-mode-font-lock-keywords
'((("'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'" . font-lock-variable-name-face))
nil nil nil nil
(font-lock-syntactic-face-function . alan-font-lock-syntactic-face-function))
"Highlighting for alan mode")
(defvar alan-mode-syntax-table
(let ((alan-mode-syntax-table (make-syntax-table)))
(modify-syntax-entry ?* ". 23b" alan-mode-syntax-table)
(modify-syntax-entry ?/ ". 124" alan-mode-syntax-table)
(modify-syntax-entry ?\n ">" alan-mode-syntax-table)
(modify-syntax-entry ?' "\"" alan-mode-syntax-table)
(modify-syntax-entry ?{ "(}" alan-mode-syntax-table)
(modify-syntax-entry ?} "){" alan-mode-syntax-table)
alan-mode-syntax-table)
"Syntax table for ‘alan-mode’.")
;;;###autoload
(define-derived-mode alan-mode prog-mode "Alan"
"Major mode for editing Alan files."
:syntax-table alan-mode-syntax-table
:group 'alan
(setq comment-start "//")
(setq comment-end "")
(setq block-comment-start "/*")
(setq block-comment-end "*/")
(modify-syntax-entry ?\] "_" alan-mode-syntax-table)
(modify-syntax-entry ?\[ "_" alan-mode-syntax-table)
(setq font-lock-defaults alan-mode-font-lock-keywords)
(add-hook 'xref-backend-functions #'alan--xref-backend nil t)
(set (make-local-variable 'indent-line-function) 'alan-mode-indent-line)
(add-hook 'post-command-hook #'alan-update-header nil t)
(setq header-line-format ""))
(defvar alan-parent-regexp "\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)")
(defmacro alan-define-mode (name &optional docstring &rest body)
"Define NAME as an Alan major mode.
The mode derives from the generic `alan-mode'.
BODY can define keyword aguments.
:file-pattern
The file pattern to associate with the major mode. If none is
provided it will associate it with NAME.alan.
:keywords
A list of cons cells where the first is a regexp or a list of keywords
and the second element is the font-face.
:language
The path to the Alan language definition.
:pairs
A list of cons cells that match open and close parameters.
:propertize-rules
A list of rules used by `syntax-propertize-rules' When set will set the
propertize function for this mode.
The rest of the BODY is evaluated in the body of the derived-mode.
Optional argument DOCSTRING for the major mode."
(declare
(doc-string 2)
(indent 2))
(let* ((mode-name (intern (concat "alan-" (symbol-name name) "-mode")))
(language-name ;; name based on language naming convention.
(s-chop-suffix "-mode" (s-chop-prefix "alan-" (symbol-name name))))
(file-pattern ;; the naming convention for the file pattern is to use underscores.
(concat (s-replace "-" "_" language-name) ".alan"))
(keywords)
(language)
(pairs '())
(propertize-rules))
;; Process the keyword args.
(while (keywordp (car body))
(pcase (pop body)
(`:file-pattern (setq file-pattern (pop body)))
(`:keywords (setq keywords (pop body)))
(`:language (setq language (pop body)))
(`:pairs (setq pairs (pop body)))
(`:propertize-rules (setq propertize-rules (pop body)))
(_ (pop body))))
(when keywords
(setq keywords (mapcar (lambda (keyword-entry)
(if (listp (car keyword-entry))
(cons (regexp-opt (car keyword-entry)) (cdr keyword-entry))
keyword-entry)
) keywords)))
`(progn
(add-to-list 'auto-mode-alist '(,file-pattern . ,name))
(flycheck-add-mode 'alan ',name)
(define-derived-mode ,name alan-mode ,language-name
,docstring
:group 'alan
:after-hook (alan-setup-build-system)
,(when language
`(progn
(setq alan-language-definition ,language)))
,(when keywords
`(progn
(font-lock-add-keywords nil ',keywords "at end")))
,@(mapcar
(lambda (pair)
`(progn
(modify-syntax-entry ,(string-to-char (car pair)) ,(concat "(" (cdr pair)) alan-mode-syntax-table)
(modify-syntax-entry ,(string-to-char (cdr pair)) ,(concat ")" (car pair)) alan-mode-syntax-table)))
pairs)
,(when propertize-rules
`(progn
(set (make-local-variable 'syntax-propertize-function) (syntax-propertize-rules ,@propertize-rules))))
,@body))))
;;; Xref backend
(defun alan-boundry-of-identifier-at-point ()
"Return the beginning and end of an alan identifier or nil if point is not on an identifier."
(let ((text-properties (nth 1 (text-properties-at (point)))))
(when (or (and (listp text-properties)
(member font-lock-variable-name-face text-properties))
(eq font-lock-variable-name-face text-properties))
(save-excursion
(when-let* ((beginning (nth 8 (syntax-ppss)))
(end (progn (goto-char beginning) (forward-sexp) (point))))
(cons beginning end))))))
(put 'identifier 'bounds-of-thing-at-point 'alan-boundry-of-identifier-at-point)
(defun alan-thing-at-point ()
"Find alan variable at point."
(let ((boundary-pair (bounds-of-thing-at-point 'identifier)))
(if boundary-pair
(buffer-substring-no-properties
(car boundary-pair) (cdr boundary-pair)))))
(put 'identifier 'thing-at-point 'alan-thing-at-point)
;; todo add view definitions
;; todo add widget definitions
;; todo add control definitions
(defun alan--xref-backend () 'alan)
(defvar alan--xref-format
(let ((str "%s %s :%d"))
(put-text-property 0 2 'face 'font-lock-variable-name-face str)
(put-text-property 3 5 'face 'font-lock-function-name-face str)
str))
(defun alan--xref-make-xref (symbol type buffer symbol-position)
(xref-make (format alan--xref-format symbol type (line-number-at-pos symbol-position))
(xref-make-buffer-location buffer symbol-position)))
(defun alan--xref-find-definitions (symbol)
"Find all definitions matching SYMBOL."
(let ((xrefs)
(project-scope-limit (and
(featurep 'projectile)
alan-xref-limit-to-project-scope
(projectile-project-root))))
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (and (derived-mode-p 'alan-mode)
(or (null project-scope-limit)
(and (featurep 'projectile)
(string= project-scope-limit (projectile-project-root)))))
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(when (string= (match-string 1) symbol)
(add-to-list 'xrefs (alan--xref-make-xref symbol "" buffer (match-beginning 1)) t))))))))
xrefs))
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql alan)))
(alan-thing-at-point))
(cl-defmethod xref-backend-definitions ((_backend (eql alan)) symbol)
(alan--xref-find-definitions symbol))
(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql alan)))
(let (words)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(add-to-list 'words (match-string-no-properties 1)))
(seq-uniq words)))))
;;; Alan functions
(defun alan--has-parent ()
"Return point of parent or nil otherwise."
(let ((line-to-ignore-regex "^\\s-*\\(//.*\\)?$"))
(save-excursion
(move-beginning-of-line 1)
(while (and (not (bobp))
(looking-at line-to-ignore-regex))
(forward-line -1))
(let ((start-indent (current-indentation))
(curr-indent (current-indentation))
(curr-point (point))
(start-line-number (line-number-at-pos)))
(defvar new-point)
(while (and (not (bobp))
(> start-indent 0)
(or (not (looking-at "\\s-*'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'"))
(looking-at line-to-ignore-regex)
(> (current-indentation) curr-indent)
(<= start-indent (current-indentation))))
(forward-line -1)
(unless (looking-at line-to-ignore-regex)
(setq curr-indent (min curr-indent (current-indentation))))
(setq new-point (point)))
(if
(and
(looking-at alan-parent-regexp)
(not (equal start-line-number (line-number-at-pos))))
(match-beginning 1))))))
(defun alan-goto-parent ()
"Goto the parent of this property."
(interactive)
(let ((parent-position (alan--has-parent)))
(when (alan--has-parent)
(push-mark (point) t)
(goto-char parent-position))))
(defun alan-copy-path-to-clipboard ()
"Copy the path as shown in the header of the buffer.
This uses the `alan-path' function to get its value."
(interactive)
(let ((path (alan-path)))
(when path
(kill-new path))))
(defun alan-path ()
"Gives the location as a path of where you are in a file.
E.g. 'views' . 'queries' . 'context' . 'candidates' . 'of'"
(let ((path-list '())
has-parent)
(save-excursion
(while (setq has-parent (alan--has-parent))
(goto-char has-parent)
(add-to-list 'path-list (match-string 1))))
(if (> (length path-list) 0)
(mapconcat 'identity path-list " . ")
"")))
(defun alan-mode-indent-line ()
"Indentation based on parens.
Not suitable for white space significant languages."
(interactive)
(let (new-indent)
(save-excursion
(beginning-of-line)
(if (bobp)
;;at the beginning indent to 0
(indent-line-to 0))
;; take the current indentation of the enclosing expression
(let ((parent-position (nth 1 (syntax-ppss)))
(previous-line-indentation
(and (not (bobp))
(save-excursion (forward-line -1) (current-indentation)))))
(cond
(parent-position
(let ((parent-indent
(save-excursion
(goto-char parent-position)
(current-indentation))))
(if (looking-at "\\s-*\\s)") ;; looking at closing paren.
(setq new-indent parent-indent)
(setq new-indent ( + parent-indent tab-width)))))
(previous-line-indentation
(setq new-indent previous-line-indentation)))
;; check for single block and add a level of indentation.
(save-excursion
(back-to-indentation)
(if (and (looking-at "\\s(")
(eq (line-number-at-pos)
(progn (forward-sexp) (line-number-at-pos))))
(setq new-indent (min (if previous-line-indentation (+ previous-line-indentation tab-width) tab-width )
(+ new-indent tab-width)))))))
(when new-indent
(indent-line-to new-indent))))
(defun alan-font-lock-syntactic-face-function (state)
"Don't fontify single quoted strings.
STATE is the result of the function `parse-partial-sexp'."
(if (nth 3 state)
(let ((startpos (nth 8 state)))
(if (eq (char-after startpos) ?')
;; This is not a string, but an identifier.
nil
font-lock-string-face))
font-lock-comment-face))
(defvar-local alan--update-headline-timer nil)
(defun alan-update-header ()
"Update the header line after 0.5 seconds of idle time."
(when (timerp alan--update-headline-timer)
(cancel-timer alan--update-headline-timer))
(setq alan--update-headline-timer
(run-with-idle-timer
0.5 nil
(lambda (buffer-to-update)
(with-current-buffer buffer-to-update
(setq header-line-format (format " %s " (alan-path)))
(force-mode-line-update)))
(current-buffer))))
;;; Flycheck
(defun alan-flycheck-error-filter (error-list)
"Flycheck error filter for the Alan comopiler.
Do not include /dev/null and only show errors for the current buffer."
(seq-remove (lambda (error)
(or (string= (flycheck-error-filename error) "/dev/null")
(not (string= (flycheck-error-filename error) (buffer-file-name)))))
error-list))
(defvar-local alan--flycheck-language-definition nil
"The real path to the language definition if `alan-language-definition' can be resolved.")
(flycheck-define-checker alan
"An Alan syntax checker."
:command ("alan"
(eval (if (null alan--flycheck-language-definition)
'("build" "--format" "emacs")
`(,alan--flycheck-language-definition "--format" "emacs" "--log" "warning" "/dev/null"))))
:error-patterns
((error line-start (file-name) ":" line ":" column ": error:" (zero-or-one " " (one-or-more digit) ":" (one-or-more digit))
;; Messages start with a white space after the error.
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end)
(warning line-start (file-name) ":" line ":" column ": warning: " (one-or-more digit) ":" (one-or-more digit)
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end))
:error-filter alan-flycheck-error-filter
:modes (alan-mode)) ;; all other modes are added using the `alan-define-mode' macro.
(add-to-list 'flycheck-checkers 'alan)
;;; Project root and build system
(defvar-local alan-project-root nil
"The project root set by function `alan-project-root'.")
(defun alan-project-root ()
"Project root folder determined based on the presence of a project.json or versions.json file.
If `alan-language-definition' is set prefer to use the
project.json over versions.json."
(or
alan-project-root
(setq alan-project-root
(expand-file-name
(or (let ((project-files ["versions.json" "project.json"]))
(seq-find
#'stringp
(seq-map (lambda (project-file)
(locate-dominating-file default-directory project-file))
;; Prefer to use project.json if `alan-language-definition' is set.
(if alan-language-definition (seq-reverse project-files) project-files))))
(progn
(message "Couldn't locate project root folder with a versions.json or project.json file. Using' %s' as project root." default-directory)
default-directory))))))
(defun alan-file-executable (file)
"Check if FILE is executable and return FILE."
(when (file-executable-p file) file))
(defun alan-find-alan-script ()
"Try to find the alan script in the dominating directory starting from the function `alan-project-root'.
Return nil if the script can not be found."
(when-let ((alan-project-script
(locate-dominating-file
(alan-project-root)
(lambda (name)
(let ((alan-script-candidate (concat name "alan")))
(and (file-executable-p alan-script-candidate)
(not (file-directory-p alan-script-candidate))))))))
(concat alan-project-script "alan")))
(defun alan--file-exists (name)
"Return the file NAME if it exists."
(when (file-exists-p name) name))
(defun alan-setup-build-system ()
"Setup Flycheck and the `compile-command'."
(let ((alan-project-script (or (alan-find-alan-script)
(executable-find alan-script)))
(alan-project-compiler (cond ((alan-file-executable (concat (alan-project-root) "dependencies/dev/internals/alan/tools/compiler-project")))
((alan-file-executable (concat (alan-project-root) "devenv/platform/project-compiler/tools/compiler-project")))))
(alan-project-language (concat (alan-project-root) alan-language-definition)))
(set (make-local-variable 'compilation-error-screen-columns) nil)
(cond
((and alan-project-compiler alan-language-definition)
(set (make-local-variable 'flycheck-alan-executable) alan-project-compiler)
(setq alan--flycheck-language-definition alan-project-language)
(set (make-local-variable 'compile-command)
(concat alan-project-compiler " " alan-project-language " --format emacs --log warning /dev/null ")))
((and alan-project-script)
(setq flycheck-alan-executable alan-project-script)
(set (make-local-variable 'compile-command) (concat alan-project-script " build emacs ")))
(t (message "No alan compiler or script found.")))))
;;; Modes
(defvar alan-imenu-generic-expression
;; Patterns to identify alan definitions
'(("dictionary" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* dictionary" 1)
("state group" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* stategroup" 1)
("component" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* component" 1)
("text" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* text" 1)
("number" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* number" 1)
("matrix" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* \\(?:dense\\|sparse\\)matrix" 1)))
;;;###autoload (autoload 'alan-schema-mode "alan-mode")
(alan-define-mode alan-schema-mode
"Major mode for editing Alan schema files."
:language "dependencies/dev/internals/alan/language"
:keywords (("->\\s-+\\(stategroup\\|component\\|group\\|dictionary\\|command\\|densematrix\\|sparsematrix\\|reference\\|number\\|text\\)\\(\\s-+\\|$\\)" 1 font-lock-type-face)
(( "component" "types" "external" "->" "plural" "numerical"
"integer" "natural" "root" "]" ":" "*" "?" "~" "+" "constrain"
"acyclic" "ordered" "dictionary" "densematrix" "sparsematrix"
"$" "==" "!=" "group" "number" "reference" "stategroup" "text"
"." "!" "!&" "&" ".^" "+^" "}" ">" "*&" "?^" ">>" "forward"
"self" "{" "graph" "usage" "implicit" "ignore" "experimental"
"libraries" "using") . font-lock-builtin-face)))
(defun alan-grammar-update-keyword ()
"Update the keywords section based on all used keywords in this grammar file."
(interactive)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((keyword-point (re-search-forward "^keywords$"))
(root-point (re-search-forward "^root$"))
(root-point-start (match-beginning 0)) ;; because the last search was for root
(alan-keywords (list)))
(while (re-search-forward "\\[\\(\\s-?'[^'
]+'\\s-?,?\\)+\\]" nil t) ;; there is a line end in the regex. Hence the weird break.
(let ((keyword-group (match-string 0))
(search-start 0))
(while (string-match "'[^']+'" keyword-group search-start)
(add-to-list 'alan-keywords (match-string 0 keyword-group))
(setq search-start (match-end 0)))))
(delete-region (+ 1 keyword-point) root-point-start)
(goto-char (+ 1 keyword-point))
(insert (string-join (mapcar (lambda (k) (concat "\t" k)) (sort (delete-dups alan-keywords ) 'string<)) "
"))
(insert "
")
(insert "
")))))
(defun alan-grammar-mode-indent-line ()
"Indentation based on parens and toggle indentation to min and max indentation possible."
(interactive)
(let
(new-indent)
(save-mark-and-excursion
(beginning-of-line)
(when (bobp) (indent-line-to 0)) ;;at the beginning indent at 0
(let* ((parent-position (nth 1 (syntax-ppss))) ;; take the current indentation of the enclosing expression
(parent-indent (if parent-position
(save-excursion (goto-char parent-position) (current-indentation))
0))
(current-indent (current-indentation))
(previous-line-indentation (and
(not (bobp))
(save-excursion
(forward-line -1)
(current-indentation))))
(min-indentation (if parent-position (+ parent-indent tab-width) 0))
(max-indentation (+ previous-line-indentation tab-width)))
(cond
((and parent-position (looking-at "\\s-*\\s)"))
(setq new-indent parent-indent))
((= current-indent min-indentation)
(setq new-indent max-indentation))
((< current-indent min-indentation) ;; usually after a newline.
(setq new-indent (max previous-line-indentation min-indentation)))
((> current-indent max-indentation)
(setq new-indent max-indentation))
((<= current-indent max-indentation)
(setq new-indent (- current-indent tab-width))))))
(when new-indent
(indent-line-to new-indent))))
;;;###autoload (autoload 'alan-grammar-mode "alan-mode")
(alan-define-mode alan-grammar-mode
"Major mode for editing Alan grammar files."
:language "dependencies/dev/internals/alan/language"
:pairs (("[" . "]"))
:keywords ((("rules" "root" "component" "indent" "keywords" "collection" "order"
"predecessors" "successors" "group" "number" "reference" "stategroup"
"has" "first" "last" "predecessor" "successor" "text" "[" "]" ","
) . font-lock-builtin-face))
(electric-indent-local-mode -1)
(local-set-key (kbd "RET") 'newline-and-indent)
(set (make-local-variable 'indent-line-function) 'alan-grammar-mode-indent-line))
(defun alan-template-yank ()
"Yank but wrap as template."
(interactive)
(let ((string-to-yank (current-kill 0 t)))
(insert (mapconcat 'identity
(mapcar (lambda (s)
(format "\"%s\"" (replace-regexp-in-string "\"" "\\\\\"" s)))
(split-string string-to-yank "\n"))
"\n"))))
;;;###autoload (autoload 'alan-template-mode "alan-mode")
(alan-define-mode alan-template-mode
"Major mode for editing Alan template files."
:file-pattern "\\.template$"
:language "dependencies/dev/internals/alan-to-text-transformation/language")
(defun alan-list-nummerical-types ()
"Return a list of all nummerical types."
(save-mark-and-excursion
(save-restriction
(widen)
(goto-char (point-max))
(let ((numerical-types-point (re-search-backward "^numerical-types"))
(numerical-types (list)))
(when numerical-types-point
(while (re-search-forward "^\\s-*'\\([^']*\\)'" nil t)
(add-to-list 'numerical-types (match-string 1))))
numerical-types))))
;;;###autoload (autoload 'alan-application-mode "alan-mode")
(alan-define-mode alan-application-mode
"Major mode for editing Alan application model files."
:pairs (("{" . "}"))
:keywords (
("^\\(users\\|roles\\|root\\|numerical-types\\)" . font-lock-keyword-face)
("\\(:\\|:=\\)\\s-+\\(stategroup\\|component\\|group\\|file\\|collection\\|command\\|reference-set\\|natural\\|integer\\|text\\)\\(\\s-+\\|$\\)" 2 font-lock-type-face)
(("today" "now" "zero" "true" "false") . font-lock-constant-face)
(( "@date" "@date-time" "@default:" "@description:" "@desired"
"@dormant" "@duration:" "@factor:" "@guid" "@hidden"
"@identifying" "@key-description:" "@label:" "@linked" "@max:"
"@metadata" "@min:" "@multi-line" "@name" "@namespace" "@small"
"@sticky" "@validate:" "@verified" "@visible" )
. font-lock-keyword-face)
(("add" "branch" "ceil" "convert" "count" "division" "floor" "increment"
"max" "min" "remainder" "subtract" "sum" "sumlist" "base" "diff"
"product")
. font-lock-function-name-face)
(("#" "#reader" "#writer" "$" "$^" "%" "%^" "%}" "&#" "&" "*" "+" "+^" ","
"-" "-<" "->" "." ".^" ".key" ".self" ".}" "/" "10^" ":" ":=" "<" "<-"
"<=" "=" "==" "=>" ">" ">=" ">key" "?" "?^" "@%^" "@" "@?^" "@date"
"@date-time" "@default:" "@description:" "@desired" "@dormant"
"@duration:" "@factor:" "@guid" "@hidden" "@identifying"
"@key-description:" "@label:" "@linked" "@max:" "@metadata" "@min:"
"@multi-line" "@name" "@namespace" "@small" "@sticky" "@validate:"
"@verified" "@visible" "[" "]" "^" "acyclic-graph" "add" "and" "anonymous"
"any" "as" "base" "ceil" "collection" "command" "component" "count"
"create" "created" "creation-time" "delete" "dense" "deprecated"
"dictionary" "diff" "division" "do" "dynamic" "entry" "external" "false"
"file" "floor" "forward" "from" "group" "hours" "if" "ignore" "in"
"increment" "integer" "interface" "invalidate" "inverse" "join"
"life-time" "log" "mapping" "match" "match-branch" "matrix" "max" "min"
"minutes" "mutation-time" "natural" "new" "node" "now" "number"
"numerical-types" "on" "one" "ontimeout" "ordered-graph" "password"
"product" "reference" "reference-set" "referencer" "remainder" "remove"
"rename" "roles" "root" "seconds" "space" "sparse" "stategroup" "std"
"subtract" "sum" "sumlist" "switch" "text" "timer" "today" "true" "union"
"unsafe" "update" "users" "with" "workfor" "zero" "|" "~>" ) . font-lock-builtin-face))
:propertize-rules (("[\\.%]\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-widget-mode "alan-mode")
(alan-define-mode alan-widget-mode
"Major mode for editing Alan widget model files."
:file-pattern "widgets/.*\\.ui\\.alan$"
:pairs (("{" . "}") ("[" . "]"))
:keywords ((( "#" "$" "*" "," "->" "." ".}" ":" "::" "=>" ">" ">>" "?" "@"
"^" "binding" "configuration" "control" "current" "dictionary"
"empty" "engine" "file" "format" "inline" "instruction" "interval"
"let" "list" "markup" "number" "on" "set" "state" "stategroup"
"static" "switch" "text" "time" "to" "transform" "unconstrained"
"view" "widget" "window" "|" ) . font-lock-builtin-face))
:propertize-rules (("\\.\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-views-mode "alan-mode")
(alan-define-mode alan-views-mode
"Major mode for editing Alan views files."
:pairs (("{" . "}") ("[" . "]"))
:file-pattern "views/.*\\.ui\\.alan$"
:propertize-rules (("/?%\\(}\\)" (1 "_")))
:keywords ((( "$" "%" "%^" "%}" "*" "+" "+^" "-" "->" "." ".>" ".^" "/%}" "/>"
":>" "<" "<<" "<=" "=" "==" ">" ">=" ">>" "?" "?^" "@" "as"
"candidates" "collection" "command" "disabled" "enabled" "entity"
"file" "filter" "from" "group" "id" "inline" "key" "limit" "link"
"matrix" "node" "none" "now" "number" "of" "on" "open" "path"
"query" "reference" "refresh" "role" "root" "selected"
"stategroup" "subscribe" "text" "using" "view" "window")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-wiring-mode "alan-mode")
(alan-define-mode alan-wiring-mode
"Major mode for editing Alan wiring files."
:keywords ((("interfaces:" "external-systems:" "systems:" "provides:"
"consumes:" "provided-connections:" "from" "external" "internal"
"(" ")" "." "=" "message" "custom")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-deployment-mode "alan-mode")
(alan-define-mode alan-deployment-mode
"Major mode for editing Alan deployment files."
:language "devenv/platform/project-build-environment/language"
:keywords ((("external-systems:" "instance-data:" "system-options:"
"provided-connections:" ":" "." "from" "local" "remote" "stack"
"system" "migrate" "timezone" "interface" "message" "custom"
"socket" "schedule" "at" "never" "every" "day" "hour" "Monday"
"Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" )
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-mapping-mode "alan-mode")
(alan-define-mode alan-mapping-mode
"Major mode for editing Alan mapping files."
:keywords ((("#" "%" "(" ")" "+" "." "/" ":" ":=" "=" "=>" ">" "?" "@" "|"
"causal" "collection" "command" "do" "file" "group" "integer"
"interfaces" "log" "natural" "number" "on" "reference-set"
"roles" "root" "stategroup" "switch" "text" "with")
. font-lock-builtin-face)))
(provide 'alan-mode)
;;; alan-mode.el ends here
| 6767 | ;;; alan-mode.el --- Major mode for editing M-industries Alan files
;; Copyright (C) 2018 M-industries
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; Version: 1.0.0
;; Created: 13 October 2017
;; URL: https://github.com/M-industries/AlanForEmacs
;; Homepage: https://alan-platform.com/
;; Keywords: alan, languages
;; Package-Requires: ((flycheck "32") (emacs "25.1") (s "1.12"))
;; MIT License
;; Copyright (c) 2017 M-industries
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; This file is not part of GNU Emacs.
;;; Commentary:
;; A major mode for editing Alan files.
(require 'flycheck)
(require 'timer)
(require 'xref)
(require 's)
;;; Code:
(add-to-list 'auto-mode-alist '("\\.alan$" . alan-mode))
(defgroup alan nil
"Alan mode."
:prefix "alan-"
:group 'tools)
(defcustom alan-xref-limit-to-project-scope t
"Limits symbol lookup to the open buffers in project scope.
Only available when projectile is loaded, because it is based on
the function `projectile-project-root'"
:group 'alan
:type '(boolean))
(defcustom alan-compiler "compiler-project"
"The alan compiler.
This one is used when the variable `alan-project-root' cannot be
resolved to an existing directory."
:group 'alan
:type '(string))
(defcustom alan-script "alan"
"The alan build script file."
:group 'alan
:type '(string))
(defcustom alan-language-definition nil
"The Alan language to use.
Setting this will try to use the `alan-compiler' instead of the `alan-script'."
:group 'alan
:safe 'stringp)
(make-variable-buffer-local 'alan-language-definition)
;;; Alan mode
(defvar-local alan-mode-font-lock-keywords
'((("'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'" . font-lock-variable-name-face))
nil nil nil nil
(font-lock-syntactic-face-function . alan-font-lock-syntactic-face-function))
"Highlighting for alan mode")
(defvar alan-mode-syntax-table
(let ((alan-mode-syntax-table (make-syntax-table)))
(modify-syntax-entry ?* ". 23b" alan-mode-syntax-table)
(modify-syntax-entry ?/ ". 124" alan-mode-syntax-table)
(modify-syntax-entry ?\n ">" alan-mode-syntax-table)
(modify-syntax-entry ?' "\"" alan-mode-syntax-table)
(modify-syntax-entry ?{ "(}" alan-mode-syntax-table)
(modify-syntax-entry ?} "){" alan-mode-syntax-table)
alan-mode-syntax-table)
"Syntax table for ‘alan-mode’.")
;;;###autoload
(define-derived-mode alan-mode prog-mode "Alan"
"Major mode for editing Alan files."
:syntax-table alan-mode-syntax-table
:group 'alan
(setq comment-start "//")
(setq comment-end "")
(setq block-comment-start "/*")
(setq block-comment-end "*/")
(modify-syntax-entry ?\] "_" alan-mode-syntax-table)
(modify-syntax-entry ?\[ "_" alan-mode-syntax-table)
(setq font-lock-defaults alan-mode-font-lock-keywords)
(add-hook 'xref-backend-functions #'alan--xref-backend nil t)
(set (make-local-variable 'indent-line-function) 'alan-mode-indent-line)
(add-hook 'post-command-hook #'alan-update-header nil t)
(setq header-line-format ""))
(defvar alan-parent-regexp "\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)")
(defmacro alan-define-mode (name &optional docstring &rest body)
"Define NAME as an Alan major mode.
The mode derives from the generic `alan-mode'.
BODY can define keyword aguments.
:file-pattern
The file pattern to associate with the major mode. If none is
provided it will associate it with NAME.alan.
:keywords
A list of cons cells where the first is a regexp or a list of keywords
and the second element is the font-face.
:language
The path to the Alan language definition.
:pairs
A list of cons cells that match open and close parameters.
:propertize-rules
A list of rules used by `syntax-propertize-rules' When set will set the
propertize function for this mode.
The rest of the BODY is evaluated in the body of the derived-mode.
Optional argument DOCSTRING for the major mode."
(declare
(doc-string 2)
(indent 2))
(let* ((mode-name (intern (concat "alan-" (symbol-name name) "-mode")))
(language-name ;; name based on language naming convention.
(s-chop-suffix "-mode" (s-chop-prefix "alan-" (symbol-name name))))
(file-pattern ;; the naming convention for the file pattern is to use underscores.
(concat (s-replace "-" "_" language-name) ".alan"))
(keywords)
(language)
(pairs '())
(propertize-rules))
;; Process the keyword args.
(while (keywordp (car body))
(pcase (pop body)
(`:file-pattern (setq file-pattern (pop body)))
(`:keywords (setq keywords (pop body)))
(`:language (setq language (pop body)))
(`:pairs (setq pairs (pop body)))
(`:propertize-rules (setq propertize-rules (pop body)))
(_ (pop body))))
(when keywords
(setq keywords (mapcar (lambda (keyword-entry)
(if (listp (car keyword-entry))
(cons (regexp-opt (car keyword-entry)) (cdr keyword-entry))
keyword-entry)
) keywords)))
`(progn
(add-to-list 'auto-mode-alist '(,file-pattern . ,name))
(flycheck-add-mode 'alan ',name)
(define-derived-mode ,name alan-mode ,language-name
,docstring
:group 'alan
:after-hook (alan-setup-build-system)
,(when language
`(progn
(setq alan-language-definition ,language)))
,(when keywords
`(progn
(font-lock-add-keywords nil ',keywords "at end")))
,@(mapcar
(lambda (pair)
`(progn
(modify-syntax-entry ,(string-to-char (car pair)) ,(concat "(" (cdr pair)) alan-mode-syntax-table)
(modify-syntax-entry ,(string-to-char (cdr pair)) ,(concat ")" (car pair)) alan-mode-syntax-table)))
pairs)
,(when propertize-rules
`(progn
(set (make-local-variable 'syntax-propertize-function) (syntax-propertize-rules ,@propertize-rules))))
,@body))))
;;; Xref backend
(defun alan-boundry-of-identifier-at-point ()
"Return the beginning and end of an alan identifier or nil if point is not on an identifier."
(let ((text-properties (nth 1 (text-properties-at (point)))))
(when (or (and (listp text-properties)
(member font-lock-variable-name-face text-properties))
(eq font-lock-variable-name-face text-properties))
(save-excursion
(when-let* ((beginning (nth 8 (syntax-ppss)))
(end (progn (goto-char beginning) (forward-sexp) (point))))
(cons beginning end))))))
(put 'identifier 'bounds-of-thing-at-point 'alan-boundry-of-identifier-at-point)
(defun alan-thing-at-point ()
"Find alan variable at point."
(let ((boundary-pair (bounds-of-thing-at-point 'identifier)))
(if boundary-pair
(buffer-substring-no-properties
(car boundary-pair) (cdr boundary-pair)))))
(put 'identifier 'thing-at-point 'alan-thing-at-point)
;; todo add view definitions
;; todo add widget definitions
;; todo add control definitions
(defun alan--xref-backend () 'alan)
(defvar alan--xref-format
(let ((str "%s %s :%d"))
(put-text-property 0 2 'face 'font-lock-variable-name-face str)
(put-text-property 3 5 'face 'font-lock-function-name-face str)
str))
(defun alan--xref-make-xref (symbol type buffer symbol-position)
(xref-make (format alan--xref-format symbol type (line-number-at-pos symbol-position))
(xref-make-buffer-location buffer symbol-position)))
(defun alan--xref-find-definitions (symbol)
"Find all definitions matching SYMBOL."
(let ((xrefs)
(project-scope-limit (and
(featurep 'projectile)
alan-xref-limit-to-project-scope
(projectile-project-root))))
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (and (derived-mode-p 'alan-mode)
(or (null project-scope-limit)
(and (featurep 'projectile)
(string= project-scope-limit (projectile-project-root)))))
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(when (string= (match-string 1) symbol)
(add-to-list 'xrefs (alan--xref-make-xref symbol "" buffer (match-beginning 1)) t))))))))
xrefs))
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql alan)))
(alan-thing-at-point))
(cl-defmethod xref-backend-definitions ((_backend (eql alan)) symbol)
(alan--xref-find-definitions symbol))
(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql alan)))
(let (words)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(add-to-list 'words (match-string-no-properties 1)))
(seq-uniq words)))))
;;; Alan functions
(defun alan--has-parent ()
"Return point of parent or nil otherwise."
(let ((line-to-ignore-regex "^\\s-*\\(//.*\\)?$"))
(save-excursion
(move-beginning-of-line 1)
(while (and (not (bobp))
(looking-at line-to-ignore-regex))
(forward-line -1))
(let ((start-indent (current-indentation))
(curr-indent (current-indentation))
(curr-point (point))
(start-line-number (line-number-at-pos)))
(defvar new-point)
(while (and (not (bobp))
(> start-indent 0)
(or (not (looking-at "\\s-*'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'"))
(looking-at line-to-ignore-regex)
(> (current-indentation) curr-indent)
(<= start-indent (current-indentation))))
(forward-line -1)
(unless (looking-at line-to-ignore-regex)
(setq curr-indent (min curr-indent (current-indentation))))
(setq new-point (point)))
(if
(and
(looking-at alan-parent-regexp)
(not (equal start-line-number (line-number-at-pos))))
(match-beginning 1))))))
(defun alan-goto-parent ()
"Goto the parent of this property."
(interactive)
(let ((parent-position (alan--has-parent)))
(when (alan--has-parent)
(push-mark (point) t)
(goto-char parent-position))))
(defun alan-copy-path-to-clipboard ()
"Copy the path as shown in the header of the buffer.
This uses the `alan-path' function to get its value."
(interactive)
(let ((path (alan-path)))
(when path
(kill-new path))))
(defun alan-path ()
"Gives the location as a path of where you are in a file.
E.g. 'views' . 'queries' . 'context' . 'candidates' . 'of'"
(let ((path-list '())
has-parent)
(save-excursion
(while (setq has-parent (alan--has-parent))
(goto-char has-parent)
(add-to-list 'path-list (match-string 1))))
(if (> (length path-list) 0)
(mapconcat 'identity path-list " . ")
"")))
(defun alan-mode-indent-line ()
"Indentation based on parens.
Not suitable for white space significant languages."
(interactive)
(let (new-indent)
(save-excursion
(beginning-of-line)
(if (bobp)
;;at the beginning indent to 0
(indent-line-to 0))
;; take the current indentation of the enclosing expression
(let ((parent-position (nth 1 (syntax-ppss)))
(previous-line-indentation
(and (not (bobp))
(save-excursion (forward-line -1) (current-indentation)))))
(cond
(parent-position
(let ((parent-indent
(save-excursion
(goto-char parent-position)
(current-indentation))))
(if (looking-at "\\s-*\\s)") ;; looking at closing paren.
(setq new-indent parent-indent)
(setq new-indent ( + parent-indent tab-width)))))
(previous-line-indentation
(setq new-indent previous-line-indentation)))
;; check for single block and add a level of indentation.
(save-excursion
(back-to-indentation)
(if (and (looking-at "\\s(")
(eq (line-number-at-pos)
(progn (forward-sexp) (line-number-at-pos))))
(setq new-indent (min (if previous-line-indentation (+ previous-line-indentation tab-width) tab-width )
(+ new-indent tab-width)))))))
(when new-indent
(indent-line-to new-indent))))
(defun alan-font-lock-syntactic-face-function (state)
"Don't fontify single quoted strings.
STATE is the result of the function `parse-partial-sexp'."
(if (nth 3 state)
(let ((startpos (nth 8 state)))
(if (eq (char-after startpos) ?')
;; This is not a string, but an identifier.
nil
font-lock-string-face))
font-lock-comment-face))
(defvar-local alan--update-headline-timer nil)
(defun alan-update-header ()
"Update the header line after 0.5 seconds of idle time."
(when (timerp alan--update-headline-timer)
(cancel-timer alan--update-headline-timer))
(setq alan--update-headline-timer
(run-with-idle-timer
0.5 nil
(lambda (buffer-to-update)
(with-current-buffer buffer-to-update
(setq header-line-format (format " %s " (alan-path)))
(force-mode-line-update)))
(current-buffer))))
;;; Flycheck
(defun alan-flycheck-error-filter (error-list)
"Flycheck error filter for the Alan comopiler.
Do not include /dev/null and only show errors for the current buffer."
(seq-remove (lambda (error)
(or (string= (flycheck-error-filename error) "/dev/null")
(not (string= (flycheck-error-filename error) (buffer-file-name)))))
error-list))
(defvar-local alan--flycheck-language-definition nil
"The real path to the language definition if `alan-language-definition' can be resolved.")
(flycheck-define-checker alan
"An Alan syntax checker."
:command ("alan"
(eval (if (null alan--flycheck-language-definition)
'("build" "--format" "emacs")
`(,alan--flycheck-language-definition "--format" "emacs" "--log" "warning" "/dev/null"))))
:error-patterns
((error line-start (file-name) ":" line ":" column ": error:" (zero-or-one " " (one-or-more digit) ":" (one-or-more digit))
;; Messages start with a white space after the error.
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end)
(warning line-start (file-name) ":" line ":" column ": warning: " (one-or-more digit) ":" (one-or-more digit)
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end))
:error-filter alan-flycheck-error-filter
:modes (alan-mode)) ;; all other modes are added using the `alan-define-mode' macro.
(add-to-list 'flycheck-checkers 'alan)
;;; Project root and build system
(defvar-local alan-project-root nil
"The project root set by function `alan-project-root'.")
(defun alan-project-root ()
"Project root folder determined based on the presence of a project.json or versions.json file.
If `alan-language-definition' is set prefer to use the
project.json over versions.json."
(or
alan-project-root
(setq alan-project-root
(expand-file-name
(or (let ((project-files ["versions.json" "project.json"]))
(seq-find
#'stringp
(seq-map (lambda (project-file)
(locate-dominating-file default-directory project-file))
;; Prefer to use project.json if `alan-language-definition' is set.
(if alan-language-definition (seq-reverse project-files) project-files))))
(progn
(message "Couldn't locate project root folder with a versions.json or project.json file. Using' %s' as project root." default-directory)
default-directory))))))
(defun alan-file-executable (file)
"Check if FILE is executable and return FILE."
(when (file-executable-p file) file))
(defun alan-find-alan-script ()
"Try to find the alan script in the dominating directory starting from the function `alan-project-root'.
Return nil if the script can not be found."
(when-let ((alan-project-script
(locate-dominating-file
(alan-project-root)
(lambda (name)
(let ((alan-script-candidate (concat name "alan")))
(and (file-executable-p alan-script-candidate)
(not (file-directory-p alan-script-candidate))))))))
(concat alan-project-script "alan")))
(defun alan--file-exists (name)
"Return the file NAME if it exists."
(when (file-exists-p name) name))
(defun alan-setup-build-system ()
"Setup Flycheck and the `compile-command'."
(let ((alan-project-script (or (alan-find-alan-script)
(executable-find alan-script)))
(alan-project-compiler (cond ((alan-file-executable (concat (alan-project-root) "dependencies/dev/internals/alan/tools/compiler-project")))
((alan-file-executable (concat (alan-project-root) "devenv/platform/project-compiler/tools/compiler-project")))))
(alan-project-language (concat (alan-project-root) alan-language-definition)))
(set (make-local-variable 'compilation-error-screen-columns) nil)
(cond
((and alan-project-compiler alan-language-definition)
(set (make-local-variable 'flycheck-alan-executable) alan-project-compiler)
(setq alan--flycheck-language-definition alan-project-language)
(set (make-local-variable 'compile-command)
(concat alan-project-compiler " " alan-project-language " --format emacs --log warning /dev/null ")))
((and alan-project-script)
(setq flycheck-alan-executable alan-project-script)
(set (make-local-variable 'compile-command) (concat alan-project-script " build emacs ")))
(t (message "No alan compiler or script found.")))))
;;; Modes
(defvar alan-imenu-generic-expression
;; Patterns to identify alan definitions
'(("dictionary" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* dictionary" 1)
("state group" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* stategroup" 1)
("component" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* component" 1)
("text" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* text" 1)
("number" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* number" 1)
("matrix" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* \\(?:dense\\|sparse\\)matrix" 1)))
;;;###autoload (autoload 'alan-schema-mode "alan-mode")
(alan-define-mode alan-schema-mode
"Major mode for editing Alan schema files."
:language "dependencies/dev/internals/alan/language"
:keywords (("->\\s-+\\(stategroup\\|component\\|group\\|dictionary\\|command\\|densematrix\\|sparsematrix\\|reference\\|number\\|text\\)\\(\\s-+\\|$\\)" 1 font-lock-type-face)
(( "component" "types" "external" "->" "plural" "numerical"
"integer" "natural" "root" "]" ":" "*" "?" "~" "+" "constrain"
"acyclic" "ordered" "dictionary" "densematrix" "sparsematrix"
"$" "==" "!=" "group" "number" "reference" "stategroup" "text"
"." "!" "!&" "&" ".^" "+^" "}" ">" "*&" "?^" ">>" "forward"
"self" "{" "graph" "usage" "implicit" "ignore" "experimental"
"libraries" "using") . font-lock-builtin-face)))
(defun alan-grammar-update-keyword ()
"Update the keywords section based on all used keywords in this grammar file."
(interactive)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((keyword-point (re-search-forward "^keywords$"))
(root-point (re-search-forward "^root$"))
(root-point-start (match-beginning 0)) ;; because the last search was for root
(alan-keywords (list)))
(while (re-search-forward "\\[\\(\\s-?'[^'
]+'\\s-?,?\\)+\\]" nil t) ;; there is a line end in the regex. Hence the weird break.
(let ((keyword-group (match-string 0))
(search-start 0))
(while (string-match "'[^']+'" keyword-group search-start)
(add-to-list 'alan-keywords (match-string 0 keyword-group))
(setq search-start (match-end 0)))))
(delete-region (+ 1 keyword-point) root-point-start)
(goto-char (+ 1 keyword-point))
(insert (string-join (mapcar (lambda (k) (concat "\t" k)) (sort (delete-dups alan-keywords ) 'string<)) "
"))
(insert "
")
(insert "
")))))
(defun alan-grammar-mode-indent-line ()
"Indentation based on parens and toggle indentation to min and max indentation possible."
(interactive)
(let
(new-indent)
(save-mark-and-excursion
(beginning-of-line)
(when (bobp) (indent-line-to 0)) ;;at the beginning indent at 0
(let* ((parent-position (nth 1 (syntax-ppss))) ;; take the current indentation of the enclosing expression
(parent-indent (if parent-position
(save-excursion (goto-char parent-position) (current-indentation))
0))
(current-indent (current-indentation))
(previous-line-indentation (and
(not (bobp))
(save-excursion
(forward-line -1)
(current-indentation))))
(min-indentation (if parent-position (+ parent-indent tab-width) 0))
(max-indentation (+ previous-line-indentation tab-width)))
(cond
((and parent-position (looking-at "\\s-*\\s)"))
(setq new-indent parent-indent))
((= current-indent min-indentation)
(setq new-indent max-indentation))
((< current-indent min-indentation) ;; usually after a newline.
(setq new-indent (max previous-line-indentation min-indentation)))
((> current-indent max-indentation)
(setq new-indent max-indentation))
((<= current-indent max-indentation)
(setq new-indent (- current-indent tab-width))))))
(when new-indent
(indent-line-to new-indent))))
;;;###autoload (autoload 'alan-grammar-mode "alan-mode")
(alan-define-mode alan-grammar-mode
"Major mode for editing Alan grammar files."
:language "dependencies/dev/internals/alan/language"
:pairs (("[" . "]"))
:keywords ((("rules" "root" "component" "indent" "keywords" "collection" "order"
"predecessors" "successors" "group" "number" "reference" "stategroup"
"has" "first" "last" "predecessor" "successor" "text" "[" "]" ","
) . font-lock-builtin-face))
(electric-indent-local-mode -1)
(local-set-key (kbd "RET") 'newline-and-indent)
(set (make-local-variable 'indent-line-function) 'alan-grammar-mode-indent-line))
(defun alan-template-yank ()
"Yank but wrap as template."
(interactive)
(let ((string-to-yank (current-kill 0 t)))
(insert (mapconcat 'identity
(mapcar (lambda (s)
(format "\"%s\"" (replace-regexp-in-string "\"" "\\\\\"" s)))
(split-string string-to-yank "\n"))
"\n"))))
;;;###autoload (autoload 'alan-template-mode "alan-mode")
(alan-define-mode alan-template-mode
"Major mode for editing Alan template files."
:file-pattern "\\.template$"
:language "dependencies/dev/internals/alan-to-text-transformation/language")
(defun alan-list-nummerical-types ()
"Return a list of all nummerical types."
(save-mark-and-excursion
(save-restriction
(widen)
(goto-char (point-max))
(let ((numerical-types-point (re-search-backward "^numerical-types"))
(numerical-types (list)))
(when numerical-types-point
(while (re-search-forward "^\\s-*'\\([^']*\\)'" nil t)
(add-to-list 'numerical-types (match-string 1))))
numerical-types))))
;;;###autoload (autoload 'alan-application-mode "alan-mode")
(alan-define-mode alan-application-mode
"Major mode for editing Alan application model files."
:pairs (("{" . "}"))
:keywords (
("^\\(users\\|roles\\|root\\|numerical-types\\)" . font-lock-keyword-face)
("\\(:\\|:=\\)\\s-+\\(stategroup\\|component\\|group\\|file\\|collection\\|command\\|reference-set\\|natural\\|integer\\|text\\)\\(\\s-+\\|$\\)" 2 font-lock-type-face)
(("today" "now" "zero" "true" "false") . font-lock-constant-face)
(( "@date" "@date-time" "@default:" "@description:" "@desired"
"@dormant" "@duration:" "@factor:" "@guid" "@hidden"
"@identifying" "@key-description:" "@label:" "@linked" "@max:"
"@metadata" "@min:" "@multi-line" "@name" "@namespace" "@small"
"@sticky" "@validate:" "@verified" "@visible" )
. font-lock-keyword-face)
(("add" "branch" "ceil" "convert" "count" "division" "floor" "increment"
"max" "min" "remainder" "subtract" "sum" "sumlist" "base" "diff"
"product")
. font-lock-function-name-face)
(("#" "#reader" "#writer" "$" "$^" "%" "%^" "%}" "&#" "&" "*" "+" "+^" ","
"-" "-<" "->" "." ".^" ".key" ".self" ".}" "/" "10^" ":" ":=" "<" "<-"
"<=" "=" "==" "=>" ">" ">=" ">key" "?" "?^" "@%^" "@" "@?^" "@date"
"@date-time" "@default:" "@description:" "@desired" "@dormant"
"@duration:" "@factor:" "@guid" "@hidden" "@identifying"
"@key-description:" "@label:" "@linked" "@max:" "@metadata" "@min:"
"@multi-line" "@name" "@namespace" "@small" "@sticky" "@validate:"
"@verified" "@visible" "[" "]" "^" "acyclic-graph" "add" "and" "anonymous"
"any" "as" "base" "ceil" "collection" "command" "component" "count"
"create" "created" "creation-time" "delete" "dense" "deprecated"
"dictionary" "diff" "division" "do" "dynamic" "entry" "external" "false"
"file" "floor" "forward" "from" "group" "hours" "if" "ignore" "in"
"increment" "integer" "interface" "invalidate" "inverse" "join"
"life-time" "log" "mapping" "match" "match-branch" "matrix" "max" "min"
"minutes" "mutation-time" "natural" "new" "node" "now" "number"
"numerical-types" "on" "one" "ontimeout" "ordered-graph" "password"
"product" "reference" "reference-set" "referencer" "remainder" "remove"
"rename" "roles" "root" "seconds" "space" "sparse" "stategroup" "std"
"subtract" "sum" "sumlist" "switch" "text" "timer" "today" "true" "union"
"unsafe" "update" "users" "with" "workfor" "zero" "|" "~>" ) . font-lock-builtin-face))
:propertize-rules (("[\\.%]\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-widget-mode "alan-mode")
(alan-define-mode alan-widget-mode
"Major mode for editing Alan widget model files."
:file-pattern "widgets/.*\\.ui\\.alan$"
:pairs (("{" . "}") ("[" . "]"))
:keywords ((( "#" "$" "*" "," "->" "." ".}" ":" "::" "=>" ">" ">>" "?" "@"
"^" "binding" "configuration" "control" "current" "dictionary"
"empty" "engine" "file" "format" "inline" "instruction" "interval"
"let" "list" "markup" "number" "on" "set" "state" "stategroup"
"static" "switch" "text" "time" "to" "transform" "unconstrained"
"view" "widget" "window" "|" ) . font-lock-builtin-face))
:propertize-rules (("\\.\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-views-mode "alan-mode")
(alan-define-mode alan-views-mode
"Major mode for editing Alan views files."
:pairs (("{" . "}") ("[" . "]"))
:file-pattern "views/.*\\.ui\\.alan$"
:propertize-rules (("/?%\\(}\\)" (1 "_")))
:keywords ((( "$" "%" "%^" "%}" "*" "+" "+^" "-" "->" "." ".>" ".^" "/%}" "/>"
":>" "<" "<<" "<=" "=" "==" ">" ">=" ">>" "?" "?^" "@" "as"
"candidates" "collection" "command" "disabled" "enabled" "entity"
"file" "filter" "from" "group" "id" "inline" "key" "limit" "link"
"matrix" "node" "none" "now" "number" "of" "on" "open" "path"
"query" "reference" "refresh" "role" "root" "selected"
"stategroup" "subscribe" "text" "using" "view" "window")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-wiring-mode "alan-mode")
(alan-define-mode alan-wiring-mode
"Major mode for editing Alan wiring files."
:keywords ((("interfaces:" "external-systems:" "systems:" "provides:"
"consumes:" "provided-connections:" "from" "external" "internal"
"(" ")" "." "=" "message" "custom")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-deployment-mode "alan-mode")
(alan-define-mode alan-deployment-mode
"Major mode for editing Alan deployment files."
:language "devenv/platform/project-build-environment/language"
:keywords ((("external-systems:" "instance-data:" "system-options:"
"provided-connections:" ":" "." "from" "local" "remote" "stack"
"system" "migrate" "timezone" "interface" "message" "custom"
"socket" "schedule" "at" "never" "every" "day" "hour" "Monday"
"Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" )
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-mapping-mode "alan-mode")
(alan-define-mode alan-mapping-mode
"Major mode for editing Alan mapping files."
:keywords ((("#" "%" "(" ")" "+" "." "/" ":" ":=" "=" "=>" ">" "?" "@" "|"
"causal" "collection" "command" "do" "file" "group" "integer"
"interfaces" "log" "natural" "number" "on" "reference-set"
"roles" "root" "stategroup" "switch" "text" "with")
. font-lock-builtin-face)))
(provide 'alan-mode)
;;; alan-mode.el ends here
| true | ;;; alan-mode.el --- Major mode for editing M-industries Alan files
;; Copyright (C) 2018 M-industries
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Version: 1.0.0
;; Created: 13 October 2017
;; URL: https://github.com/M-industries/AlanForEmacs
;; Homepage: https://alan-platform.com/
;; Keywords: alan, languages
;; Package-Requires: ((flycheck "32") (emacs "25.1") (s "1.12"))
;; MIT License
;; Copyright (c) 2017 M-industries
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; This file is not part of GNU Emacs.
;;; Commentary:
;; A major mode for editing Alan files.
(require 'flycheck)
(require 'timer)
(require 'xref)
(require 's)
;;; Code:
(add-to-list 'auto-mode-alist '("\\.alan$" . alan-mode))
(defgroup alan nil
"Alan mode."
:prefix "alan-"
:group 'tools)
(defcustom alan-xref-limit-to-project-scope t
"Limits symbol lookup to the open buffers in project scope.
Only available when projectile is loaded, because it is based on
the function `projectile-project-root'"
:group 'alan
:type '(boolean))
(defcustom alan-compiler "compiler-project"
"The alan compiler.
This one is used when the variable `alan-project-root' cannot be
resolved to an existing directory."
:group 'alan
:type '(string))
(defcustom alan-script "alan"
"The alan build script file."
:group 'alan
:type '(string))
(defcustom alan-language-definition nil
"The Alan language to use.
Setting this will try to use the `alan-compiler' instead of the `alan-script'."
:group 'alan
:safe 'stringp)
(make-variable-buffer-local 'alan-language-definition)
;;; Alan mode
(defvar-local alan-mode-font-lock-keywords
'((("'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'" . font-lock-variable-name-face))
nil nil nil nil
(font-lock-syntactic-face-function . alan-font-lock-syntactic-face-function))
"Highlighting for alan mode")
(defvar alan-mode-syntax-table
(let ((alan-mode-syntax-table (make-syntax-table)))
(modify-syntax-entry ?* ". 23b" alan-mode-syntax-table)
(modify-syntax-entry ?/ ". 124" alan-mode-syntax-table)
(modify-syntax-entry ?\n ">" alan-mode-syntax-table)
(modify-syntax-entry ?' "\"" alan-mode-syntax-table)
(modify-syntax-entry ?{ "(}" alan-mode-syntax-table)
(modify-syntax-entry ?} "){" alan-mode-syntax-table)
alan-mode-syntax-table)
"Syntax table for ‘alan-mode’.")
;;;###autoload
(define-derived-mode alan-mode prog-mode "Alan"
"Major mode for editing Alan files."
:syntax-table alan-mode-syntax-table
:group 'alan
(setq comment-start "//")
(setq comment-end "")
(setq block-comment-start "/*")
(setq block-comment-end "*/")
(modify-syntax-entry ?\] "_" alan-mode-syntax-table)
(modify-syntax-entry ?\[ "_" alan-mode-syntax-table)
(setq font-lock-defaults alan-mode-font-lock-keywords)
(add-hook 'xref-backend-functions #'alan--xref-backend nil t)
(set (make-local-variable 'indent-line-function) 'alan-mode-indent-line)
(add-hook 'post-command-hook #'alan-update-header nil t)
(setq header-line-format ""))
(defvar alan-parent-regexp "\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)")
(defmacro alan-define-mode (name &optional docstring &rest body)
"Define NAME as an Alan major mode.
The mode derives from the generic `alan-mode'.
BODY can define keyword aguments.
:file-pattern
The file pattern to associate with the major mode. If none is
provided it will associate it with NAME.alan.
:keywords
A list of cons cells where the first is a regexp or a list of keywords
and the second element is the font-face.
:language
The path to the Alan language definition.
:pairs
A list of cons cells that match open and close parameters.
:propertize-rules
A list of rules used by `syntax-propertize-rules' When set will set the
propertize function for this mode.
The rest of the BODY is evaluated in the body of the derived-mode.
Optional argument DOCSTRING for the major mode."
(declare
(doc-string 2)
(indent 2))
(let* ((mode-name (intern (concat "alan-" (symbol-name name) "-mode")))
(language-name ;; name based on language naming convention.
(s-chop-suffix "-mode" (s-chop-prefix "alan-" (symbol-name name))))
(file-pattern ;; the naming convention for the file pattern is to use underscores.
(concat (s-replace "-" "_" language-name) ".alan"))
(keywords)
(language)
(pairs '())
(propertize-rules))
;; Process the keyword args.
(while (keywordp (car body))
(pcase (pop body)
(`:file-pattern (setq file-pattern (pop body)))
(`:keywords (setq keywords (pop body)))
(`:language (setq language (pop body)))
(`:pairs (setq pairs (pop body)))
(`:propertize-rules (setq propertize-rules (pop body)))
(_ (pop body))))
(when keywords
(setq keywords (mapcar (lambda (keyword-entry)
(if (listp (car keyword-entry))
(cons (regexp-opt (car keyword-entry)) (cdr keyword-entry))
keyword-entry)
) keywords)))
`(progn
(add-to-list 'auto-mode-alist '(,file-pattern . ,name))
(flycheck-add-mode 'alan ',name)
(define-derived-mode ,name alan-mode ,language-name
,docstring
:group 'alan
:after-hook (alan-setup-build-system)
,(when language
`(progn
(setq alan-language-definition ,language)))
,(when keywords
`(progn
(font-lock-add-keywords nil ',keywords "at end")))
,@(mapcar
(lambda (pair)
`(progn
(modify-syntax-entry ,(string-to-char (car pair)) ,(concat "(" (cdr pair)) alan-mode-syntax-table)
(modify-syntax-entry ,(string-to-char (cdr pair)) ,(concat ")" (car pair)) alan-mode-syntax-table)))
pairs)
,(when propertize-rules
`(progn
(set (make-local-variable 'syntax-propertize-function) (syntax-propertize-rules ,@propertize-rules))))
,@body))))
;;; Xref backend
(defun alan-boundry-of-identifier-at-point ()
"Return the beginning and end of an alan identifier or nil if point is not on an identifier."
(let ((text-properties (nth 1 (text-properties-at (point)))))
(when (or (and (listp text-properties)
(member font-lock-variable-name-face text-properties))
(eq font-lock-variable-name-face text-properties))
(save-excursion
(when-let* ((beginning (nth 8 (syntax-ppss)))
(end (progn (goto-char beginning) (forward-sexp) (point))))
(cons beginning end))))))
(put 'identifier 'bounds-of-thing-at-point 'alan-boundry-of-identifier-at-point)
(defun alan-thing-at-point ()
"Find alan variable at point."
(let ((boundary-pair (bounds-of-thing-at-point 'identifier)))
(if boundary-pair
(buffer-substring-no-properties
(car boundary-pair) (cdr boundary-pair)))))
(put 'identifier 'thing-at-point 'alan-thing-at-point)
;; todo add view definitions
;; todo add widget definitions
;; todo add control definitions
(defun alan--xref-backend () 'alan)
(defvar alan--xref-format
(let ((str "%s %s :%d"))
(put-text-property 0 2 'face 'font-lock-variable-name-face str)
(put-text-property 3 5 'face 'font-lock-function-name-face str)
str))
(defun alan--xref-make-xref (symbol type buffer symbol-position)
(xref-make (format alan--xref-format symbol type (line-number-at-pos symbol-position))
(xref-make-buffer-location buffer symbol-position)))
(defun alan--xref-find-definitions (symbol)
"Find all definitions matching SYMBOL."
(let ((xrefs)
(project-scope-limit (and
(featurep 'projectile)
alan-xref-limit-to-project-scope
(projectile-project-root))))
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(when (and (derived-mode-p 'alan-mode)
(or (null project-scope-limit)
(and (featurep 'projectile)
(string= project-scope-limit (projectile-project-root)))))
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(when (string= (match-string 1) symbol)
(add-to-list 'xrefs (alan--xref-make-xref symbol "" buffer (match-beginning 1)) t))))))))
xrefs))
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql alan)))
(alan-thing-at-point))
(cl-defmethod xref-backend-definitions ((_backend (eql alan)) symbol)
(alan--xref-find-definitions symbol))
(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql alan)))
(let (words)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(while (re-search-forward "^\\s-*\\('\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'\\)" nil t)
(add-to-list 'words (match-string-no-properties 1)))
(seq-uniq words)))))
;;; Alan functions
(defun alan--has-parent ()
"Return point of parent or nil otherwise."
(let ((line-to-ignore-regex "^\\s-*\\(//.*\\)?$"))
(save-excursion
(move-beginning-of-line 1)
(while (and (not (bobp))
(looking-at line-to-ignore-regex))
(forward-line -1))
(let ((start-indent (current-indentation))
(curr-indent (current-indentation))
(curr-point (point))
(start-line-number (line-number-at-pos)))
(defvar new-point)
(while (and (not (bobp))
(> start-indent 0)
(or (not (looking-at "\\s-*'\\([^'\n\\]\\|\\(\\\\'\\)\\|\\\\\\\)*'"))
(looking-at line-to-ignore-regex)
(> (current-indentation) curr-indent)
(<= start-indent (current-indentation))))
(forward-line -1)
(unless (looking-at line-to-ignore-regex)
(setq curr-indent (min curr-indent (current-indentation))))
(setq new-point (point)))
(if
(and
(looking-at alan-parent-regexp)
(not (equal start-line-number (line-number-at-pos))))
(match-beginning 1))))))
(defun alan-goto-parent ()
"Goto the parent of this property."
(interactive)
(let ((parent-position (alan--has-parent)))
(when (alan--has-parent)
(push-mark (point) t)
(goto-char parent-position))))
(defun alan-copy-path-to-clipboard ()
"Copy the path as shown in the header of the buffer.
This uses the `alan-path' function to get its value."
(interactive)
(let ((path (alan-path)))
(when path
(kill-new path))))
(defun alan-path ()
"Gives the location as a path of where you are in a file.
E.g. 'views' . 'queries' . 'context' . 'candidates' . 'of'"
(let ((path-list '())
has-parent)
(save-excursion
(while (setq has-parent (alan--has-parent))
(goto-char has-parent)
(add-to-list 'path-list (match-string 1))))
(if (> (length path-list) 0)
(mapconcat 'identity path-list " . ")
"")))
(defun alan-mode-indent-line ()
"Indentation based on parens.
Not suitable for white space significant languages."
(interactive)
(let (new-indent)
(save-excursion
(beginning-of-line)
(if (bobp)
;;at the beginning indent to 0
(indent-line-to 0))
;; take the current indentation of the enclosing expression
(let ((parent-position (nth 1 (syntax-ppss)))
(previous-line-indentation
(and (not (bobp))
(save-excursion (forward-line -1) (current-indentation)))))
(cond
(parent-position
(let ((parent-indent
(save-excursion
(goto-char parent-position)
(current-indentation))))
(if (looking-at "\\s-*\\s)") ;; looking at closing paren.
(setq new-indent parent-indent)
(setq new-indent ( + parent-indent tab-width)))))
(previous-line-indentation
(setq new-indent previous-line-indentation)))
;; check for single block and add a level of indentation.
(save-excursion
(back-to-indentation)
(if (and (looking-at "\\s(")
(eq (line-number-at-pos)
(progn (forward-sexp) (line-number-at-pos))))
(setq new-indent (min (if previous-line-indentation (+ previous-line-indentation tab-width) tab-width )
(+ new-indent tab-width)))))))
(when new-indent
(indent-line-to new-indent))))
(defun alan-font-lock-syntactic-face-function (state)
"Don't fontify single quoted strings.
STATE is the result of the function `parse-partial-sexp'."
(if (nth 3 state)
(let ((startpos (nth 8 state)))
(if (eq (char-after startpos) ?')
;; This is not a string, but an identifier.
nil
font-lock-string-face))
font-lock-comment-face))
(defvar-local alan--update-headline-timer nil)
(defun alan-update-header ()
"Update the header line after 0.5 seconds of idle time."
(when (timerp alan--update-headline-timer)
(cancel-timer alan--update-headline-timer))
(setq alan--update-headline-timer
(run-with-idle-timer
0.5 nil
(lambda (buffer-to-update)
(with-current-buffer buffer-to-update
(setq header-line-format (format " %s " (alan-path)))
(force-mode-line-update)))
(current-buffer))))
;;; Flycheck
(defun alan-flycheck-error-filter (error-list)
"Flycheck error filter for the Alan comopiler.
Do not include /dev/null and only show errors for the current buffer."
(seq-remove (lambda (error)
(or (string= (flycheck-error-filename error) "/dev/null")
(not (string= (flycheck-error-filename error) (buffer-file-name)))))
error-list))
(defvar-local alan--flycheck-language-definition nil
"The real path to the language definition if `alan-language-definition' can be resolved.")
(flycheck-define-checker alan
"An Alan syntax checker."
:command ("alan"
(eval (if (null alan--flycheck-language-definition)
'("build" "--format" "emacs")
`(,alan--flycheck-language-definition "--format" "emacs" "--log" "warning" "/dev/null"))))
:error-patterns
((error line-start (file-name) ":" line ":" column ": error:" (zero-or-one " " (one-or-more digit) ":" (one-or-more digit))
;; Messages start with a white space after the error.
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end)
(warning line-start (file-name) ":" line ":" column ": warning: " (one-or-more digit) ":" (one-or-more digit)
(message (zero-or-more not-newline)
(zero-or-more "\n " (zero-or-more not-newline)))
line-end))
:error-filter alan-flycheck-error-filter
:modes (alan-mode)) ;; all other modes are added using the `alan-define-mode' macro.
(add-to-list 'flycheck-checkers 'alan)
;;; Project root and build system
(defvar-local alan-project-root nil
"The project root set by function `alan-project-root'.")
(defun alan-project-root ()
"Project root folder determined based on the presence of a project.json or versions.json file.
If `alan-language-definition' is set prefer to use the
project.json over versions.json."
(or
alan-project-root
(setq alan-project-root
(expand-file-name
(or (let ((project-files ["versions.json" "project.json"]))
(seq-find
#'stringp
(seq-map (lambda (project-file)
(locate-dominating-file default-directory project-file))
;; Prefer to use project.json if `alan-language-definition' is set.
(if alan-language-definition (seq-reverse project-files) project-files))))
(progn
(message "Couldn't locate project root folder with a versions.json or project.json file. Using' %s' as project root." default-directory)
default-directory))))))
(defun alan-file-executable (file)
"Check if FILE is executable and return FILE."
(when (file-executable-p file) file))
(defun alan-find-alan-script ()
"Try to find the alan script in the dominating directory starting from the function `alan-project-root'.
Return nil if the script can not be found."
(when-let ((alan-project-script
(locate-dominating-file
(alan-project-root)
(lambda (name)
(let ((alan-script-candidate (concat name "alan")))
(and (file-executable-p alan-script-candidate)
(not (file-directory-p alan-script-candidate))))))))
(concat alan-project-script "alan")))
(defun alan--file-exists (name)
"Return the file NAME if it exists."
(when (file-exists-p name) name))
(defun alan-setup-build-system ()
"Setup Flycheck and the `compile-command'."
(let ((alan-project-script (or (alan-find-alan-script)
(executable-find alan-script)))
(alan-project-compiler (cond ((alan-file-executable (concat (alan-project-root) "dependencies/dev/internals/alan/tools/compiler-project")))
((alan-file-executable (concat (alan-project-root) "devenv/platform/project-compiler/tools/compiler-project")))))
(alan-project-language (concat (alan-project-root) alan-language-definition)))
(set (make-local-variable 'compilation-error-screen-columns) nil)
(cond
((and alan-project-compiler alan-language-definition)
(set (make-local-variable 'flycheck-alan-executable) alan-project-compiler)
(setq alan--flycheck-language-definition alan-project-language)
(set (make-local-variable 'compile-command)
(concat alan-project-compiler " " alan-project-language " --format emacs --log warning /dev/null ")))
((and alan-project-script)
(setq flycheck-alan-executable alan-project-script)
(set (make-local-variable 'compile-command) (concat alan-project-script " build emacs ")))
(t (message "No alan compiler or script found.")))))
;;; Modes
(defvar alan-imenu-generic-expression
;; Patterns to identify alan definitions
'(("dictionary" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* dictionary" 1)
("state group" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* stategroup" 1)
("component" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* component" 1)
("text" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* text" 1)
("number" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* number" 1)
("matrix" "^\\s-+'\\(\\(?:\\sw\\|\\s-+\\)*\\)'\\s-+->\\s-* \\(?:dense\\|sparse\\)matrix" 1)))
;;;###autoload (autoload 'alan-schema-mode "alan-mode")
(alan-define-mode alan-schema-mode
"Major mode for editing Alan schema files."
:language "dependencies/dev/internals/alan/language"
:keywords (("->\\s-+\\(stategroup\\|component\\|group\\|dictionary\\|command\\|densematrix\\|sparsematrix\\|reference\\|number\\|text\\)\\(\\s-+\\|$\\)" 1 font-lock-type-face)
(( "component" "types" "external" "->" "plural" "numerical"
"integer" "natural" "root" "]" ":" "*" "?" "~" "+" "constrain"
"acyclic" "ordered" "dictionary" "densematrix" "sparsematrix"
"$" "==" "!=" "group" "number" "reference" "stategroup" "text"
"." "!" "!&" "&" ".^" "+^" "}" ">" "*&" "?^" ">>" "forward"
"self" "{" "graph" "usage" "implicit" "ignore" "experimental"
"libraries" "using") . font-lock-builtin-face)))
(defun alan-grammar-update-keyword ()
"Update the keywords section based on all used keywords in this grammar file."
(interactive)
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((keyword-point (re-search-forward "^keywords$"))
(root-point (re-search-forward "^root$"))
(root-point-start (match-beginning 0)) ;; because the last search was for root
(alan-keywords (list)))
(while (re-search-forward "\\[\\(\\s-?'[^'
]+'\\s-?,?\\)+\\]" nil t) ;; there is a line end in the regex. Hence the weird break.
(let ((keyword-group (match-string 0))
(search-start 0))
(while (string-match "'[^']+'" keyword-group search-start)
(add-to-list 'alan-keywords (match-string 0 keyword-group))
(setq search-start (match-end 0)))))
(delete-region (+ 1 keyword-point) root-point-start)
(goto-char (+ 1 keyword-point))
(insert (string-join (mapcar (lambda (k) (concat "\t" k)) (sort (delete-dups alan-keywords ) 'string<)) "
"))
(insert "
")
(insert "
")))))
(defun alan-grammar-mode-indent-line ()
"Indentation based on parens and toggle indentation to min and max indentation possible."
(interactive)
(let
(new-indent)
(save-mark-and-excursion
(beginning-of-line)
(when (bobp) (indent-line-to 0)) ;;at the beginning indent at 0
(let* ((parent-position (nth 1 (syntax-ppss))) ;; take the current indentation of the enclosing expression
(parent-indent (if parent-position
(save-excursion (goto-char parent-position) (current-indentation))
0))
(current-indent (current-indentation))
(previous-line-indentation (and
(not (bobp))
(save-excursion
(forward-line -1)
(current-indentation))))
(min-indentation (if parent-position (+ parent-indent tab-width) 0))
(max-indentation (+ previous-line-indentation tab-width)))
(cond
((and parent-position (looking-at "\\s-*\\s)"))
(setq new-indent parent-indent))
((= current-indent min-indentation)
(setq new-indent max-indentation))
((< current-indent min-indentation) ;; usually after a newline.
(setq new-indent (max previous-line-indentation min-indentation)))
((> current-indent max-indentation)
(setq new-indent max-indentation))
((<= current-indent max-indentation)
(setq new-indent (- current-indent tab-width))))))
(when new-indent
(indent-line-to new-indent))))
;;;###autoload (autoload 'alan-grammar-mode "alan-mode")
(alan-define-mode alan-grammar-mode
"Major mode for editing Alan grammar files."
:language "dependencies/dev/internals/alan/language"
:pairs (("[" . "]"))
:keywords ((("rules" "root" "component" "indent" "keywords" "collection" "order"
"predecessors" "successors" "group" "number" "reference" "stategroup"
"has" "first" "last" "predecessor" "successor" "text" "[" "]" ","
) . font-lock-builtin-face))
(electric-indent-local-mode -1)
(local-set-key (kbd "RET") 'newline-and-indent)
(set (make-local-variable 'indent-line-function) 'alan-grammar-mode-indent-line))
(defun alan-template-yank ()
"Yank but wrap as template."
(interactive)
(let ((string-to-yank (current-kill 0 t)))
(insert (mapconcat 'identity
(mapcar (lambda (s)
(format "\"%s\"" (replace-regexp-in-string "\"" "\\\\\"" s)))
(split-string string-to-yank "\n"))
"\n"))))
;;;###autoload (autoload 'alan-template-mode "alan-mode")
(alan-define-mode alan-template-mode
"Major mode for editing Alan template files."
:file-pattern "\\.template$"
:language "dependencies/dev/internals/alan-to-text-transformation/language")
(defun alan-list-nummerical-types ()
"Return a list of all nummerical types."
(save-mark-and-excursion
(save-restriction
(widen)
(goto-char (point-max))
(let ((numerical-types-point (re-search-backward "^numerical-types"))
(numerical-types (list)))
(when numerical-types-point
(while (re-search-forward "^\\s-*'\\([^']*\\)'" nil t)
(add-to-list 'numerical-types (match-string 1))))
numerical-types))))
;;;###autoload (autoload 'alan-application-mode "alan-mode")
(alan-define-mode alan-application-mode
"Major mode for editing Alan application model files."
:pairs (("{" . "}"))
:keywords (
("^\\(users\\|roles\\|root\\|numerical-types\\)" . font-lock-keyword-face)
("\\(:\\|:=\\)\\s-+\\(stategroup\\|component\\|group\\|file\\|collection\\|command\\|reference-set\\|natural\\|integer\\|text\\)\\(\\s-+\\|$\\)" 2 font-lock-type-face)
(("today" "now" "zero" "true" "false") . font-lock-constant-face)
(( "@date" "@date-time" "@default:" "@description:" "@desired"
"@dormant" "@duration:" "@factor:" "@guid" "@hidden"
"@identifying" "@key-description:" "@label:" "@linked" "@max:"
"@metadata" "@min:" "@multi-line" "@name" "@namespace" "@small"
"@sticky" "@validate:" "@verified" "@visible" )
. font-lock-keyword-face)
(("add" "branch" "ceil" "convert" "count" "division" "floor" "increment"
"max" "min" "remainder" "subtract" "sum" "sumlist" "base" "diff"
"product")
. font-lock-function-name-face)
(("#" "#reader" "#writer" "$" "$^" "%" "%^" "%}" "&#" "&" "*" "+" "+^" ","
"-" "-<" "->" "." ".^" ".key" ".self" ".}" "/" "10^" ":" ":=" "<" "<-"
"<=" "=" "==" "=>" ">" ">=" ">key" "?" "?^" "@%^" "@" "@?^" "@date"
"@date-time" "@default:" "@description:" "@desired" "@dormant"
"@duration:" "@factor:" "@guid" "@hidden" "@identifying"
"@key-description:" "@label:" "@linked" "@max:" "@metadata" "@min:"
"@multi-line" "@name" "@namespace" "@small" "@sticky" "@validate:"
"@verified" "@visible" "[" "]" "^" "acyclic-graph" "add" "and" "anonymous"
"any" "as" "base" "ceil" "collection" "command" "component" "count"
"create" "created" "creation-time" "delete" "dense" "deprecated"
"dictionary" "diff" "division" "do" "dynamic" "entry" "external" "false"
"file" "floor" "forward" "from" "group" "hours" "if" "ignore" "in"
"increment" "integer" "interface" "invalidate" "inverse" "join"
"life-time" "log" "mapping" "match" "match-branch" "matrix" "max" "min"
"minutes" "mutation-time" "natural" "new" "node" "now" "number"
"numerical-types" "on" "one" "ontimeout" "ordered-graph" "password"
"product" "reference" "reference-set" "referencer" "remainder" "remove"
"rename" "roles" "root" "seconds" "space" "sparse" "stategroup" "std"
"subtract" "sum" "sumlist" "switch" "text" "timer" "today" "true" "union"
"unsafe" "update" "users" "with" "workfor" "zero" "|" "~>" ) . font-lock-builtin-face))
:propertize-rules (("[\\.%]\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-widget-mode "alan-mode")
(alan-define-mode alan-widget-mode
"Major mode for editing Alan widget model files."
:file-pattern "widgets/.*\\.ui\\.alan$"
:pairs (("{" . "}") ("[" . "]"))
:keywords ((( "#" "$" "*" "," "->" "." ".}" ":" "::" "=>" ">" ">>" "?" "@"
"^" "binding" "configuration" "control" "current" "dictionary"
"empty" "engine" "file" "format" "inline" "instruction" "interval"
"let" "list" "markup" "number" "on" "set" "state" "stategroup"
"static" "switch" "text" "time" "to" "transform" "unconstrained"
"view" "widget" "window" "|" ) . font-lock-builtin-face))
:propertize-rules (("\\.\\(}\\)" (1 "_"))))
;;;###autoload (autoload 'alan-views-mode "alan-mode")
(alan-define-mode alan-views-mode
"Major mode for editing Alan views files."
:pairs (("{" . "}") ("[" . "]"))
:file-pattern "views/.*\\.ui\\.alan$"
:propertize-rules (("/?%\\(}\\)" (1 "_")))
:keywords ((( "$" "%" "%^" "%}" "*" "+" "+^" "-" "->" "." ".>" ".^" "/%}" "/>"
":>" "<" "<<" "<=" "=" "==" ">" ">=" ">>" "?" "?^" "@" "as"
"candidates" "collection" "command" "disabled" "enabled" "entity"
"file" "filter" "from" "group" "id" "inline" "key" "limit" "link"
"matrix" "node" "none" "now" "number" "of" "on" "open" "path"
"query" "reference" "refresh" "role" "root" "selected"
"stategroup" "subscribe" "text" "using" "view" "window")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-wiring-mode "alan-mode")
(alan-define-mode alan-wiring-mode
"Major mode for editing Alan wiring files."
:keywords ((("interfaces:" "external-systems:" "systems:" "provides:"
"consumes:" "provided-connections:" "from" "external" "internal"
"(" ")" "." "=" "message" "custom")
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-deployment-mode "alan-mode")
(alan-define-mode alan-deployment-mode
"Major mode for editing Alan deployment files."
:language "devenv/platform/project-build-environment/language"
:keywords ((("external-systems:" "instance-data:" "system-options:"
"provided-connections:" ":" "." "from" "local" "remote" "stack"
"system" "migrate" "timezone" "interface" "message" "custom"
"socket" "schedule" "at" "never" "every" "day" "hour" "Monday"
"Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday" )
. font-lock-builtin-face)))
;;;###autoload (autoload 'alan-mapping-mode "alan-mode")
(alan-define-mode alan-mapping-mode
"Major mode for editing Alan mapping files."
:keywords ((("#" "%" "(" ")" "+" "." "/" ":" ":=" "=" "=>" ">" "?" "@" "|"
"causal" "collection" "command" "do" "file" "group" "integer"
"interfaces" "log" "natural" "number" "on" "reference-set"
"roles" "root" "stategroup" "switch" "text" "with")
. font-lock-builtin-face)))
(provide 'alan-mode)
;;; alan-mode.el ends here
|
[
{
"context": "n current line if region undefined\" 'nil :commit \"a60e022b30c2f4d3118bcaef1adb77b90e0ca941\" :keywords '(\"kill\" \"yank\" \"cut\" \"copy\" \"paste\" \"",
"end": 186,
"score": 0.5900166034698486,
"start": 146,
"tag": "PASSWORD",
"value": "a60e022b30c2f4d3118bcaef1adb77b90e0ca941"
}
] | elpa-25.2/whole-line-or-region-20110901.130/whole-line-or-region-pkg.el | taoyr/emacs | 0 | ;;; -*- no-byte-compile: t -*-
(define-package "whole-line-or-region" "20110901.130" "operate on current line if region undefined" 'nil :commit "a60e022b30c2f4d3118bcaef1adb77b90e0ca941" :keywords '("kill" "yank" "cut" "copy" "paste" "whole" "lines"))
| 29592 | ;;; -*- no-byte-compile: t -*-
(define-package "whole-line-or-region" "20110901.130" "operate on current line if region undefined" 'nil :commit "<PASSWORD>" :keywords '("kill" "yank" "cut" "copy" "paste" "whole" "lines"))
| true | ;;; -*- no-byte-compile: t -*-
(define-package "whole-line-or-region" "20110901.130" "operate on current line if region undefined" 'nil :commit "PI:PASSWORD:<PASSWORD>END_PI" :keywords '("kill" "yank" "cut" "copy" "paste" "whole" "lines"))
|
[
{
"context": "hat can be found in the LICENSE file.\n\n;;; Author: Philippe Ivaldi for OVYA\n;; Source: Some pieces of code are copie",
"end": 258,
"score": 0.9998825788497925,
"start": 243,
"tag": "NAME",
"value": "Philippe Ivaldi"
},
{
"context": "ode are copied from go-mode.el https://github.com/dominikh/go-mode.el\n;; Version: 1.0\n;; Keywords: languages",
"end": 353,
"score": 0.9985187649726868,
"start": 345,
"tag": "USERNAME",
"value": "dominikh"
},
{
"context": "Executable dependency\" \"https://github.com/FriendsOfPHP/PHP-CS-Fixer\"))\n\n(defcustom php-cs-fixer-command ",
"end": 928,
"score": 0.529753565788269,
"start": 923,
"tag": "USERNAME",
"value": "OfPHP"
},
{
"context": "\n;; Copy of go--goto-line from https://github.com/dominikh/go-mode.el\n(defun php-cs-fixer--goto-line (line)\n",
"end": 2088,
"score": 0.9987236261367798,
"start": 2080,
"tag": "USERNAME",
"value": "dominikh"
},
{
"context": "ed of go--apply-rcs-patch from https://github.com/dominikh/go-mode.el\n(defun php-cs-fixer--apply-rcs-patch (",
"end": 2540,
"score": 0.9986568093299866,
"start": 2532,
"tag": "USERNAME",
"value": "dominikh"
}
] | php-cs-fixer.el | emacsmirror/php-cs-fixer | 13 | ;;; php-cs-fixer.el --- php-cs-fixer wrapper.
;;; License:
;; Copyright 2015 OVYA (Renée Costes Group). All rights reserved.
;; Use of this source code is governed by a BSD-style
;; license that can be found in the LICENSE file.
;;; Author: Philippe Ivaldi for OVYA
;; Source: Some pieces of code are copied from go-mode.el https://github.com/dominikh/go-mode.el
;; Version: 1.0
;; Keywords: languages php
;; Package-Requires: ((cl-lib "0.5"))
;; URL: https://github.com/OVYA/php-cs-fixer
;;
;;; Commentary:
;; This file is not part of GNU Emacs.
;; See the file README.org for further information.
;;; Code:
(require 'cl-lib)
;;;###autoload
(defgroup php-cs-fixer nil
"php-cs-fixer wrapper."
:tag "PHP"
:prefix "php-cs-fixer-"
:group 'languages
:link '(url-link :tag "Source code repository" "https://github.com/OVYA/php-cs-fixer")
:link '(url-link :tag "Executable dependency" "https://github.com/FriendsOfPHP/PHP-CS-Fixer"))
(defcustom php-cs-fixer-command "php-cs-fixer"
"The 'php-cs-fixer' command."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-config-option nil
"The 'php-cs-fixer' config option.
If not nil `php-cs-rules-level-part-options`
and `php-cs-rules-fixer-part-options` are not used."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-level-part-options '("@Symfony")
"The 'php-cs-fixer' --rules base part options."
:type '(repeat
(choice
;; (const :tag "Not set" :value nil)
(const :value "@PSR0")
(const :value "@PSR1")
(const :value "@PSR2")
(const :value "@Symfony")
(const :value "@Symfony::risky")
(const :value "@PHP70Migration:risky")
))
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-fixer-part-options
'("no_multiline_whitespace_before_semicolons" "concat_space")
"The 'php-cs-fixer' --rules part options.
These options are not part of `php-cs-fixer-rules-level-part-options`."
:type '(repeat string)
:group 'php-cs-fixer)
;; Copy of go--goto-line from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--goto-line (line)
"Private goto line to LINE."
(goto-char (point-min))
(forward-line (1- line)))
(defun php-cs-fixer--delete-whole-line (&optional arg)
"Delete the current line without putting it in the `kill-ring`.
Derived from the function `kill-whole-line'.
ARG is defined as for that function."
(let (kill-ring) (kill-whole-line arg)))
;; Derivated of go--apply-rcs-patch from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--apply-rcs-patch (patch-buffer)
"Apply an RCS-formatted diff from PATCH-BUFFER to the current buffer."
(let ((target-buffer (current-buffer))
;; Relative offset between buffer line numbers and line numbers
;; in patch.
;;
;; Line numbers in the patch are based on the source file, so
;; we have to keep an offset when making changes to the
;; buffer.
;;
;; Appending lines decrements the offset (possibly making it
;; negative), deleting lines increments it. This order
;; simplifies the forward-line invocations.
(line-offset 0))
(save-excursion
(with-current-buffer patch-buffer
(goto-char (point-min))
(while (not (eobp))
(unless (looking-at "^\\([ad]\\)\\([0-9]+\\) \\([0-9]+\\)")
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch"))
(forward-line)
(let ((action (match-string 1))
(from (string-to-number (match-string 2)))
(len (string-to-number (match-string 3))))
(cond
((equal action "a")
(let ((start (point)))
(forward-line len)
(let ((text (buffer-substring start (point))))
(with-current-buffer target-buffer
(cl-decf line-offset len)
(goto-char (point-min))
(forward-line (- from len line-offset))
(insert text)))))
((equal action "d")
(with-current-buffer target-buffer
(php-cs-fixer--goto-line (- from line-offset))
(cl-incf line-offset len)
(php-cs-fixer--delete-whole-line len)))
(t
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch")))))))))
(defun php-cs-fixer--kill-error-buffer (errbuf)
"Private function that kill the error buffer ERRBUF."
(let ((win (get-buffer-window errbuf)))
(if win
(quit-window t win)
(kill-buffer errbuf))))
(defun php-cs-fixer--build-rules-options ()
"Private method to build the --rules options."
(if php-cs-fixer-config-option ""
(let ((base-opts
(concat
(if php-cs-fixer-rules-level-part-options
(concat (mapconcat 'identity php-cs-fixer-rules-level-part-options ",") ",")
nil)
"-psr0" ;; Because tmpfile can not support this constraint
))
(other-opts (if php-cs-fixer-rules-fixer-part-options (concat "," (mapconcat 'identity php-cs-fixer-rules-fixer-part-options ",")) nil)))
(concat
"--rules=" base-opts
(if other-opts other-opts "")))
))
(defvar php-cs-fixer-command-not-found-msg "Command php-cs-fixer not found.
Fix this issue removing the Emacs package php-cs-fixer or installing the program php-cs-fixer")
(defvar php-cs-fixer-command-bad-version-msg "Command php-cs-fixer version not supported.
Fix this issue removing the Emacs package php-cs-fixer or updating the program php-cs-fixer to version 2.*")
(defvar php-cs-fixer-is-command-ok-var nil)
(defun php-cs-fixer--is-command-ok ()
"Private Method.
Return t if the command `php-cs-fixer-command`
is available and supported by this package, return nil otherwise.
The test is done at first call and the same result will returns
for the next calls."
(if php-cs-fixer-is-command-ok-var
(= 1 php-cs-fixer-is-command-ok-var)
(progn
(message "Testing php-cs-fixer existence and version...")
(setq php-cs-fixer-is-command-ok-var 0)
(if (executable-find php-cs-fixer-command)
(if (string-match ".+ [2-3].[0-9]+.*"
(shell-command-to-string
(concat php-cs-fixer-command " --version")))
(progn (setq php-cs-fixer-is-command-ok-var 1) t)
(progn
(warn php-cs-fixer-command-bad-version-msg)
nil))
(progn (warn php-cs-fixer-command-not-found-msg) nil)
))))
;;;###autoload
(defun php-cs-fixer-fix ()
"Formats the current PHP buffer according to the PHP-CS-Fixer tool."
(interactive)
(when (php-cs-fixer--is-command-ok)
(let ((tmpfile (make-temp-file "PHP-CS-Fixer" nil ".php"))
(patchbuf (get-buffer-create "*PHP-CS-Fixer patch*"))
(errbuf (get-buffer-create "*PHP-CS-Fixer Errors*"))
(coding-system-for-read 'utf-8)
(coding-system-for-write 'utf-8))
(save-restriction
(widen)
(if errbuf
(with-current-buffer errbuf
(setq buffer-read-only nil)
(erase-buffer)))
(with-current-buffer patchbuf
(erase-buffer))
(write-region nil nil tmpfile)
;; We're using errbuf for the mixed stdout and stderr output. This
;; is not an issue because php-cs-fixer -q does not produce any stdout
;; output in case of success.
(if (zerop (call-process "php" nil errbuf nil "-l" tmpfile))
(progn
(call-process php-cs-fixer-command
nil errbuf nil
"fix"
(if php-cs-fixer-config-option
(concat "--config=" (shell-quote-argument php-cs-fixer-config-option))
(php-cs-fixer--build-rules-options))
"--using-cache=no"
"--quiet"
tmpfile)
(if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile))
(message "Buffer is already php-cs-fixed")
(php-cs-fixer--apply-rcs-patch patchbuf)
(message "Applied php-cs-fixer")))
(warn (with-current-buffer errbuf (buffer-string)))))
(php-cs-fixer--kill-error-buffer errbuf)
(kill-buffer patchbuf)
(delete-file tmpfile)
)))
;;;###autoload
(defun php-cs-fixer-before-save ()
"Used to automatically fix the file saving the buffer.
Add this to .emacs to run php-cs-fix on the current buffer when saving:
(add-hook 'before-save-hook 'php-cs-fixer-before-save)."
(interactive)
(when (and
buffer-file-name
(string= (file-name-extension buffer-file-name) "php")
(or (not (boundp 'geben-temporary-file-directory))
(not (string-match geben-temporary-file-directory (file-name-directory buffer-file-name))))
) (php-cs-fixer-fix)))
(provide 'php-cs-fixer)
;;; php-cs-fixer ends here
| 42531 | ;;; php-cs-fixer.el --- php-cs-fixer wrapper.
;;; License:
;; Copyright 2015 OVYA (Renée Costes Group). All rights reserved.
;; Use of this source code is governed by a BSD-style
;; license that can be found in the LICENSE file.
;;; Author: <NAME> for OVYA
;; Source: Some pieces of code are copied from go-mode.el https://github.com/dominikh/go-mode.el
;; Version: 1.0
;; Keywords: languages php
;; Package-Requires: ((cl-lib "0.5"))
;; URL: https://github.com/OVYA/php-cs-fixer
;;
;;; Commentary:
;; This file is not part of GNU Emacs.
;; See the file README.org for further information.
;;; Code:
(require 'cl-lib)
;;;###autoload
(defgroup php-cs-fixer nil
"php-cs-fixer wrapper."
:tag "PHP"
:prefix "php-cs-fixer-"
:group 'languages
:link '(url-link :tag "Source code repository" "https://github.com/OVYA/php-cs-fixer")
:link '(url-link :tag "Executable dependency" "https://github.com/FriendsOfPHP/PHP-CS-Fixer"))
(defcustom php-cs-fixer-command "php-cs-fixer"
"The 'php-cs-fixer' command."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-config-option nil
"The 'php-cs-fixer' config option.
If not nil `php-cs-rules-level-part-options`
and `php-cs-rules-fixer-part-options` are not used."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-level-part-options '("@Symfony")
"The 'php-cs-fixer' --rules base part options."
:type '(repeat
(choice
;; (const :tag "Not set" :value nil)
(const :value "@PSR0")
(const :value "@PSR1")
(const :value "@PSR2")
(const :value "@Symfony")
(const :value "@Symfony::risky")
(const :value "@PHP70Migration:risky")
))
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-fixer-part-options
'("no_multiline_whitespace_before_semicolons" "concat_space")
"The 'php-cs-fixer' --rules part options.
These options are not part of `php-cs-fixer-rules-level-part-options`."
:type '(repeat string)
:group 'php-cs-fixer)
;; Copy of go--goto-line from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--goto-line (line)
"Private goto line to LINE."
(goto-char (point-min))
(forward-line (1- line)))
(defun php-cs-fixer--delete-whole-line (&optional arg)
"Delete the current line without putting it in the `kill-ring`.
Derived from the function `kill-whole-line'.
ARG is defined as for that function."
(let (kill-ring) (kill-whole-line arg)))
;; Derivated of go--apply-rcs-patch from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--apply-rcs-patch (patch-buffer)
"Apply an RCS-formatted diff from PATCH-BUFFER to the current buffer."
(let ((target-buffer (current-buffer))
;; Relative offset between buffer line numbers and line numbers
;; in patch.
;;
;; Line numbers in the patch are based on the source file, so
;; we have to keep an offset when making changes to the
;; buffer.
;;
;; Appending lines decrements the offset (possibly making it
;; negative), deleting lines increments it. This order
;; simplifies the forward-line invocations.
(line-offset 0))
(save-excursion
(with-current-buffer patch-buffer
(goto-char (point-min))
(while (not (eobp))
(unless (looking-at "^\\([ad]\\)\\([0-9]+\\) \\([0-9]+\\)")
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch"))
(forward-line)
(let ((action (match-string 1))
(from (string-to-number (match-string 2)))
(len (string-to-number (match-string 3))))
(cond
((equal action "a")
(let ((start (point)))
(forward-line len)
(let ((text (buffer-substring start (point))))
(with-current-buffer target-buffer
(cl-decf line-offset len)
(goto-char (point-min))
(forward-line (- from len line-offset))
(insert text)))))
((equal action "d")
(with-current-buffer target-buffer
(php-cs-fixer--goto-line (- from line-offset))
(cl-incf line-offset len)
(php-cs-fixer--delete-whole-line len)))
(t
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch")))))))))
(defun php-cs-fixer--kill-error-buffer (errbuf)
"Private function that kill the error buffer ERRBUF."
(let ((win (get-buffer-window errbuf)))
(if win
(quit-window t win)
(kill-buffer errbuf))))
(defun php-cs-fixer--build-rules-options ()
"Private method to build the --rules options."
(if php-cs-fixer-config-option ""
(let ((base-opts
(concat
(if php-cs-fixer-rules-level-part-options
(concat (mapconcat 'identity php-cs-fixer-rules-level-part-options ",") ",")
nil)
"-psr0" ;; Because tmpfile can not support this constraint
))
(other-opts (if php-cs-fixer-rules-fixer-part-options (concat "," (mapconcat 'identity php-cs-fixer-rules-fixer-part-options ",")) nil)))
(concat
"--rules=" base-opts
(if other-opts other-opts "")))
))
(defvar php-cs-fixer-command-not-found-msg "Command php-cs-fixer not found.
Fix this issue removing the Emacs package php-cs-fixer or installing the program php-cs-fixer")
(defvar php-cs-fixer-command-bad-version-msg "Command php-cs-fixer version not supported.
Fix this issue removing the Emacs package php-cs-fixer or updating the program php-cs-fixer to version 2.*")
(defvar php-cs-fixer-is-command-ok-var nil)
(defun php-cs-fixer--is-command-ok ()
"Private Method.
Return t if the command `php-cs-fixer-command`
is available and supported by this package, return nil otherwise.
The test is done at first call and the same result will returns
for the next calls."
(if php-cs-fixer-is-command-ok-var
(= 1 php-cs-fixer-is-command-ok-var)
(progn
(message "Testing php-cs-fixer existence and version...")
(setq php-cs-fixer-is-command-ok-var 0)
(if (executable-find php-cs-fixer-command)
(if (string-match ".+ [2-3].[0-9]+.*"
(shell-command-to-string
(concat php-cs-fixer-command " --version")))
(progn (setq php-cs-fixer-is-command-ok-var 1) t)
(progn
(warn php-cs-fixer-command-bad-version-msg)
nil))
(progn (warn php-cs-fixer-command-not-found-msg) nil)
))))
;;;###autoload
(defun php-cs-fixer-fix ()
"Formats the current PHP buffer according to the PHP-CS-Fixer tool."
(interactive)
(when (php-cs-fixer--is-command-ok)
(let ((tmpfile (make-temp-file "PHP-CS-Fixer" nil ".php"))
(patchbuf (get-buffer-create "*PHP-CS-Fixer patch*"))
(errbuf (get-buffer-create "*PHP-CS-Fixer Errors*"))
(coding-system-for-read 'utf-8)
(coding-system-for-write 'utf-8))
(save-restriction
(widen)
(if errbuf
(with-current-buffer errbuf
(setq buffer-read-only nil)
(erase-buffer)))
(with-current-buffer patchbuf
(erase-buffer))
(write-region nil nil tmpfile)
;; We're using errbuf for the mixed stdout and stderr output. This
;; is not an issue because php-cs-fixer -q does not produce any stdout
;; output in case of success.
(if (zerop (call-process "php" nil errbuf nil "-l" tmpfile))
(progn
(call-process php-cs-fixer-command
nil errbuf nil
"fix"
(if php-cs-fixer-config-option
(concat "--config=" (shell-quote-argument php-cs-fixer-config-option))
(php-cs-fixer--build-rules-options))
"--using-cache=no"
"--quiet"
tmpfile)
(if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile))
(message "Buffer is already php-cs-fixed")
(php-cs-fixer--apply-rcs-patch patchbuf)
(message "Applied php-cs-fixer")))
(warn (with-current-buffer errbuf (buffer-string)))))
(php-cs-fixer--kill-error-buffer errbuf)
(kill-buffer patchbuf)
(delete-file tmpfile)
)))
;;;###autoload
(defun php-cs-fixer-before-save ()
"Used to automatically fix the file saving the buffer.
Add this to .emacs to run php-cs-fix on the current buffer when saving:
(add-hook 'before-save-hook 'php-cs-fixer-before-save)."
(interactive)
(when (and
buffer-file-name
(string= (file-name-extension buffer-file-name) "php")
(or (not (boundp 'geben-temporary-file-directory))
(not (string-match geben-temporary-file-directory (file-name-directory buffer-file-name))))
) (php-cs-fixer-fix)))
(provide 'php-cs-fixer)
;;; php-cs-fixer ends here
| true | ;;; php-cs-fixer.el --- php-cs-fixer wrapper.
;;; License:
;; Copyright 2015 OVYA (Renée Costes Group). All rights reserved.
;; Use of this source code is governed by a BSD-style
;; license that can be found in the LICENSE file.
;;; Author: PI:NAME:<NAME>END_PI for OVYA
;; Source: Some pieces of code are copied from go-mode.el https://github.com/dominikh/go-mode.el
;; Version: 1.0
;; Keywords: languages php
;; Package-Requires: ((cl-lib "0.5"))
;; URL: https://github.com/OVYA/php-cs-fixer
;;
;;; Commentary:
;; This file is not part of GNU Emacs.
;; See the file README.org for further information.
;;; Code:
(require 'cl-lib)
;;;###autoload
(defgroup php-cs-fixer nil
"php-cs-fixer wrapper."
:tag "PHP"
:prefix "php-cs-fixer-"
:group 'languages
:link '(url-link :tag "Source code repository" "https://github.com/OVYA/php-cs-fixer")
:link '(url-link :tag "Executable dependency" "https://github.com/FriendsOfPHP/PHP-CS-Fixer"))
(defcustom php-cs-fixer-command "php-cs-fixer"
"The 'php-cs-fixer' command."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-config-option nil
"The 'php-cs-fixer' config option.
If not nil `php-cs-rules-level-part-options`
and `php-cs-rules-fixer-part-options` are not used."
:type 'string
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-level-part-options '("@Symfony")
"The 'php-cs-fixer' --rules base part options."
:type '(repeat
(choice
;; (const :tag "Not set" :value nil)
(const :value "@PSR0")
(const :value "@PSR1")
(const :value "@PSR2")
(const :value "@Symfony")
(const :value "@Symfony::risky")
(const :value "@PHP70Migration:risky")
))
:group 'php-cs-fixer)
(defcustom php-cs-fixer-rules-fixer-part-options
'("no_multiline_whitespace_before_semicolons" "concat_space")
"The 'php-cs-fixer' --rules part options.
These options are not part of `php-cs-fixer-rules-level-part-options`."
:type '(repeat string)
:group 'php-cs-fixer)
;; Copy of go--goto-line from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--goto-line (line)
"Private goto line to LINE."
(goto-char (point-min))
(forward-line (1- line)))
(defun php-cs-fixer--delete-whole-line (&optional arg)
"Delete the current line without putting it in the `kill-ring`.
Derived from the function `kill-whole-line'.
ARG is defined as for that function."
(let (kill-ring) (kill-whole-line arg)))
;; Derivated of go--apply-rcs-patch from https://github.com/dominikh/go-mode.el
(defun php-cs-fixer--apply-rcs-patch (patch-buffer)
"Apply an RCS-formatted diff from PATCH-BUFFER to the current buffer."
(let ((target-buffer (current-buffer))
;; Relative offset between buffer line numbers and line numbers
;; in patch.
;;
;; Line numbers in the patch are based on the source file, so
;; we have to keep an offset when making changes to the
;; buffer.
;;
;; Appending lines decrements the offset (possibly making it
;; negative), deleting lines increments it. This order
;; simplifies the forward-line invocations.
(line-offset 0))
(save-excursion
(with-current-buffer patch-buffer
(goto-char (point-min))
(while (not (eobp))
(unless (looking-at "^\\([ad]\\)\\([0-9]+\\) \\([0-9]+\\)")
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch"))
(forward-line)
(let ((action (match-string 1))
(from (string-to-number (match-string 2)))
(len (string-to-number (match-string 3))))
(cond
((equal action "a")
(let ((start (point)))
(forward-line len)
(let ((text (buffer-substring start (point))))
(with-current-buffer target-buffer
(cl-decf line-offset len)
(goto-char (point-min))
(forward-line (- from len line-offset))
(insert text)))))
((equal action "d")
(with-current-buffer target-buffer
(php-cs-fixer--goto-line (- from line-offset))
(cl-incf line-offset len)
(php-cs-fixer--delete-whole-line len)))
(t
(error "Invalid rcs patch or internal error in php-cs-fixer--apply-rcs-patch")))))))))
(defun php-cs-fixer--kill-error-buffer (errbuf)
"Private function that kill the error buffer ERRBUF."
(let ((win (get-buffer-window errbuf)))
(if win
(quit-window t win)
(kill-buffer errbuf))))
(defun php-cs-fixer--build-rules-options ()
"Private method to build the --rules options."
(if php-cs-fixer-config-option ""
(let ((base-opts
(concat
(if php-cs-fixer-rules-level-part-options
(concat (mapconcat 'identity php-cs-fixer-rules-level-part-options ",") ",")
nil)
"-psr0" ;; Because tmpfile can not support this constraint
))
(other-opts (if php-cs-fixer-rules-fixer-part-options (concat "," (mapconcat 'identity php-cs-fixer-rules-fixer-part-options ",")) nil)))
(concat
"--rules=" base-opts
(if other-opts other-opts "")))
))
(defvar php-cs-fixer-command-not-found-msg "Command php-cs-fixer not found.
Fix this issue removing the Emacs package php-cs-fixer or installing the program php-cs-fixer")
(defvar php-cs-fixer-command-bad-version-msg "Command php-cs-fixer version not supported.
Fix this issue removing the Emacs package php-cs-fixer or updating the program php-cs-fixer to version 2.*")
(defvar php-cs-fixer-is-command-ok-var nil)
(defun php-cs-fixer--is-command-ok ()
"Private Method.
Return t if the command `php-cs-fixer-command`
is available and supported by this package, return nil otherwise.
The test is done at first call and the same result will returns
for the next calls."
(if php-cs-fixer-is-command-ok-var
(= 1 php-cs-fixer-is-command-ok-var)
(progn
(message "Testing php-cs-fixer existence and version...")
(setq php-cs-fixer-is-command-ok-var 0)
(if (executable-find php-cs-fixer-command)
(if (string-match ".+ [2-3].[0-9]+.*"
(shell-command-to-string
(concat php-cs-fixer-command " --version")))
(progn (setq php-cs-fixer-is-command-ok-var 1) t)
(progn
(warn php-cs-fixer-command-bad-version-msg)
nil))
(progn (warn php-cs-fixer-command-not-found-msg) nil)
))))
;;;###autoload
(defun php-cs-fixer-fix ()
"Formats the current PHP buffer according to the PHP-CS-Fixer tool."
(interactive)
(when (php-cs-fixer--is-command-ok)
(let ((tmpfile (make-temp-file "PHP-CS-Fixer" nil ".php"))
(patchbuf (get-buffer-create "*PHP-CS-Fixer patch*"))
(errbuf (get-buffer-create "*PHP-CS-Fixer Errors*"))
(coding-system-for-read 'utf-8)
(coding-system-for-write 'utf-8))
(save-restriction
(widen)
(if errbuf
(with-current-buffer errbuf
(setq buffer-read-only nil)
(erase-buffer)))
(with-current-buffer patchbuf
(erase-buffer))
(write-region nil nil tmpfile)
;; We're using errbuf for the mixed stdout and stderr output. This
;; is not an issue because php-cs-fixer -q does not produce any stdout
;; output in case of success.
(if (zerop (call-process "php" nil errbuf nil "-l" tmpfile))
(progn
(call-process php-cs-fixer-command
nil errbuf nil
"fix"
(if php-cs-fixer-config-option
(concat "--config=" (shell-quote-argument php-cs-fixer-config-option))
(php-cs-fixer--build-rules-options))
"--using-cache=no"
"--quiet"
tmpfile)
(if (zerop (call-process-region (point-min) (point-max) "diff" nil patchbuf nil "-n" "-" tmpfile))
(message "Buffer is already php-cs-fixed")
(php-cs-fixer--apply-rcs-patch patchbuf)
(message "Applied php-cs-fixer")))
(warn (with-current-buffer errbuf (buffer-string)))))
(php-cs-fixer--kill-error-buffer errbuf)
(kill-buffer patchbuf)
(delete-file tmpfile)
)))
;;;###autoload
(defun php-cs-fixer-before-save ()
"Used to automatically fix the file saving the buffer.
Add this to .emacs to run php-cs-fix on the current buffer when saving:
(add-hook 'before-save-hook 'php-cs-fixer-before-save)."
(interactive)
(when (and
buffer-file-name
(string= (file-name-extension buffer-file-name) "php")
(or (not (boundp 'geben-temporary-file-directory))
(not (string-match geben-temporary-file-directory (file-name-directory buffer-file-name))))
) (php-cs-fixer-fix)))
(provide 'php-cs-fixer)
;;; php-cs-fixer ends here
|
[
{
"context": "phically indicate the fill column\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"c",
"end": 115,
"score": 0.5221076607704163,
"start": 110,
"tag": "PASSWORD",
"value": "e7553"
},
{
"context": " indicate the fill column\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"conve",
"end": 119,
"score": 0.44923892617225647,
"start": 118,
"tag": "PASSWORD",
"value": "5"
},
{
"context": "icate the fill column\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"convenienc",
"end": 124,
"score": 0.45723992586135864,
"start": 122,
"tag": "PASSWORD",
"value": "9c"
},
{
"context": "ll column\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"convenience\"))\n",
"end": 135,
"score": 0.5034056901931763,
"start": 134,
"tag": "PASSWORD",
"value": "8"
},
{
"context": "column\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"convenience\"))\n",
"end": 138,
"score": 0.4489820897579193,
"start": 137,
"tag": "PASSWORD",
"value": "8"
},
{
"context": "lumn\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"convenience\"))\n",
"end": 140,
"score": 0.4452759325504303,
"start": 139,
"tag": "PASSWORD",
"value": "0"
},
{
"context": "n\" 'nil :commit \"0e755319451dd9c6c99c2a2ef82c890ba93343b6\" :keywords '(\"convenience\"))\n",
"end": 149,
"score": 0.4958241283893585,
"start": 142,
"tag": "PASSWORD",
"value": "93343b6"
}
] | elpa-24.5/fill-column-indicator-20151030.1233/fill-column-indicator-pkg.el | KevinBean/.emacs.d | 0 | (define-package "fill-column-indicator" "20151030.1233" "Graphically indicate the fill column" 'nil :commit "0e755319451dd9c6c99c2a2ef82c890ba93343b6" :keywords '("convenience"))
| 50348 | (define-package "fill-column-indicator" "20151030.1233" "Graphically indicate the fill column" 'nil :commit "0<PASSWORD>194<PASSWORD>1dd<PASSWORD>6c99c2a2ef<PASSWORD>2c<PASSWORD>9<PASSWORD>ba<PASSWORD>" :keywords '("convenience"))
| true | (define-package "fill-column-indicator" "20151030.1233" "Graphically indicate the fill column" 'nil :commit "0PI:PASSWORD:<PASSWORD>END_PI194PI:PASSWORD:<PASSWORD>END_PI1ddPI:PASSWORD:<PASSWORD>END_PI6c99c2a2efPI:PASSWORD:<PASSWORD>END_PI2cPI:PASSWORD:<PASSWORD>END_PI9PI:PASSWORD:<PASSWORD>END_PIbaPI:PASSWORD:<PASSWORD>END_PI" :keywords '("convenience"))
|
[
{
"context": "Packages\n\n(require 'comment) ; https://github.com/tonyaldon/emacs.d/blob/master/settings/packages/comment.el\n",
"end": 1501,
"score": 0.9994285106658936,
"start": 1492,
"tag": "USERNAME",
"value": "tonyaldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 4384,
"score": 0.99988853931427,
"start": 4374,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 4901,
"score": 0.9998890161514282,
"start": 4891,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 6306,
"score": 0.9998985528945923,
"start": 6296,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 6988,
"score": 0.9999032616615295,
"start": 6978,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 7542,
"score": 0.9998989105224609,
"start": 7532,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 8063,
"score": 0.9998964071273804,
"start": 8053,
"tag": "NAME",
"value": "Tony aldon"
},
{
"context": "t ((story\n \"#+TITLE: Inside Emacs\n#+AUTHOR: Tony aldon\n\n* a heading\n* another heading\n* scenes\n** scene ",
"end": 8964,
"score": 0.9998683929443359,
"start": 8954,
"tag": "NAME",
"value": "Tony aldon"
}
] | ie-story/ie-story-parse.el | tonyaldon/inside-emacs-tooling | 0 | ;;; About
;; A boring part but really important when making Inside Emacs videos
;; is to transform the story (written in a specific formated text
;; file) to beautiful footage. So far it involves 3 steps:
;; 1) parse the story (specific formated text),
;; 2) generate "svg" files (the story) from the specific
;; formated text,
;; 3) generate "kdenlive" files with the previous "svg" files.
;;
;; The part 1) is treated in this file, and the parts 2) and 3)
;; are treated in the file ./ie-story-generate.el
;;
;; In this file, we define the following parsing functions:
;; `ie-story-parse-goto-next-description',
;; `ie-story-parse-description',
;; `ie-story-parse-scene-title',
;; `ie-story-parse-next-scene',
;; `ie-story-parse-goto-next-scene',
;; `ie-story-parse-scenes'.
;;
;; The stories of Inside Emacs videos are written as described
;; bellow (and also in the file ./ie-story-template.org)
;;
;; * scenes
;; ** scene 0: intro
;; # description
;; a description splited
;; into two lines
;;
;; ** scene 1: First Scene
;; # description
;; A one line paragraph
;;
;; # description
;; we handle only
;; paragraph with 4 lines
;; to be readable
;; for the viewer
;;
;; The descriptions belong to subsections (** scene 1: scene title)
;; which belongs to the main section (* scenes). Each paragraph of
;; the story must start in the line following (# description) line and
;; end up at the first empty line.
;;; Packages
(require 'comment) ; https://github.com/tonyaldon/emacs.d/blob/master/settings/packages/comment.el
(require 'f)
(require 's)
;;; Parse story
(defun ie-story-parse-goto-next-description (&optional bound)
"Move point to the next description paragraph.
Return (point) if a description paragraph is found.
nil if not."
(when (looking-at "# description") (forward-char))
(when (search-forward "# description" bound t)
(next-line)
(beginning-of-line)
(point)))
(defun ie-story-parse-description (description-beginning)
"Return the description paragraph at DESCRIPTION-BEGINNING
as a list of string
Each element represents a line."
(save-excursion
(when description-beginning
(goto-char description-beginning)
(let ((description-end (progn (search-forward-regexp "^$" nil t)
(backward-char)
(point))))
(s-lines (buffer-substring-no-properties description-beginning
description-end))))))
(defun ie-story-parse-scene-title (scene-buffer-position
&optional kebab-case)
"Return the title of the scene at SCENE-BUFFER-POSITION.
If KEBAB-CASE is t, return the title of the scene but in kebab-case."
(save-excursion
(goto-char scene-buffer-position)
(search-forward-regexp ": *" nil t)
(let* ((beg (point))
(end (progn (end-of-line) (point)))
(name (buffer-substring-no-properties beg end)))
(if kebab-case
(s-downcase (s-replace " " "-" name))
name))))
(defun ie-story-parse-next-scene ()
"Return buffer position of the next scene heading."
(save-excursion
(when (looking-at "^\\** scene ") (forward-char))
(when (search-forward-regexp "^\\** scene " nil t)
(beginning-of-line)
(point))))
(defun ie-story-parse-goto-next-scene ()
"Go to the next heading scene."
(when-let ((next-scene (ie-story-parse-next-scene)))
(goto-char next-scene)))
(defun ie-story-parse-descriptions-in-scene (scene-buffer-position)
"Return the list of buffer position of the descriptions in the
scene SCENE-BUFFER-POSITION."
(save-excursion
(goto-char scene-buffer-position)
(let ((bound (ie-story-parse-next-scene))
description)
(while (ie-story-parse-goto-next-description bound)
(push (point) description))
(reverse description))))
(defun ie-story-parse-scenes ()
"Return the list of buffer position of the scenes in the current buffer."
(save-excursion
(beginning-of-buffer)
(let ((scenes '()))
(while (ie-story-parse-goto-next-scene)
(beginning-of-line)
(add-to-list 'scenes (point))
(next-line))
(reverse scenes))))
;;; Comments
;;;; ie-story-parse
(comment ; ie-story-parse-goto-next-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-description)
(equal (line-number-at-pos) 9))) ; t
)
(comment ; ie-story-parse-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader
")
description-beg-1 description-beg-2 description-beg-3)
(with-temp-buffer
(insert story)
(save-excursion
(setq description-beg-1
(progn (goto-char (point-min))
(forward-line (1- 9))
(point)))
(setq description-beg-2
(progn (goto-char (point-min))
(forward-line (1- 14))
(point)))
(setq description-beg-3
(progn (goto-char (point-min))
(forward-line (1- 17))
(point))))
(and (equal (ie-story-parse-description description-beg-1)
'("a description splited"
"into two lines"))
(equal (ie-story-parse-description description-beg-2)
'("A one line paragraph"))
(equal (ie-story-parse-description description-beg-3)
'("we handle only"
"paragraph with 4 lines"
"to be readable"
"for the reader")))))
)
(comment ; ie-story-parse-scene-title
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(goto-line 7)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
(goto-line 12)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
))
)
(comment ; ie-story-parse-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(let ((scene-0 (save-excursion (goto-line 7) (point))))
(equal (ie-story-parse-next-scene) scene-0)))) ; t
)
(comment ; ie-story-parse-goto-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-scene)
(equal (line-number-at-pos) 7))) ; t
)
(comment ; ie-story-parse-descriptions-in-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-0 (progn (goto-line 7) (point)))
(scene-0-desc-1 (progn (goto-line 9) (point)))
(scene-1 (progn (goto-line 12) (point)))
(scene-1-desc-1 (progn (goto-line 14) (point)))
(scene-1-desc-2 (progn (goto-line 17) (point))))
(equal (ie-story-parse-descriptions-in-scene scene-0)
(list scene-0-desc-1))
(equal (ie-story-parse-descriptions-in-scene scene-1)
(list scene-1-desc-1 scene-1-desc-2))
)))
)
(comment ; ie-story-parse-scenes
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: Tony aldon
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-1 (progn (goto-line 7) (point)))
(scene-2 (progn (goto-line 12) (point))))
(equal (ie-story-parse-scenes) (list scene-1 scene-2))))) ; t
)
;;;; emacs-lisp
(comment ; s-concat, s-join, f-join, f-mkdir
(f-join "r-images"
(s-concat
(s-join "-" `("description" "scene" ,(number-to-string 1)))
".svg")) ; "r-images/description-scene-1.svg"
(f-mkdir "dir-test")
(s-lines "uie\ntony") ; '("uie" "tony")
(s-replace " " "-" "tony aldon") ; "tony-aldon"
)
(comment ; reverse, pop, search-forward-regexp
(search-forward-regexp "^$")
(setq test-list '(a b c)) ; '(a b c)
(reverse test-list) ; '(c b a)
(pop test-list) ; a
test-list ; '(b c)
)
(comment ; push, nconc
(let ((l))
(push 1 l)
(push 2 l)) ; '(2 1)
(let ((l))
(setq l (nconc l '(1)))
(setq l (nconc l '(2))))
)
;;; Footer
(provide 'ie-story-parse)
| 9074 | ;;; About
;; A boring part but really important when making Inside Emacs videos
;; is to transform the story (written in a specific formated text
;; file) to beautiful footage. So far it involves 3 steps:
;; 1) parse the story (specific formated text),
;; 2) generate "svg" files (the story) from the specific
;; formated text,
;; 3) generate "kdenlive" files with the previous "svg" files.
;;
;; The part 1) is treated in this file, and the parts 2) and 3)
;; are treated in the file ./ie-story-generate.el
;;
;; In this file, we define the following parsing functions:
;; `ie-story-parse-goto-next-description',
;; `ie-story-parse-description',
;; `ie-story-parse-scene-title',
;; `ie-story-parse-next-scene',
;; `ie-story-parse-goto-next-scene',
;; `ie-story-parse-scenes'.
;;
;; The stories of Inside Emacs videos are written as described
;; bellow (and also in the file ./ie-story-template.org)
;;
;; * scenes
;; ** scene 0: intro
;; # description
;; a description splited
;; into two lines
;;
;; ** scene 1: First Scene
;; # description
;; A one line paragraph
;;
;; # description
;; we handle only
;; paragraph with 4 lines
;; to be readable
;; for the viewer
;;
;; The descriptions belong to subsections (** scene 1: scene title)
;; which belongs to the main section (* scenes). Each paragraph of
;; the story must start in the line following (# description) line and
;; end up at the first empty line.
;;; Packages
(require 'comment) ; https://github.com/tonyaldon/emacs.d/blob/master/settings/packages/comment.el
(require 'f)
(require 's)
;;; Parse story
(defun ie-story-parse-goto-next-description (&optional bound)
"Move point to the next description paragraph.
Return (point) if a description paragraph is found.
nil if not."
(when (looking-at "# description") (forward-char))
(when (search-forward "# description" bound t)
(next-line)
(beginning-of-line)
(point)))
(defun ie-story-parse-description (description-beginning)
"Return the description paragraph at DESCRIPTION-BEGINNING
as a list of string
Each element represents a line."
(save-excursion
(when description-beginning
(goto-char description-beginning)
(let ((description-end (progn (search-forward-regexp "^$" nil t)
(backward-char)
(point))))
(s-lines (buffer-substring-no-properties description-beginning
description-end))))))
(defun ie-story-parse-scene-title (scene-buffer-position
&optional kebab-case)
"Return the title of the scene at SCENE-BUFFER-POSITION.
If KEBAB-CASE is t, return the title of the scene but in kebab-case."
(save-excursion
(goto-char scene-buffer-position)
(search-forward-regexp ": *" nil t)
(let* ((beg (point))
(end (progn (end-of-line) (point)))
(name (buffer-substring-no-properties beg end)))
(if kebab-case
(s-downcase (s-replace " " "-" name))
name))))
(defun ie-story-parse-next-scene ()
"Return buffer position of the next scene heading."
(save-excursion
(when (looking-at "^\\** scene ") (forward-char))
(when (search-forward-regexp "^\\** scene " nil t)
(beginning-of-line)
(point))))
(defun ie-story-parse-goto-next-scene ()
"Go to the next heading scene."
(when-let ((next-scene (ie-story-parse-next-scene)))
(goto-char next-scene)))
(defun ie-story-parse-descriptions-in-scene (scene-buffer-position)
"Return the list of buffer position of the descriptions in the
scene SCENE-BUFFER-POSITION."
(save-excursion
(goto-char scene-buffer-position)
(let ((bound (ie-story-parse-next-scene))
description)
(while (ie-story-parse-goto-next-description bound)
(push (point) description))
(reverse description))))
(defun ie-story-parse-scenes ()
"Return the list of buffer position of the scenes in the current buffer."
(save-excursion
(beginning-of-buffer)
(let ((scenes '()))
(while (ie-story-parse-goto-next-scene)
(beginning-of-line)
(add-to-list 'scenes (point))
(next-line))
(reverse scenes))))
;;; Comments
;;;; ie-story-parse
(comment ; ie-story-parse-goto-next-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-description)
(equal (line-number-at-pos) 9))) ; t
)
(comment ; ie-story-parse-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader
")
description-beg-1 description-beg-2 description-beg-3)
(with-temp-buffer
(insert story)
(save-excursion
(setq description-beg-1
(progn (goto-char (point-min))
(forward-line (1- 9))
(point)))
(setq description-beg-2
(progn (goto-char (point-min))
(forward-line (1- 14))
(point)))
(setq description-beg-3
(progn (goto-char (point-min))
(forward-line (1- 17))
(point))))
(and (equal (ie-story-parse-description description-beg-1)
'("a description splited"
"into two lines"))
(equal (ie-story-parse-description description-beg-2)
'("A one line paragraph"))
(equal (ie-story-parse-description description-beg-3)
'("we handle only"
"paragraph with 4 lines"
"to be readable"
"for the reader")))))
)
(comment ; ie-story-parse-scene-title
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(goto-line 7)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
(goto-line 12)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
))
)
(comment ; ie-story-parse-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(let ((scene-0 (save-excursion (goto-line 7) (point))))
(equal (ie-story-parse-next-scene) scene-0)))) ; t
)
(comment ; ie-story-parse-goto-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-scene)
(equal (line-number-at-pos) 7))) ; t
)
(comment ; ie-story-parse-descriptions-in-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-0 (progn (goto-line 7) (point)))
(scene-0-desc-1 (progn (goto-line 9) (point)))
(scene-1 (progn (goto-line 12) (point)))
(scene-1-desc-1 (progn (goto-line 14) (point)))
(scene-1-desc-2 (progn (goto-line 17) (point))))
(equal (ie-story-parse-descriptions-in-scene scene-0)
(list scene-0-desc-1))
(equal (ie-story-parse-descriptions-in-scene scene-1)
(list scene-1-desc-1 scene-1-desc-2))
)))
)
(comment ; ie-story-parse-scenes
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: <NAME>
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-1 (progn (goto-line 7) (point)))
(scene-2 (progn (goto-line 12) (point))))
(equal (ie-story-parse-scenes) (list scene-1 scene-2))))) ; t
)
;;;; emacs-lisp
(comment ; s-concat, s-join, f-join, f-mkdir
(f-join "r-images"
(s-concat
(s-join "-" `("description" "scene" ,(number-to-string 1)))
".svg")) ; "r-images/description-scene-1.svg"
(f-mkdir "dir-test")
(s-lines "uie\ntony") ; '("uie" "tony")
(s-replace " " "-" "tony aldon") ; "tony-aldon"
)
(comment ; reverse, pop, search-forward-regexp
(search-forward-regexp "^$")
(setq test-list '(a b c)) ; '(a b c)
(reverse test-list) ; '(c b a)
(pop test-list) ; a
test-list ; '(b c)
)
(comment ; push, nconc
(let ((l))
(push 1 l)
(push 2 l)) ; '(2 1)
(let ((l))
(setq l (nconc l '(1)))
(setq l (nconc l '(2))))
)
;;; Footer
(provide 'ie-story-parse)
| true | ;;; About
;; A boring part but really important when making Inside Emacs videos
;; is to transform the story (written in a specific formated text
;; file) to beautiful footage. So far it involves 3 steps:
;; 1) parse the story (specific formated text),
;; 2) generate "svg" files (the story) from the specific
;; formated text,
;; 3) generate "kdenlive" files with the previous "svg" files.
;;
;; The part 1) is treated in this file, and the parts 2) and 3)
;; are treated in the file ./ie-story-generate.el
;;
;; In this file, we define the following parsing functions:
;; `ie-story-parse-goto-next-description',
;; `ie-story-parse-description',
;; `ie-story-parse-scene-title',
;; `ie-story-parse-next-scene',
;; `ie-story-parse-goto-next-scene',
;; `ie-story-parse-scenes'.
;;
;; The stories of Inside Emacs videos are written as described
;; bellow (and also in the file ./ie-story-template.org)
;;
;; * scenes
;; ** scene 0: intro
;; # description
;; a description splited
;; into two lines
;;
;; ** scene 1: First Scene
;; # description
;; A one line paragraph
;;
;; # description
;; we handle only
;; paragraph with 4 lines
;; to be readable
;; for the viewer
;;
;; The descriptions belong to subsections (** scene 1: scene title)
;; which belongs to the main section (* scenes). Each paragraph of
;; the story must start in the line following (# description) line and
;; end up at the first empty line.
;;; Packages
(require 'comment) ; https://github.com/tonyaldon/emacs.d/blob/master/settings/packages/comment.el
(require 'f)
(require 's)
;;; Parse story
(defun ie-story-parse-goto-next-description (&optional bound)
"Move point to the next description paragraph.
Return (point) if a description paragraph is found.
nil if not."
(when (looking-at "# description") (forward-char))
(when (search-forward "# description" bound t)
(next-line)
(beginning-of-line)
(point)))
(defun ie-story-parse-description (description-beginning)
"Return the description paragraph at DESCRIPTION-BEGINNING
as a list of string
Each element represents a line."
(save-excursion
(when description-beginning
(goto-char description-beginning)
(let ((description-end (progn (search-forward-regexp "^$" nil t)
(backward-char)
(point))))
(s-lines (buffer-substring-no-properties description-beginning
description-end))))))
(defun ie-story-parse-scene-title (scene-buffer-position
&optional kebab-case)
"Return the title of the scene at SCENE-BUFFER-POSITION.
If KEBAB-CASE is t, return the title of the scene but in kebab-case."
(save-excursion
(goto-char scene-buffer-position)
(search-forward-regexp ": *" nil t)
(let* ((beg (point))
(end (progn (end-of-line) (point)))
(name (buffer-substring-no-properties beg end)))
(if kebab-case
(s-downcase (s-replace " " "-" name))
name))))
(defun ie-story-parse-next-scene ()
"Return buffer position of the next scene heading."
(save-excursion
(when (looking-at "^\\** scene ") (forward-char))
(when (search-forward-regexp "^\\** scene " nil t)
(beginning-of-line)
(point))))
(defun ie-story-parse-goto-next-scene ()
"Go to the next heading scene."
(when-let ((next-scene (ie-story-parse-next-scene)))
(goto-char next-scene)))
(defun ie-story-parse-descriptions-in-scene (scene-buffer-position)
"Return the list of buffer position of the descriptions in the
scene SCENE-BUFFER-POSITION."
(save-excursion
(goto-char scene-buffer-position)
(let ((bound (ie-story-parse-next-scene))
description)
(while (ie-story-parse-goto-next-description bound)
(push (point) description))
(reverse description))))
(defun ie-story-parse-scenes ()
"Return the list of buffer position of the scenes in the current buffer."
(save-excursion
(beginning-of-buffer)
(let ((scenes '()))
(while (ie-story-parse-goto-next-scene)
(beginning-of-line)
(add-to-list 'scenes (point))
(next-line))
(reverse scenes))))
;;; Comments
;;;; ie-story-parse
(comment ; ie-story-parse-goto-next-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-description)
(equal (line-number-at-pos) 9))) ; t
)
(comment ; ie-story-parse-description
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader
")
description-beg-1 description-beg-2 description-beg-3)
(with-temp-buffer
(insert story)
(save-excursion
(setq description-beg-1
(progn (goto-char (point-min))
(forward-line (1- 9))
(point)))
(setq description-beg-2
(progn (goto-char (point-min))
(forward-line (1- 14))
(point)))
(setq description-beg-3
(progn (goto-char (point-min))
(forward-line (1- 17))
(point))))
(and (equal (ie-story-parse-description description-beg-1)
'("a description splited"
"into two lines"))
(equal (ie-story-parse-description description-beg-2)
'("A one line paragraph"))
(equal (ie-story-parse-description description-beg-3)
'("we handle only"
"paragraph with 4 lines"
"to be readable"
"for the reader")))))
)
(comment ; ie-story-parse-scene-title
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(goto-line 7)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
(goto-line 12)
(message "%s" (ie-story-parse-scene-title (point)))
(message "%s" (ie-story-parse-scene-title (point) t))
))
)
(comment ; ie-story-parse-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(let ((scene-0 (save-excursion (goto-line 7) (point))))
(equal (ie-story-parse-next-scene) scene-0)))) ; t
)
(comment ; ie-story-parse-goto-next-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(beginning-of-buffer)
(ie-story-parse-goto-next-scene)
(equal (line-number-at-pos) 7))) ; t
)
(comment ; ie-story-parse-descriptions-in-scene
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-0 (progn (goto-line 7) (point)))
(scene-0-desc-1 (progn (goto-line 9) (point)))
(scene-1 (progn (goto-line 12) (point)))
(scene-1-desc-1 (progn (goto-line 14) (point)))
(scene-1-desc-2 (progn (goto-line 17) (point))))
(equal (ie-story-parse-descriptions-in-scene scene-0)
(list scene-0-desc-1))
(equal (ie-story-parse-descriptions-in-scene scene-1)
(list scene-1-desc-1 scene-1-desc-2))
)))
)
(comment ; ie-story-parse-scenes
(let ((story
"#+TITLE: Inside Emacs
#+AUTHOR: PI:NAME:<NAME>END_PI
* a heading
* another heading
* scenes
** scene 0: intro
# description
a description splited
into two lines
** scene 1: First Scene
# description
A one line paragraph
# description
we handle only
paragraph with 4 lines
to be readable
for the reader"))
(with-temp-buffer
(insert story)
(let ((scene-1 (progn (goto-line 7) (point)))
(scene-2 (progn (goto-line 12) (point))))
(equal (ie-story-parse-scenes) (list scene-1 scene-2))))) ; t
)
;;;; emacs-lisp
(comment ; s-concat, s-join, f-join, f-mkdir
(f-join "r-images"
(s-concat
(s-join "-" `("description" "scene" ,(number-to-string 1)))
".svg")) ; "r-images/description-scene-1.svg"
(f-mkdir "dir-test")
(s-lines "uie\ntony") ; '("uie" "tony")
(s-replace " " "-" "tony aldon") ; "tony-aldon"
)
(comment ; reverse, pop, search-forward-regexp
(search-forward-regexp "^$")
(setq test-list '(a b c)) ; '(a b c)
(reverse test-list) ; '(c b a)
(pop test-list) ; a
test-list ; '(b c)
)
(comment ; push, nconc
(let ((l))
(push 1 l)
(push 2 l)) ; '(2 1)
(let ((l))
(setq l (nconc l '(1)))
(setq l (nconc l '(2))))
)
;;; Footer
(provide 'ie-story-parse)
|
[
{
"context": " databases provided by DICT server\n(global-set-key \"\\C-c\\M-b\" 'dictem-run-show-databases)\n\n(provide 'my-dictem",
"end": 1758,
"score": 0.9485806226730347,
"start": 1749,
"tag": "KEY",
"value": "\"\\C-c\\M-b"
}
] | config/my-dictem.el | suzp1984/emacs_d | 1 | (add-to-list 'load-path (expand-file-name "~/.emacs.d/emacs-lisp/dictem-1.0.4/"))
; Loading dictem functions
(require 'dictem)
; Setting the dictionary server hostname.
; This part is optional, if dictem-server is nil (the default value)
; "dict" command line utility will use its ows config file
; ~/.dictrc or PREFIX/etc/dict.conf.
; Keeping dictem-server variable unset is recomended because
; this allows to try _list of_ servers until connection is made,
; see dict(1) for details.
(setq dictem-server "localhost")
;(setq dictem-server "dict.org")
; Setting the dictionary server port.
; Setting dictem-port is usually not necessary because
; most DICT servers use the default port 2628.
;(setq dictem-port "2628")
; Code necessary to obtain database and strategy list from DICT
; server. As of version 0.90, dictem runs this function from
; dictem-select-database and dictem-select-strategy if an
; initialization was not completed or failed previously, that is
; running dictem-initialize is optional
(dictem-initialize)
; Assigning hot keys for accessing DICT server
; SEARCH = MATCH + DEFINE
; Ask for word, database and search strategy
; and show definitions found
(global-set-key "\C-cs" 'dictem-run-search)
; MATCH
; Ask for word, database and search strategy
; and show matches found
(global-set-key "\C-cm" 'dictem-run-match)
; DEFINE
; Ask for word and database name
; and show definitions found
(global-set-key "\C-cd" 'dictem-run-define)
; SHOW SERVER
; Show information about DICT server
(global-set-key "\C-c\M-r" 'dictem-run-show-server)
; SHOW INFO
; Show information about the database
(global-set-key "\C-c\M-i" 'dictem-run-show-info)
; SHOW DB
; Show a list of databases provided by DICT server
(global-set-key "\C-c\M-b" 'dictem-run-show-databases)
(provide 'my-dictem)
| 31722 | (add-to-list 'load-path (expand-file-name "~/.emacs.d/emacs-lisp/dictem-1.0.4/"))
; Loading dictem functions
(require 'dictem)
; Setting the dictionary server hostname.
; This part is optional, if dictem-server is nil (the default value)
; "dict" command line utility will use its ows config file
; ~/.dictrc or PREFIX/etc/dict.conf.
; Keeping dictem-server variable unset is recomended because
; this allows to try _list of_ servers until connection is made,
; see dict(1) for details.
(setq dictem-server "localhost")
;(setq dictem-server "dict.org")
; Setting the dictionary server port.
; Setting dictem-port is usually not necessary because
; most DICT servers use the default port 2628.
;(setq dictem-port "2628")
; Code necessary to obtain database and strategy list from DICT
; server. As of version 0.90, dictem runs this function from
; dictem-select-database and dictem-select-strategy if an
; initialization was not completed or failed previously, that is
; running dictem-initialize is optional
(dictem-initialize)
; Assigning hot keys for accessing DICT server
; SEARCH = MATCH + DEFINE
; Ask for word, database and search strategy
; and show definitions found
(global-set-key "\C-cs" 'dictem-run-search)
; MATCH
; Ask for word, database and search strategy
; and show matches found
(global-set-key "\C-cm" 'dictem-run-match)
; DEFINE
; Ask for word and database name
; and show definitions found
(global-set-key "\C-cd" 'dictem-run-define)
; SHOW SERVER
; Show information about DICT server
(global-set-key "\C-c\M-r" 'dictem-run-show-server)
; SHOW INFO
; Show information about the database
(global-set-key "\C-c\M-i" 'dictem-run-show-info)
; SHOW DB
; Show a list of databases provided by DICT server
(global-set-key <KEY>" 'dictem-run-show-databases)
(provide 'my-dictem)
| true | (add-to-list 'load-path (expand-file-name "~/.emacs.d/emacs-lisp/dictem-1.0.4/"))
; Loading dictem functions
(require 'dictem)
; Setting the dictionary server hostname.
; This part is optional, if dictem-server is nil (the default value)
; "dict" command line utility will use its ows config file
; ~/.dictrc or PREFIX/etc/dict.conf.
; Keeping dictem-server variable unset is recomended because
; this allows to try _list of_ servers until connection is made,
; see dict(1) for details.
(setq dictem-server "localhost")
;(setq dictem-server "dict.org")
; Setting the dictionary server port.
; Setting dictem-port is usually not necessary because
; most DICT servers use the default port 2628.
;(setq dictem-port "2628")
; Code necessary to obtain database and strategy list from DICT
; server. As of version 0.90, dictem runs this function from
; dictem-select-database and dictem-select-strategy if an
; initialization was not completed or failed previously, that is
; running dictem-initialize is optional
(dictem-initialize)
; Assigning hot keys for accessing DICT server
; SEARCH = MATCH + DEFINE
; Ask for word, database and search strategy
; and show definitions found
(global-set-key "\C-cs" 'dictem-run-search)
; MATCH
; Ask for word, database and search strategy
; and show matches found
(global-set-key "\C-cm" 'dictem-run-match)
; DEFINE
; Ask for word and database name
; and show definitions found
(global-set-key "\C-cd" 'dictem-run-define)
; SHOW SERVER
; Show information about DICT server
(global-set-key "\C-c\M-r" 'dictem-run-show-server)
; SHOW INFO
; Show information about the database
(global-set-key "\C-c\M-i" 'dictem-run-show-info)
; SHOW DB
; Show a list of databases provided by DICT server
(global-set-key PI:KEY:<KEY>END_PI" 'dictem-run-show-databases)
(provide 'my-dictem)
|
[
{
"context": "-*- lexical-binding: t; -*-\n\n;; Copyright (C) 2020 Benjamin Staffin\n\n;; Author: Benjamin Staffin <benley@gmail.com>\n;",
"end": 132,
"score": 0.9998668432235718,
"start": 116,
"tag": "NAME",
"value": "Benjamin Staffin"
},
{
"context": ";; Copyright (C) 2020 Benjamin Staffin\n\n;; Author: Benjamin Staffin <benley@gmail.com>\n;; Version: 0.1\n;; Package-Ver",
"end": 161,
"score": 0.9998757839202881,
"start": 145,
"tag": "NAME",
"value": "Benjamin Staffin"
},
{
"context": "20 Benjamin Staffin\n\n;; Author: Benjamin Staffin <benley@gmail.com>\n;; Version: 0.1\n;; Package-Version: 20200702.153",
"end": 179,
"score": 0.9999276995658875,
"start": 163,
"tag": "EMAIL",
"value": "benley@gmail.com"
},
{
"context": "Package-Version: 20200702.1536\n;; Package-Commit: 5ca236980662141518603672ebdbdf863756da5a\n;; URL: https://github.com/benley/e",
"end": 276,
"score": 0.4979279041290283,
"start": 250,
"tag": "PASSWORD",
"value": "5ca236980662141518603672eb"
},
{
"context": "36\n;; Package-Commit: 5ca236980662141518603672ebdbdf863756da5a\n;; URL: https://github.com/benley/emacs-udev-mode",
"end": 290,
"score": 0.5089236497879028,
"start": 278,
"tag": "PASSWORD",
"value": "df863756da5a"
}
] | dotemacs/elpa/udev-mode-20200702.1536/udev-mode.el | flavorjones/dotfiles | 0 | ;;; udev-mode.el --- Major mode for editing udev rules files -*- lexical-binding: t; -*-
;; Copyright (C) 2020 Benjamin Staffin
;; Author: Benjamin Staffin <benley@gmail.com>
;; Version: 0.1
;; Package-Version: 20200702.1536
;; Package-Commit: 5ca236980662141518603672ebdbdf863756da5a
;; URL: https://github.com/benley/emacs-udev-mode
;; Keywords: languages, unix
;; Package-Requires: ((emacs "24"))
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides a major mode for editing rules files for udev.
;;; Code:
(defconst udev-match-keywords
'("ACTION"
"DEVPATH"
"KERNEL"
"NAME"
"SYMLINK"
"SUBSYSTEM"
"DRIVER"
"KERNELS"
"SUBSYSTEMS"
"DRIVERS"
"TAGS"
"TAG"
"TEST"
;; "PROGRAM" ;; this is special - uses PROGRAM="" even though it's a matcher, not a setter
"RESULT"))
(defconst udev-matchparam-keywords
'("ATTR"
"SYSCTL"
"ATTRS"
"ENV"
"CONST"
"TEST"))
(defconst udev-assign-keywords
'("NAME"
"SYMLINK"
"OWNER"
"GROUP"
"MODE"
"TAG"
"LABEL"
"GOTO"
"OPTIONS"))
(defconst udev-assignparam-keywords
'("SECLABEL"
"ATTR"
"SYSCTL"
"ENV"
"RUN" ;; {(program|builtin)}
"IMPORT" ;; {(program|builtin|file|db|cmdline|parent)}
))
(defconst udev-font-lock-keywords
`((,(concat (regexp-opt udev-match-keywords 'words)
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face))
(,(concat (regexp-opt udev-matchparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face)
(2 font-lock-variable-name-face))
(,(concat (regexp-opt udev-assign-keywords 'words)
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face))
(,(concat (regexp-opt udev-assignparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face)
(2 font-lock-variable-name-face))
("\\(PROGRAM\\)=" . (1 font-lock-constant-face))))
;;;###autoload
(define-derived-mode udev-mode prog-mode "udev"
(setq font-lock-defaults '(udev-font-lock-keywords
nil ;; keywords-only
nil ;; case-fold
nil ;; syntax-alist
nil ;; other-vars
))
(setq comment-start "#")
(setq comment-end "")
(modify-syntax-entry ?# "<" udev-mode-syntax-table)
(modify-syntax-entry ?\n ">" udev-mode-syntax-table))
;;;###autoload
(add-to-list 'auto-mode-alist (cons "\\.rules\\'" 'udev-mode))
(provide 'udev-mode)
;;; udev-mode.el ends here
| 39094 | ;;; udev-mode.el --- Major mode for editing udev rules files -*- lexical-binding: t; -*-
;; Copyright (C) 2020 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Version: 0.1
;; Package-Version: 20200702.1536
;; Package-Commit: <PASSWORD>db<PASSWORD>
;; URL: https://github.com/benley/emacs-udev-mode
;; Keywords: languages, unix
;; Package-Requires: ((emacs "24"))
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides a major mode for editing rules files for udev.
;;; Code:
(defconst udev-match-keywords
'("ACTION"
"DEVPATH"
"KERNEL"
"NAME"
"SYMLINK"
"SUBSYSTEM"
"DRIVER"
"KERNELS"
"SUBSYSTEMS"
"DRIVERS"
"TAGS"
"TAG"
"TEST"
;; "PROGRAM" ;; this is special - uses PROGRAM="" even though it's a matcher, not a setter
"RESULT"))
(defconst udev-matchparam-keywords
'("ATTR"
"SYSCTL"
"ATTRS"
"ENV"
"CONST"
"TEST"))
(defconst udev-assign-keywords
'("NAME"
"SYMLINK"
"OWNER"
"GROUP"
"MODE"
"TAG"
"LABEL"
"GOTO"
"OPTIONS"))
(defconst udev-assignparam-keywords
'("SECLABEL"
"ATTR"
"SYSCTL"
"ENV"
"RUN" ;; {(program|builtin)}
"IMPORT" ;; {(program|builtin|file|db|cmdline|parent)}
))
(defconst udev-font-lock-keywords
`((,(concat (regexp-opt udev-match-keywords 'words)
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face))
(,(concat (regexp-opt udev-matchparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face)
(2 font-lock-variable-name-face))
(,(concat (regexp-opt udev-assign-keywords 'words)
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face))
(,(concat (regexp-opt udev-assignparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face)
(2 font-lock-variable-name-face))
("\\(PROGRAM\\)=" . (1 font-lock-constant-face))))
;;;###autoload
(define-derived-mode udev-mode prog-mode "udev"
(setq font-lock-defaults '(udev-font-lock-keywords
nil ;; keywords-only
nil ;; case-fold
nil ;; syntax-alist
nil ;; other-vars
))
(setq comment-start "#")
(setq comment-end "")
(modify-syntax-entry ?# "<" udev-mode-syntax-table)
(modify-syntax-entry ?\n ">" udev-mode-syntax-table))
;;;###autoload
(add-to-list 'auto-mode-alist (cons "\\.rules\\'" 'udev-mode))
(provide 'udev-mode)
;;; udev-mode.el ends here
| true | ;;; udev-mode.el --- Major mode for editing udev rules files -*- lexical-binding: t; -*-
;; Copyright (C) 2020 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Version: 0.1
;; Package-Version: 20200702.1536
;; Package-Commit: PI:PASSWORD:<PASSWORD>END_PIdbPI:PASSWORD:<PASSWORD>END_PI
;; URL: https://github.com/benley/emacs-udev-mode
;; Keywords: languages, unix
;; Package-Requires: ((emacs "24"))
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides a major mode for editing rules files for udev.
;;; Code:
(defconst udev-match-keywords
'("ACTION"
"DEVPATH"
"KERNEL"
"NAME"
"SYMLINK"
"SUBSYSTEM"
"DRIVER"
"KERNELS"
"SUBSYSTEMS"
"DRIVERS"
"TAGS"
"TAG"
"TEST"
;; "PROGRAM" ;; this is special - uses PROGRAM="" even though it's a matcher, not a setter
"RESULT"))
(defconst udev-matchparam-keywords
'("ATTR"
"SYSCTL"
"ATTRS"
"ENV"
"CONST"
"TEST"))
(defconst udev-assign-keywords
'("NAME"
"SYMLINK"
"OWNER"
"GROUP"
"MODE"
"TAG"
"LABEL"
"GOTO"
"OPTIONS"))
(defconst udev-assignparam-keywords
'("SECLABEL"
"ATTR"
"SYSCTL"
"ENV"
"RUN" ;; {(program|builtin)}
"IMPORT" ;; {(program|builtin|file|db|cmdline|parent)}
))
(defconst udev-font-lock-keywords
`((,(concat (regexp-opt udev-match-keywords 'words)
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face))
(,(concat (regexp-opt udev-matchparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("==" "!=")))
(1 font-lock-constant-face)
(2 font-lock-variable-name-face))
(,(concat (regexp-opt udev-assign-keywords 'words)
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face))
(,(concat (regexp-opt udev-assignparam-keywords 'words)
"{\\([_A-Za-z0-9]+\\)}"
(regexp-opt '("+=" "-=" ":=" "=")))
(1 font-lock-builtin-face)
(2 font-lock-variable-name-face))
("\\(PROGRAM\\)=" . (1 font-lock-constant-face))))
;;;###autoload
(define-derived-mode udev-mode prog-mode "udev"
(setq font-lock-defaults '(udev-font-lock-keywords
nil ;; keywords-only
nil ;; case-fold
nil ;; syntax-alist
nil ;; other-vars
))
(setq comment-start "#")
(setq comment-end "")
(modify-syntax-entry ?# "<" udev-mode-syntax-table)
(modify-syntax-entry ?\n ">" udev-mode-syntax-table))
;;;###autoload
(add-to-list 'auto-mode-alist (cons "\\.rules\\'" 'udev-mode))
(provide 'udev-mode)
;;; udev-mode.el ends here
|
[
{
"context": "for emacs lisp\n\n;; Copyright (C) 2010, 2011, 2012 SAKURAI Masashi\n\n;; Author: SAKURAI Masashi <m.sakurai at kiwanam",
"end": 117,
"score": 0.9998467564582825,
"start": 102,
"tag": "NAME",
"value": "SAKURAI Masashi"
},
{
"context": " (C) 2010, 2011, 2012 SAKURAI Masashi\n\n;; Author: SAKURAI Masashi <m.sakurai at kiwanami.net>\n;; Version: 0.3.1\n;; ",
"end": 145,
"score": 0.9998441338539124,
"start": 130,
"tag": "NAME",
"value": "SAKURAI Masashi"
}
] | .emacs.d/elpa/concurrent-0.3.1/concurrent.el | sethdenner/.files | 0 | ;;; concurrent.el --- Concurrent utility functions for emacs lisp
;; Copyright (C) 2010, 2011, 2012 SAKURAI Masashi
;; Author: SAKURAI Masashi <m.sakurai at kiwanami.net>
;; Version: 0.3.1
;; Keywords: deferred, async, concurrent
;; Package-Requires: ((deferred "0.3.1"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; 'concurrent.el' is a higher level library for concurrent tasks
;; based on 'deferred.el'. This library has following features:
;;
;; - Generator
;; - Green thread
;; - Semaphore
;; - Dataflow
;; - Signal/Channel
(eval-when-compile
(require 'cl))
(require 'deferred)
(defvar cc:version nil "version number")
(setq cc:version "0.3")
;;; Code:
(defmacro cc:aif (test-form then-form &rest else-forms)
(declare (debug (form form &rest form)))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(put 'cc:aif 'lisp-indent-function 2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generator
(defun cc:generator-replace-yield (tree)
"[internal] Replace `yield' symbols to calling a function in TREE."
(let (ret)
(loop for i in tree
do (cond
((eq i 'yield)
(push 'funcall ret)
(push i ret))
((listp i)
(push (cc:generator-replace-yield i) ret))
(t
(push i ret))))
(nreverse ret)))
(defun cc:generator-line (line)
"[internal] Return a macro expansion to execute the sexp LINE
asynchronously."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(progn
,@(cc:generator-replace-yield body)) self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x) ,(cc:generator-replace-yield line)))))))
(defmacro cc:generator (callback &rest body)
"Create a generator object. If BODY has `yield' symbols, it
means calling callback function CALLBACK."
(let ((chain (gensym))
(cc (gensym))
(waiter (gensym)))
`(lexical-let*
(,chain
(,cc ,callback)
(,waiter (deferred:new))
(yield (lambda (x) (funcall ,cc x) ,waiter)))
(setq ,chain ,waiter)
,@(loop for i in body
collect
(cc:generator-line i))
(lambda () (deferred:callback ,waiter)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Thread
(defun cc:thread-line (wait-time chain line)
"[internal] Return a macro expansion to execute the sexp LINE asynchronously.
WAIT-TIME is an interval time between tasks.
CHAIN is the previous deferred task."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line))
(retsym (gensym)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(let ((,retsym (progn ,@body)))
(if (deferred-p ,retsym) ,retsym
(deferred:wait ,wait-time)))
self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(lambda (x) ,line))))))
(defmacro cc:thread (wait-time-msec &rest body)
"Return a thread object."
(let ((chain (gensym))
(dstart (gensym)))
`(lexical-let*
(,chain
(,dstart (deferred:new)))
(setq ,chain ,dstart)
,@(loop for i in body
collect
(cc:thread-line wait-time-msec chain i))
(deferred:callback ,dstart))))
(put 'cc:thread 'lisp-indent-function 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Semaphore
(defstruct cc:semaphore max-permits permits waiting-deferreds)
(defun cc:semaphore-create(permits-num)
"Return a semaphore object with PERMITS-NUM permissions."
(make-cc:semaphore :max-permits permits-num :permits permits-num))
(defun cc:semaphore-acquire(semaphore)
"Acquire an execution permission and return deferred object to chain.
If this semaphore object has permissions, the subsequent deferred
task is executed immediately. If this semaphore object has no
permissions, the subsequent deferred task is blocked. After the
permission is returned, the task is executed."
(cond
((< 0 (cc:semaphore-permits semaphore))
(decf (cc:semaphore-permits semaphore))
(deferred:succeed))
(t
(let ((d (deferred:new)))
(push d (cc:semaphore-waiting-deferreds semaphore))
d))))
(defun cc:semaphore-release(semaphore)
"Release an execution permission. The programmer is responsible to return the permissions."
(when (<= (cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore))
(error "Too many calling semaphore-release. [max:%s <= permits:%s]"
(cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore)))
(let ((waiting-deferreds
(cc:semaphore-waiting-deferreds semaphore)))
(cond
(waiting-deferreds
(let* ((d (car (last waiting-deferreds))))
(setf (cc:semaphore-waiting-deferreds semaphore)
(nbutlast waiting-deferreds))
(deferred:callback-post d)))
(t
(incf (cc:semaphore-permits semaphore)))))
semaphore)
(defun cc:semaphore-with (semaphore body-func &optional error-func)
"Execute the task BODY-FUNC asynchronously with the semaphore block."
(lexical-let ((semaphore semaphore))
(deferred:try
(deferred:nextc (cc:semaphore-acquire semaphore) body-func)
:catch
error-func
:finally
(lambda (x) (cc:semaphore-release semaphore)))))
(put 'cc:semaphore-with 'lisp-indent-function 1)
(defun cc:semaphore-release-all (semaphore)
"Release all permissions for resetting the semaphore object.
If the semaphore object has some blocked tasks, this function
return a list of the tasks and clear the list of the blocked
tasks in the semaphore object."
(setf (cc:semaphore-permits semaphore)
(cc:semaphore-max-permits semaphore))
(let ((ds (cc:semaphore-waiting-deferreds semaphore)))
(when ds
(setf (cc:semaphore-waiting-deferreds semaphore) nil))
ds))
(defun cc:semaphore-interrupt-all (semaphore)
"Clear the list of the blocked tasks in the semaphore and return a deferred object to chain.
This function is used for the interruption cases."
(when (cc:semaphore-waiting-deferreds semaphore)
(setf (cc:semaphore-waiting-deferreds semaphore) nil)
(setf (cc:semaphore-permits semaphore) 0))
(cc:semaphore-acquire semaphore))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Signal / Channel
(defun cc:signal-channel (&optional name parent-channel)
"Create a channel.
NAME is a channel name for debug.
PARENT-CHANNEL is an upstream channel. The observers of this channel can receive the upstream signals.
In the case of using the function `cc:signal-send', the observers of the upstream channel can not receive the signals of this channel. The function `cc:signal-send-global' can send a signal to the upstream channels from the downstream channels."
(lexical-let
((ch (cons
(or name (format "signal%s" (deferred:uid))) ; name for debug
(cons
parent-channel ; parent-channel
nil)))) ; observers
(when parent-channel
(cc:signal-connect
parent-channel
t (lambda (event)
(destructuring-bind
(event-name event-args) event
(apply 'cc:signal-send
ch event-name event-args)))))
ch))
(defmacro cc:signal-name (ch)
"[internal] Return signal name."
`(car ,ch))
(defmacro cc:signal-parent-channel (ch)
"[internal] Return parent channel object."
`(cadr ,ch))
(defmacro cc:signal-observers (ch)
"[internal] Return observers."
`(cddr ,ch))
(defun cc:signal-connect (channel event-sym &optional callback)
"Append an observer for EVENT-SYM of CHANNEL and return a deferred object.
If EVENT-SYM is `t', the observer receives all signals of the channel.
If CALLBACK function is given, the deferred object executes the
CALLBACK function asynchronously. One can connect subsequent
tasks to the returned deferred object."
(let ((d (if callback
(deferred:new callback)
(deferred:new))))
(push (cons event-sym d)
(cc:signal-observers channel))
d))
(defun cc:signal-send (channel event-sym &rest args)
"Send a signal to CHANNEL. If ARGS values are given, observers can get the values by following code: (lambda (event) (destructuring-bind (event-sym (args)) event ... )). "
(let ((observers (cc:signal-observers channel))
(event (list event-sym args)))
(loop for i in observers
for name = (car i)
for d = (cdr i)
if (or (eq event-sym name) (eq t name))
do (deferred:callback-post d event))))
(defun cc:signal-send-global (channel event-sym &rest args)
"Send a signal to the most upstream channel. "
(cc:aif (cc:signal-parent-channel channel)
(apply 'cc:signal-send-global it event-sym args)
(apply 'cc:signal-send channel event-sym args)))
(defun cc:signal-disconnect (channel deferred)
"Remove the observer object DEFERRED from CHANNEL and return
the removed deferred object. "
(let ((observers (cc:signal-observers channel)) deleted)
(setf
(cc:signal-observers channel) ; place
(loop for i in observers
for d = (cdr i)
unless (eq d deferred)
collect i
else
do (push i deleted)))
deleted))
(defun cc:signal-disconnect-all (channel)
"Remove all observers."
(setf
(cc:signal-observers channel) ; place
nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dataflow
;; Dataflow variable entry
(defstruct cc:dataflow key (value 'cc:dataflow-undefine) deferred-list)
(defun cc:dataflow-undefine-p (obj)
"[internal] If the variable entry is not bound, return `t'."
(eq 'cc:dataflow-undefine (cc:dataflow-value obj)))
(defun cc:dataflow-environment (&optional parent-env test-func channel)
"Create a dataflow environment.
PARENT-ENV is the default environment. If this environment doesn't have the entry A and the parent one has the entry A, this environment can return the entry A. One can override the entry, setting another entry A to this environment.
TEST-FUNC is a test function that compares the entry keys. The default function is `equal'.
CHANNEL is a channel object that sends signals of variable events. Observers can receive following signals:
-get-first : the fist referrer is waiting for binding,
-get-waiting : another referrer is waiting for binding,
-set : a value is bound,
-get : returned a bound value,
-clear : cleared one entry,
-clear-all : cleared all entries.
"
(let ((this (list parent-env
(or test-func 'equal)
(or channel
(cc:signal-channel
'dataflow
(and parent-env
(cc:dataflow-channel parent-env)))))))
(cc:dataflow-init-connect this)
this))
(defun cc:dataflow-init-connect (df)
"[internal] Initialize the channel object."
(lexical-let ((df df))
(cc:dataflow-connect
df 'set
(lambda (args)
(destructuring-bind (event (key)) args
(let* ((obj (cc:dataflow-get-object-for-value df key))
(value (and obj (cc:dataflow-value obj))))
(when obj
(loop for i in (cc:aif (cc:dataflow-get-object-for-deferreds df key)
(cc:dataflow-deferred-list it) nil)
do (deferred:callback-post i value))
(setf (cc:dataflow-deferred-list obj) nil))))))))
(defmacro cc:dataflow-parent-environment (df)
"[internal] Return the parent environment."
`(car ,df))
(defmacro cc:dataflow-test (df)
"[internal] Return the test function."
`(cadr ,df))
(defmacro cc:dataflow-channel (df)
"[internal] Return the channel object."
`(caddr ,df))
(defmacro cc:dataflow-list (df)
"[internal] Return the list of deferred object which are waiting for value binding."
`(cdddr ,df))
(defun cc:dataflow-get-object-for-value (df key)
"[internal] Return an entry object that is indicated by KEY.
If the environment DF doesn't have the entry and the parent one has the entry, this function returns the entry of the parent environment. This function doesn't affect the waiting list."
(or
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (and (funcall test key (cc:dataflow-key i))
(not (cc:dataflow-undefine-p i)))
return i)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-object-for-value it key))))
(defun cc:dataflow-get-object-for-deferreds (df key)
"[internal] Return a list of the deferred objects those are waiting for value binding.
This function doesn't affect the waiting list and doesn't refer the parent environment."
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (funcall test key (cc:dataflow-key i))
return i))
(defun cc:dataflow-connect (df event-sym &optional callback)
"Append an observer for EVENT-SYM of the channel of DF and return a deferred object.
See the docstring of `cc:dataflow-environment' for details."
(cc:signal-connect (cc:dataflow-channel df) event-sym callback))
(defun cc:dataflow-signal (df event &optional arg)
"[internal] Send a signal to the channel of DF."
(cc:signal-send (cc:dataflow-channel df) event arg))
(defun cc:dataflow-get (df key)
"Return a deferred object that can refer the value which is indicated by KEY.
If DF has the entry that bound value, the subsequent deferred task is executed immediately.
If not, the task is deferred till a value is bound."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(cond
((and obj (cc:dataflow-value obj))
(cc:dataflow-signal df 'get key)
(deferred:succeed (cc:dataflow-value obj)))
(t
(setq obj (cc:dataflow-get-object-for-deferreds df key))
(unless obj
(setq obj (make-cc:dataflow :key key))
(push obj (cc:dataflow-list df))
(cc:dataflow-signal df 'get-first key))
(let ((d (deferred:new)))
(push d (cc:dataflow-deferred-list obj))
(cc:dataflow-signal df 'get-waiting key)
d)))))
(defun cc:dataflow-get-sync (df key)
"Return the value which is indicated by KEY synchronously.
If the environment DF doesn't have an entry of KEY, this function returns nil."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(and obj (cc:dataflow-value obj))))
(defun cc:dataflow-set (df key value)
"Bind the VALUE to KEY in the environment DF.
If DF already has the bound entry of KEY, this function throws an error signal.
VALUE can be nil as a value."
(let ((obj (cc:dataflow-get-object-for-deferreds df key)))
(cond
((and obj (not (cc:dataflow-undefine-p obj)))
;; overwrite!
(error "Can not set a dataflow value. The key [%s] has already had a value. NEW:[%s] OLD:[%s]" key value (cc:dataflow-value obj)))
(obj
(setf (cc:dataflow-value obj) value))
(t
;; just value arrived
(push (make-cc:dataflow :key key :value value)
(cc:dataflow-list df))))
;; value arrived and start deferred objects
(cc:dataflow-signal df 'set key)
value))
(defun cc:dataflow-clear (df key)
"Clear the entry which is indicated by KEY.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear key)
(setf (cc:dataflow-list df)
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
unless (funcall test key (cc:dataflow-key i))
collect i)))
(defun cc:dataflow-get-avalable-pairs (df)
"Return an available key-value alist in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
unless (cc:dataflow-undefine-p i) collect (cons key val))
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-avalable-pairs it))))
(defun cc:dataflow-get-waiting-keys (df)
"Return a list of keys which have waiting deferred objects in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
if (cc:dataflow-undefine-p i) collect key)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-waiting-keys it))))
(defun cc:dataflow-clear-all (df)
"Clear all entries in the environment DF.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear-all)
(setf (cc:dataflow-list df) nil))
(provide 'concurrent)
;;; concurrent.el ends here
| 28298 | ;;; concurrent.el --- Concurrent utility functions for emacs lisp
;; Copyright (C) 2010, 2011, 2012 <NAME>
;; Author: <NAME> <m.sakurai at kiwanami.net>
;; Version: 0.3.1
;; Keywords: deferred, async, concurrent
;; Package-Requires: ((deferred "0.3.1"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; 'concurrent.el' is a higher level library for concurrent tasks
;; based on 'deferred.el'. This library has following features:
;;
;; - Generator
;; - Green thread
;; - Semaphore
;; - Dataflow
;; - Signal/Channel
(eval-when-compile
(require 'cl))
(require 'deferred)
(defvar cc:version nil "version number")
(setq cc:version "0.3")
;;; Code:
(defmacro cc:aif (test-form then-form &rest else-forms)
(declare (debug (form form &rest form)))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(put 'cc:aif 'lisp-indent-function 2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generator
(defun cc:generator-replace-yield (tree)
"[internal] Replace `yield' symbols to calling a function in TREE."
(let (ret)
(loop for i in tree
do (cond
((eq i 'yield)
(push 'funcall ret)
(push i ret))
((listp i)
(push (cc:generator-replace-yield i) ret))
(t
(push i ret))))
(nreverse ret)))
(defun cc:generator-line (line)
"[internal] Return a macro expansion to execute the sexp LINE
asynchronously."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(progn
,@(cc:generator-replace-yield body)) self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x) ,(cc:generator-replace-yield line)))))))
(defmacro cc:generator (callback &rest body)
"Create a generator object. If BODY has `yield' symbols, it
means calling callback function CALLBACK."
(let ((chain (gensym))
(cc (gensym))
(waiter (gensym)))
`(lexical-let*
(,chain
(,cc ,callback)
(,waiter (deferred:new))
(yield (lambda (x) (funcall ,cc x) ,waiter)))
(setq ,chain ,waiter)
,@(loop for i in body
collect
(cc:generator-line i))
(lambda () (deferred:callback ,waiter)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Thread
(defun cc:thread-line (wait-time chain line)
"[internal] Return a macro expansion to execute the sexp LINE asynchronously.
WAIT-TIME is an interval time between tasks.
CHAIN is the previous deferred task."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line))
(retsym (gensym)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(let ((,retsym (progn ,@body)))
(if (deferred-p ,retsym) ,retsym
(deferred:wait ,wait-time)))
self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(lambda (x) ,line))))))
(defmacro cc:thread (wait-time-msec &rest body)
"Return a thread object."
(let ((chain (gensym))
(dstart (gensym)))
`(lexical-let*
(,chain
(,dstart (deferred:new)))
(setq ,chain ,dstart)
,@(loop for i in body
collect
(cc:thread-line wait-time-msec chain i))
(deferred:callback ,dstart))))
(put 'cc:thread 'lisp-indent-function 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Semaphore
(defstruct cc:semaphore max-permits permits waiting-deferreds)
(defun cc:semaphore-create(permits-num)
"Return a semaphore object with PERMITS-NUM permissions."
(make-cc:semaphore :max-permits permits-num :permits permits-num))
(defun cc:semaphore-acquire(semaphore)
"Acquire an execution permission and return deferred object to chain.
If this semaphore object has permissions, the subsequent deferred
task is executed immediately. If this semaphore object has no
permissions, the subsequent deferred task is blocked. After the
permission is returned, the task is executed."
(cond
((< 0 (cc:semaphore-permits semaphore))
(decf (cc:semaphore-permits semaphore))
(deferred:succeed))
(t
(let ((d (deferred:new)))
(push d (cc:semaphore-waiting-deferreds semaphore))
d))))
(defun cc:semaphore-release(semaphore)
"Release an execution permission. The programmer is responsible to return the permissions."
(when (<= (cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore))
(error "Too many calling semaphore-release. [max:%s <= permits:%s]"
(cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore)))
(let ((waiting-deferreds
(cc:semaphore-waiting-deferreds semaphore)))
(cond
(waiting-deferreds
(let* ((d (car (last waiting-deferreds))))
(setf (cc:semaphore-waiting-deferreds semaphore)
(nbutlast waiting-deferreds))
(deferred:callback-post d)))
(t
(incf (cc:semaphore-permits semaphore)))))
semaphore)
(defun cc:semaphore-with (semaphore body-func &optional error-func)
"Execute the task BODY-FUNC asynchronously with the semaphore block."
(lexical-let ((semaphore semaphore))
(deferred:try
(deferred:nextc (cc:semaphore-acquire semaphore) body-func)
:catch
error-func
:finally
(lambda (x) (cc:semaphore-release semaphore)))))
(put 'cc:semaphore-with 'lisp-indent-function 1)
(defun cc:semaphore-release-all (semaphore)
"Release all permissions for resetting the semaphore object.
If the semaphore object has some blocked tasks, this function
return a list of the tasks and clear the list of the blocked
tasks in the semaphore object."
(setf (cc:semaphore-permits semaphore)
(cc:semaphore-max-permits semaphore))
(let ((ds (cc:semaphore-waiting-deferreds semaphore)))
(when ds
(setf (cc:semaphore-waiting-deferreds semaphore) nil))
ds))
(defun cc:semaphore-interrupt-all (semaphore)
"Clear the list of the blocked tasks in the semaphore and return a deferred object to chain.
This function is used for the interruption cases."
(when (cc:semaphore-waiting-deferreds semaphore)
(setf (cc:semaphore-waiting-deferreds semaphore) nil)
(setf (cc:semaphore-permits semaphore) 0))
(cc:semaphore-acquire semaphore))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Signal / Channel
(defun cc:signal-channel (&optional name parent-channel)
"Create a channel.
NAME is a channel name for debug.
PARENT-CHANNEL is an upstream channel. The observers of this channel can receive the upstream signals.
In the case of using the function `cc:signal-send', the observers of the upstream channel can not receive the signals of this channel. The function `cc:signal-send-global' can send a signal to the upstream channels from the downstream channels."
(lexical-let
((ch (cons
(or name (format "signal%s" (deferred:uid))) ; name for debug
(cons
parent-channel ; parent-channel
nil)))) ; observers
(when parent-channel
(cc:signal-connect
parent-channel
t (lambda (event)
(destructuring-bind
(event-name event-args) event
(apply 'cc:signal-send
ch event-name event-args)))))
ch))
(defmacro cc:signal-name (ch)
"[internal] Return signal name."
`(car ,ch))
(defmacro cc:signal-parent-channel (ch)
"[internal] Return parent channel object."
`(cadr ,ch))
(defmacro cc:signal-observers (ch)
"[internal] Return observers."
`(cddr ,ch))
(defun cc:signal-connect (channel event-sym &optional callback)
"Append an observer for EVENT-SYM of CHANNEL and return a deferred object.
If EVENT-SYM is `t', the observer receives all signals of the channel.
If CALLBACK function is given, the deferred object executes the
CALLBACK function asynchronously. One can connect subsequent
tasks to the returned deferred object."
(let ((d (if callback
(deferred:new callback)
(deferred:new))))
(push (cons event-sym d)
(cc:signal-observers channel))
d))
(defun cc:signal-send (channel event-sym &rest args)
"Send a signal to CHANNEL. If ARGS values are given, observers can get the values by following code: (lambda (event) (destructuring-bind (event-sym (args)) event ... )). "
(let ((observers (cc:signal-observers channel))
(event (list event-sym args)))
(loop for i in observers
for name = (car i)
for d = (cdr i)
if (or (eq event-sym name) (eq t name))
do (deferred:callback-post d event))))
(defun cc:signal-send-global (channel event-sym &rest args)
"Send a signal to the most upstream channel. "
(cc:aif (cc:signal-parent-channel channel)
(apply 'cc:signal-send-global it event-sym args)
(apply 'cc:signal-send channel event-sym args)))
(defun cc:signal-disconnect (channel deferred)
"Remove the observer object DEFERRED from CHANNEL and return
the removed deferred object. "
(let ((observers (cc:signal-observers channel)) deleted)
(setf
(cc:signal-observers channel) ; place
(loop for i in observers
for d = (cdr i)
unless (eq d deferred)
collect i
else
do (push i deleted)))
deleted))
(defun cc:signal-disconnect-all (channel)
"Remove all observers."
(setf
(cc:signal-observers channel) ; place
nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dataflow
;; Dataflow variable entry
(defstruct cc:dataflow key (value 'cc:dataflow-undefine) deferred-list)
(defun cc:dataflow-undefine-p (obj)
"[internal] If the variable entry is not bound, return `t'."
(eq 'cc:dataflow-undefine (cc:dataflow-value obj)))
(defun cc:dataflow-environment (&optional parent-env test-func channel)
"Create a dataflow environment.
PARENT-ENV is the default environment. If this environment doesn't have the entry A and the parent one has the entry A, this environment can return the entry A. One can override the entry, setting another entry A to this environment.
TEST-FUNC is a test function that compares the entry keys. The default function is `equal'.
CHANNEL is a channel object that sends signals of variable events. Observers can receive following signals:
-get-first : the fist referrer is waiting for binding,
-get-waiting : another referrer is waiting for binding,
-set : a value is bound,
-get : returned a bound value,
-clear : cleared one entry,
-clear-all : cleared all entries.
"
(let ((this (list parent-env
(or test-func 'equal)
(or channel
(cc:signal-channel
'dataflow
(and parent-env
(cc:dataflow-channel parent-env)))))))
(cc:dataflow-init-connect this)
this))
(defun cc:dataflow-init-connect (df)
"[internal] Initialize the channel object."
(lexical-let ((df df))
(cc:dataflow-connect
df 'set
(lambda (args)
(destructuring-bind (event (key)) args
(let* ((obj (cc:dataflow-get-object-for-value df key))
(value (and obj (cc:dataflow-value obj))))
(when obj
(loop for i in (cc:aif (cc:dataflow-get-object-for-deferreds df key)
(cc:dataflow-deferred-list it) nil)
do (deferred:callback-post i value))
(setf (cc:dataflow-deferred-list obj) nil))))))))
(defmacro cc:dataflow-parent-environment (df)
"[internal] Return the parent environment."
`(car ,df))
(defmacro cc:dataflow-test (df)
"[internal] Return the test function."
`(cadr ,df))
(defmacro cc:dataflow-channel (df)
"[internal] Return the channel object."
`(caddr ,df))
(defmacro cc:dataflow-list (df)
"[internal] Return the list of deferred object which are waiting for value binding."
`(cdddr ,df))
(defun cc:dataflow-get-object-for-value (df key)
"[internal] Return an entry object that is indicated by KEY.
If the environment DF doesn't have the entry and the parent one has the entry, this function returns the entry of the parent environment. This function doesn't affect the waiting list."
(or
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (and (funcall test key (cc:dataflow-key i))
(not (cc:dataflow-undefine-p i)))
return i)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-object-for-value it key))))
(defun cc:dataflow-get-object-for-deferreds (df key)
"[internal] Return a list of the deferred objects those are waiting for value binding.
This function doesn't affect the waiting list and doesn't refer the parent environment."
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (funcall test key (cc:dataflow-key i))
return i))
(defun cc:dataflow-connect (df event-sym &optional callback)
"Append an observer for EVENT-SYM of the channel of DF and return a deferred object.
See the docstring of `cc:dataflow-environment' for details."
(cc:signal-connect (cc:dataflow-channel df) event-sym callback))
(defun cc:dataflow-signal (df event &optional arg)
"[internal] Send a signal to the channel of DF."
(cc:signal-send (cc:dataflow-channel df) event arg))
(defun cc:dataflow-get (df key)
"Return a deferred object that can refer the value which is indicated by KEY.
If DF has the entry that bound value, the subsequent deferred task is executed immediately.
If not, the task is deferred till a value is bound."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(cond
((and obj (cc:dataflow-value obj))
(cc:dataflow-signal df 'get key)
(deferred:succeed (cc:dataflow-value obj)))
(t
(setq obj (cc:dataflow-get-object-for-deferreds df key))
(unless obj
(setq obj (make-cc:dataflow :key key))
(push obj (cc:dataflow-list df))
(cc:dataflow-signal df 'get-first key))
(let ((d (deferred:new)))
(push d (cc:dataflow-deferred-list obj))
(cc:dataflow-signal df 'get-waiting key)
d)))))
(defun cc:dataflow-get-sync (df key)
"Return the value which is indicated by KEY synchronously.
If the environment DF doesn't have an entry of KEY, this function returns nil."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(and obj (cc:dataflow-value obj))))
(defun cc:dataflow-set (df key value)
"Bind the VALUE to KEY in the environment DF.
If DF already has the bound entry of KEY, this function throws an error signal.
VALUE can be nil as a value."
(let ((obj (cc:dataflow-get-object-for-deferreds df key)))
(cond
((and obj (not (cc:dataflow-undefine-p obj)))
;; overwrite!
(error "Can not set a dataflow value. The key [%s] has already had a value. NEW:[%s] OLD:[%s]" key value (cc:dataflow-value obj)))
(obj
(setf (cc:dataflow-value obj) value))
(t
;; just value arrived
(push (make-cc:dataflow :key key :value value)
(cc:dataflow-list df))))
;; value arrived and start deferred objects
(cc:dataflow-signal df 'set key)
value))
(defun cc:dataflow-clear (df key)
"Clear the entry which is indicated by KEY.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear key)
(setf (cc:dataflow-list df)
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
unless (funcall test key (cc:dataflow-key i))
collect i)))
(defun cc:dataflow-get-avalable-pairs (df)
"Return an available key-value alist in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
unless (cc:dataflow-undefine-p i) collect (cons key val))
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-avalable-pairs it))))
(defun cc:dataflow-get-waiting-keys (df)
"Return a list of keys which have waiting deferred objects in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
if (cc:dataflow-undefine-p i) collect key)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-waiting-keys it))))
(defun cc:dataflow-clear-all (df)
"Clear all entries in the environment DF.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear-all)
(setf (cc:dataflow-list df) nil))
(provide 'concurrent)
;;; concurrent.el ends here
| true | ;;; concurrent.el --- Concurrent utility functions for emacs lisp
;; Copyright (C) 2010, 2011, 2012 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <m.sakurai at kiwanami.net>
;; Version: 0.3.1
;; Keywords: deferred, async, concurrent
;; Package-Requires: ((deferred "0.3.1"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; 'concurrent.el' is a higher level library for concurrent tasks
;; based on 'deferred.el'. This library has following features:
;;
;; - Generator
;; - Green thread
;; - Semaphore
;; - Dataflow
;; - Signal/Channel
(eval-when-compile
(require 'cl))
(require 'deferred)
(defvar cc:version nil "version number")
(setq cc:version "0.3")
;;; Code:
(defmacro cc:aif (test-form then-form &rest else-forms)
(declare (debug (form form &rest form)))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(put 'cc:aif 'lisp-indent-function 2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Generator
(defun cc:generator-replace-yield (tree)
"[internal] Replace `yield' symbols to calling a function in TREE."
(let (ret)
(loop for i in tree
do (cond
((eq i 'yield)
(push 'funcall ret)
(push i ret))
((listp i)
(push (cc:generator-replace-yield i) ret))
(t
(push i ret))))
(nreverse ret)))
(defun cc:generator-line (line)
"[internal] Return a macro expansion to execute the sexp LINE
asynchronously."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(progn
,@(cc:generator-replace-yield body)) self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x) ,(cc:generator-replace-yield line)))))))
(defmacro cc:generator (callback &rest body)
"Create a generator object. If BODY has `yield' symbols, it
means calling callback function CALLBACK."
(let ((chain (gensym))
(cc (gensym))
(waiter (gensym)))
`(lexical-let*
(,chain
(,cc ,callback)
(,waiter (deferred:new))
(yield (lambda (x) (funcall ,cc x) ,waiter)))
(setq ,chain ,waiter)
,@(loop for i in body
collect
(cc:generator-line i))
(lambda () (deferred:callback ,waiter)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Thread
(defun cc:thread-line (wait-time chain line)
"[internal] Return a macro expansion to execute the sexp LINE asynchronously.
WAIT-TIME is an interval time between tasks.
CHAIN is the previous deferred task."
(cond
;; function object
((functionp line)
`(setq ,chain (deferred:nextc ,chain ,line)))
;; while loop form
((eq 'while (car line))
(let ((condition (cadr line))
(body (cddr line))
(retsym (gensym)))
`(setq ,chain
(deferred:nextc ,chain
(deferred:lambda (x)
(if ,condition
(deferred:nextc
(let ((,retsym (progn ,@body)))
(if (deferred-p ,retsym) ,retsym
(deferred:wait ,wait-time)))
self)))))))
;; statement
(t
`(setq ,chain
(deferred:nextc ,chain
(lambda (x) ,line))))))
(defmacro cc:thread (wait-time-msec &rest body)
"Return a thread object."
(let ((chain (gensym))
(dstart (gensym)))
`(lexical-let*
(,chain
(,dstart (deferred:new)))
(setq ,chain ,dstart)
,@(loop for i in body
collect
(cc:thread-line wait-time-msec chain i))
(deferred:callback ,dstart))))
(put 'cc:thread 'lisp-indent-function 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Semaphore
(defstruct cc:semaphore max-permits permits waiting-deferreds)
(defun cc:semaphore-create(permits-num)
"Return a semaphore object with PERMITS-NUM permissions."
(make-cc:semaphore :max-permits permits-num :permits permits-num))
(defun cc:semaphore-acquire(semaphore)
"Acquire an execution permission and return deferred object to chain.
If this semaphore object has permissions, the subsequent deferred
task is executed immediately. If this semaphore object has no
permissions, the subsequent deferred task is blocked. After the
permission is returned, the task is executed."
(cond
((< 0 (cc:semaphore-permits semaphore))
(decf (cc:semaphore-permits semaphore))
(deferred:succeed))
(t
(let ((d (deferred:new)))
(push d (cc:semaphore-waiting-deferreds semaphore))
d))))
(defun cc:semaphore-release(semaphore)
"Release an execution permission. The programmer is responsible to return the permissions."
(when (<= (cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore))
(error "Too many calling semaphore-release. [max:%s <= permits:%s]"
(cc:semaphore-max-permits semaphore)
(cc:semaphore-permits semaphore)))
(let ((waiting-deferreds
(cc:semaphore-waiting-deferreds semaphore)))
(cond
(waiting-deferreds
(let* ((d (car (last waiting-deferreds))))
(setf (cc:semaphore-waiting-deferreds semaphore)
(nbutlast waiting-deferreds))
(deferred:callback-post d)))
(t
(incf (cc:semaphore-permits semaphore)))))
semaphore)
(defun cc:semaphore-with (semaphore body-func &optional error-func)
"Execute the task BODY-FUNC asynchronously with the semaphore block."
(lexical-let ((semaphore semaphore))
(deferred:try
(deferred:nextc (cc:semaphore-acquire semaphore) body-func)
:catch
error-func
:finally
(lambda (x) (cc:semaphore-release semaphore)))))
(put 'cc:semaphore-with 'lisp-indent-function 1)
(defun cc:semaphore-release-all (semaphore)
"Release all permissions for resetting the semaphore object.
If the semaphore object has some blocked tasks, this function
return a list of the tasks and clear the list of the blocked
tasks in the semaphore object."
(setf (cc:semaphore-permits semaphore)
(cc:semaphore-max-permits semaphore))
(let ((ds (cc:semaphore-waiting-deferreds semaphore)))
(when ds
(setf (cc:semaphore-waiting-deferreds semaphore) nil))
ds))
(defun cc:semaphore-interrupt-all (semaphore)
"Clear the list of the blocked tasks in the semaphore and return a deferred object to chain.
This function is used for the interruption cases."
(when (cc:semaphore-waiting-deferreds semaphore)
(setf (cc:semaphore-waiting-deferreds semaphore) nil)
(setf (cc:semaphore-permits semaphore) 0))
(cc:semaphore-acquire semaphore))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Signal / Channel
(defun cc:signal-channel (&optional name parent-channel)
"Create a channel.
NAME is a channel name for debug.
PARENT-CHANNEL is an upstream channel. The observers of this channel can receive the upstream signals.
In the case of using the function `cc:signal-send', the observers of the upstream channel can not receive the signals of this channel. The function `cc:signal-send-global' can send a signal to the upstream channels from the downstream channels."
(lexical-let
((ch (cons
(or name (format "signal%s" (deferred:uid))) ; name for debug
(cons
parent-channel ; parent-channel
nil)))) ; observers
(when parent-channel
(cc:signal-connect
parent-channel
t (lambda (event)
(destructuring-bind
(event-name event-args) event
(apply 'cc:signal-send
ch event-name event-args)))))
ch))
(defmacro cc:signal-name (ch)
"[internal] Return signal name."
`(car ,ch))
(defmacro cc:signal-parent-channel (ch)
"[internal] Return parent channel object."
`(cadr ,ch))
(defmacro cc:signal-observers (ch)
"[internal] Return observers."
`(cddr ,ch))
(defun cc:signal-connect (channel event-sym &optional callback)
"Append an observer for EVENT-SYM of CHANNEL and return a deferred object.
If EVENT-SYM is `t', the observer receives all signals of the channel.
If CALLBACK function is given, the deferred object executes the
CALLBACK function asynchronously. One can connect subsequent
tasks to the returned deferred object."
(let ((d (if callback
(deferred:new callback)
(deferred:new))))
(push (cons event-sym d)
(cc:signal-observers channel))
d))
(defun cc:signal-send (channel event-sym &rest args)
"Send a signal to CHANNEL. If ARGS values are given, observers can get the values by following code: (lambda (event) (destructuring-bind (event-sym (args)) event ... )). "
(let ((observers (cc:signal-observers channel))
(event (list event-sym args)))
(loop for i in observers
for name = (car i)
for d = (cdr i)
if (or (eq event-sym name) (eq t name))
do (deferred:callback-post d event))))
(defun cc:signal-send-global (channel event-sym &rest args)
"Send a signal to the most upstream channel. "
(cc:aif (cc:signal-parent-channel channel)
(apply 'cc:signal-send-global it event-sym args)
(apply 'cc:signal-send channel event-sym args)))
(defun cc:signal-disconnect (channel deferred)
"Remove the observer object DEFERRED from CHANNEL and return
the removed deferred object. "
(let ((observers (cc:signal-observers channel)) deleted)
(setf
(cc:signal-observers channel) ; place
(loop for i in observers
for d = (cdr i)
unless (eq d deferred)
collect i
else
do (push i deleted)))
deleted))
(defun cc:signal-disconnect-all (channel)
"Remove all observers."
(setf
(cc:signal-observers channel) ; place
nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dataflow
;; Dataflow variable entry
(defstruct cc:dataflow key (value 'cc:dataflow-undefine) deferred-list)
(defun cc:dataflow-undefine-p (obj)
"[internal] If the variable entry is not bound, return `t'."
(eq 'cc:dataflow-undefine (cc:dataflow-value obj)))
(defun cc:dataflow-environment (&optional parent-env test-func channel)
"Create a dataflow environment.
PARENT-ENV is the default environment. If this environment doesn't have the entry A and the parent one has the entry A, this environment can return the entry A. One can override the entry, setting another entry A to this environment.
TEST-FUNC is a test function that compares the entry keys. The default function is `equal'.
CHANNEL is a channel object that sends signals of variable events. Observers can receive following signals:
-get-first : the fist referrer is waiting for binding,
-get-waiting : another referrer is waiting for binding,
-set : a value is bound,
-get : returned a bound value,
-clear : cleared one entry,
-clear-all : cleared all entries.
"
(let ((this (list parent-env
(or test-func 'equal)
(or channel
(cc:signal-channel
'dataflow
(and parent-env
(cc:dataflow-channel parent-env)))))))
(cc:dataflow-init-connect this)
this))
(defun cc:dataflow-init-connect (df)
"[internal] Initialize the channel object."
(lexical-let ((df df))
(cc:dataflow-connect
df 'set
(lambda (args)
(destructuring-bind (event (key)) args
(let* ((obj (cc:dataflow-get-object-for-value df key))
(value (and obj (cc:dataflow-value obj))))
(when obj
(loop for i in (cc:aif (cc:dataflow-get-object-for-deferreds df key)
(cc:dataflow-deferred-list it) nil)
do (deferred:callback-post i value))
(setf (cc:dataflow-deferred-list obj) nil))))))))
(defmacro cc:dataflow-parent-environment (df)
"[internal] Return the parent environment."
`(car ,df))
(defmacro cc:dataflow-test (df)
"[internal] Return the test function."
`(cadr ,df))
(defmacro cc:dataflow-channel (df)
"[internal] Return the channel object."
`(caddr ,df))
(defmacro cc:dataflow-list (df)
"[internal] Return the list of deferred object which are waiting for value binding."
`(cdddr ,df))
(defun cc:dataflow-get-object-for-value (df key)
"[internal] Return an entry object that is indicated by KEY.
If the environment DF doesn't have the entry and the parent one has the entry, this function returns the entry of the parent environment. This function doesn't affect the waiting list."
(or
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (and (funcall test key (cc:dataflow-key i))
(not (cc:dataflow-undefine-p i)))
return i)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-object-for-value it key))))
(defun cc:dataflow-get-object-for-deferreds (df key)
"[internal] Return a list of the deferred objects those are waiting for value binding.
This function doesn't affect the waiting list and doesn't refer the parent environment."
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
if (funcall test key (cc:dataflow-key i))
return i))
(defun cc:dataflow-connect (df event-sym &optional callback)
"Append an observer for EVENT-SYM of the channel of DF and return a deferred object.
See the docstring of `cc:dataflow-environment' for details."
(cc:signal-connect (cc:dataflow-channel df) event-sym callback))
(defun cc:dataflow-signal (df event &optional arg)
"[internal] Send a signal to the channel of DF."
(cc:signal-send (cc:dataflow-channel df) event arg))
(defun cc:dataflow-get (df key)
"Return a deferred object that can refer the value which is indicated by KEY.
If DF has the entry that bound value, the subsequent deferred task is executed immediately.
If not, the task is deferred till a value is bound."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(cond
((and obj (cc:dataflow-value obj))
(cc:dataflow-signal df 'get key)
(deferred:succeed (cc:dataflow-value obj)))
(t
(setq obj (cc:dataflow-get-object-for-deferreds df key))
(unless obj
(setq obj (make-cc:dataflow :key key))
(push obj (cc:dataflow-list df))
(cc:dataflow-signal df 'get-first key))
(let ((d (deferred:new)))
(push d (cc:dataflow-deferred-list obj))
(cc:dataflow-signal df 'get-waiting key)
d)))))
(defun cc:dataflow-get-sync (df key)
"Return the value which is indicated by KEY synchronously.
If the environment DF doesn't have an entry of KEY, this function returns nil."
(let ((obj (cc:dataflow-get-object-for-value df key)))
(and obj (cc:dataflow-value obj))))
(defun cc:dataflow-set (df key value)
"Bind the VALUE to KEY in the environment DF.
If DF already has the bound entry of KEY, this function throws an error signal.
VALUE can be nil as a value."
(let ((obj (cc:dataflow-get-object-for-deferreds df key)))
(cond
((and obj (not (cc:dataflow-undefine-p obj)))
;; overwrite!
(error "Can not set a dataflow value. The key [%s] has already had a value. NEW:[%s] OLD:[%s]" key value (cc:dataflow-value obj)))
(obj
(setf (cc:dataflow-value obj) value))
(t
;; just value arrived
(push (make-cc:dataflow :key key :value value)
(cc:dataflow-list df))))
;; value arrived and start deferred objects
(cc:dataflow-signal df 'set key)
value))
(defun cc:dataflow-clear (df key)
"Clear the entry which is indicated by KEY.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear key)
(setf (cc:dataflow-list df)
(loop for i in (cc:dataflow-list df)
with test = (cc:dataflow-test df)
unless (funcall test key (cc:dataflow-key i))
collect i)))
(defun cc:dataflow-get-avalable-pairs (df)
"Return an available key-value alist in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
unless (cc:dataflow-undefine-p i) collect (cons key val))
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-avalable-pairs it))))
(defun cc:dataflow-get-waiting-keys (df)
"Return a list of keys which have waiting deferred objects in the environment DF and the parent ones."
(append
(loop for i in (cc:dataflow-list df)
for key = (cc:dataflow-key i)
for val = (cc:dataflow-value i)
if (cc:dataflow-undefine-p i) collect key)
(deferred:aand
(cc:dataflow-parent-environment df)
(cc:dataflow-get-waiting-keys it))))
(defun cc:dataflow-clear-all (df)
"Clear all entries in the environment DF.
This function does nothing for the waiting deferred objects."
(cc:dataflow-signal df 'clear-all)
(setf (cc:dataflow-list df) nil))
(provide 'concurrent)
;;; concurrent.el ends here
|
[
{
"context": "-message-contact-field-matches msg \n\t\t\t\t\t\t\t\t :to \"ragnese@ufl.edu\")))\n\t :vars '((user-mail-address . \"ragn",
"end": 582,
"score": 0.999928891658783,
"start": 567,
"tag": "EMAIL",
"value": "ragnese@ufl.edu"
},
{
"context": ".edu\")))\n\t :vars '((user-mail-address . \"ragnese@ufl.edu\")\n\t\t (user-full-name . \"Rob Agnese\")\n",
"end": 643,
"score": 0.9999275207519531,
"start": 628,
"tag": "EMAIL",
"value": "ragnese@ufl.edu"
},
{
"context": "gnese@ufl.edu\")\n\t\t (user-full-name . \"Rob Agnese\")\n\t\t (mu4e-maildir . \"~/mail/ufl\")\n",
"end": 690,
"score": 0.9998642206192017,
"start": 680,
"tag": "NAME",
"value": "Rob Agnese"
},
{
"context": "-message-contact-field-matches msg \n\t\t\t\t\t\t\t\t :to \"rob@litmushealth.com\")))\n\t :vars '((user-mail-address . \"rob",
"end": 1315,
"score": 0.9999340772628784,
"start": 1295,
"tag": "EMAIL",
"value": "rob@litmushealth.com"
},
{
"context": "com\")))\n\t :vars '((user-mail-address . \"rob@litmushealth.com\")\n\t\t ( user-full-name . \"Rob Agnese\")",
"end": 1382,
"score": 0.9999350905418396,
"start": 1362,
"tag": "EMAIL",
"value": "rob@litmushealth.com"
},
{
"context": "ushealth.com\")\n\t\t ( user-full-name . \"Rob Agnese\")\n\t\t (mu4e-maildir . \"~/mail/litmus",
"end": 1430,
"score": 0.9998765587806702,
"start": 1420,
"tag": "NAME",
"value": "Rob Agnese"
}
] | elisp/init-mu4e.el | ragnese/emacs-settings | 1 | ;;; package --- Initializes my mu4esettings.
;;; Commentary:
;;; Code:
;; Enable mu4e
(use-package mu4e
:config
;; Create contexts for each account
;; TODO: match UFL on phys.ufl.edu too
(setq mu4e-contexts
`( ,(make-mu4e-context
:name "UFL"
:enter-func (lambda () (mu4e-message "Entering UFL context"))
:leave-func (lambda () (mu4e-message "Leaving UFL context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "ragnese@ufl.edu")))
:vars '((user-mail-address . "ragnese@ufl.edu")
(user-full-name . "Rob Agnese")
(mu4e-maildir . "~/mail/ufl")
(mu4e-sent-folder . "/Sent Items")
(mu4e-drafts-folder . "/Drafts")
(mu4e-trash-folder . "/Deleted Items")
(mu4e-refile-folder . "/Archives/2017")))
,(make-mu4e-context
:name "Litmus"
:enter-func (lambda () (mu4e-message "Entering Litmus context"))
:leave-func (lambda () (mu4e-message "Leaving Litmus context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "rob@litmushealth.com")))
:vars '((user-mail-address . "rob@litmushealth.com")
( user-full-name . "Rob Agnese")
(mu4e-maildir . "~/mail/litmus")
(mu4e-sent-folder . "/[Gmail]/Sent Mail")
(mu4e-drafts-folder . "/[Gmail]/Drafts")
(mu4e-trash-folder . "/[Gmail]/Trash")
(mu4e-refile-folder . "/All Mail")))))
;; Update every 10 minutes
(setq mu4e-update-interval 600)
;; don't do a full cleanup check
;;(setq mu4e-index-cleanup nil)
;; don't consider up-to-date dirs
;;(setq mu4e-index-lazy-check t)
;; compose with the current context is no context matches;
;; default is to ask
(setq mu4e-compose-context-policy nil))
(provide 'init-mu4e)
;;; init-mu4e ends here
| 18366 | ;;; package --- Initializes my mu4esettings.
;;; Commentary:
;;; Code:
;; Enable mu4e
(use-package mu4e
:config
;; Create contexts for each account
;; TODO: match UFL on phys.ufl.edu too
(setq mu4e-contexts
`( ,(make-mu4e-context
:name "UFL"
:enter-func (lambda () (mu4e-message "Entering UFL context"))
:leave-func (lambda () (mu4e-message "Leaving UFL context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "<EMAIL>")))
:vars '((user-mail-address . "<EMAIL>")
(user-full-name . "<NAME>")
(mu4e-maildir . "~/mail/ufl")
(mu4e-sent-folder . "/Sent Items")
(mu4e-drafts-folder . "/Drafts")
(mu4e-trash-folder . "/Deleted Items")
(mu4e-refile-folder . "/Archives/2017")))
,(make-mu4e-context
:name "Litmus"
:enter-func (lambda () (mu4e-message "Entering Litmus context"))
:leave-func (lambda () (mu4e-message "Leaving Litmus context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "<EMAIL>")))
:vars '((user-mail-address . "<EMAIL>")
( user-full-name . "<NAME>")
(mu4e-maildir . "~/mail/litmus")
(mu4e-sent-folder . "/[Gmail]/Sent Mail")
(mu4e-drafts-folder . "/[Gmail]/Drafts")
(mu4e-trash-folder . "/[Gmail]/Trash")
(mu4e-refile-folder . "/All Mail")))))
;; Update every 10 minutes
(setq mu4e-update-interval 600)
;; don't do a full cleanup check
;;(setq mu4e-index-cleanup nil)
;; don't consider up-to-date dirs
;;(setq mu4e-index-lazy-check t)
;; compose with the current context is no context matches;
;; default is to ask
(setq mu4e-compose-context-policy nil))
(provide 'init-mu4e)
;;; init-mu4e ends here
| true | ;;; package --- Initializes my mu4esettings.
;;; Commentary:
;;; Code:
;; Enable mu4e
(use-package mu4e
:config
;; Create contexts for each account
;; TODO: match UFL on phys.ufl.edu too
(setq mu4e-contexts
`( ,(make-mu4e-context
:name "UFL"
:enter-func (lambda () (mu4e-message "Entering UFL context"))
:leave-func (lambda () (mu4e-message "Leaving UFL context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "PI:EMAIL:<EMAIL>END_PI")))
:vars '((user-mail-address . "PI:EMAIL:<EMAIL>END_PI")
(user-full-name . "PI:NAME:<NAME>END_PI")
(mu4e-maildir . "~/mail/ufl")
(mu4e-sent-folder . "/Sent Items")
(mu4e-drafts-folder . "/Drafts")
(mu4e-trash-folder . "/Deleted Items")
(mu4e-refile-folder . "/Archives/2017")))
,(make-mu4e-context
:name "Litmus"
:enter-func (lambda () (mu4e-message "Entering Litmus context"))
:leave-func (lambda () (mu4e-message "Leaving Litmus context"))
;; we match based on the contact-fields of the message
:match-func (lambda (msg)
(when msg
(mu4e-message-contact-field-matches msg
:to "PI:EMAIL:<EMAIL>END_PI")))
:vars '((user-mail-address . "PI:EMAIL:<EMAIL>END_PI")
( user-full-name . "PI:NAME:<NAME>END_PI")
(mu4e-maildir . "~/mail/litmus")
(mu4e-sent-folder . "/[Gmail]/Sent Mail")
(mu4e-drafts-folder . "/[Gmail]/Drafts")
(mu4e-trash-folder . "/[Gmail]/Trash")
(mu4e-refile-folder . "/All Mail")))))
;; Update every 10 minutes
(setq mu4e-update-interval 600)
;; don't do a full cleanup check
;;(setq mu4e-index-cleanup nil)
;; don't consider up-to-date dirs
;;(setq mu4e-index-lazy-check t)
;; compose with the current context is no context matches;
;; default is to ask
(setq mu4e-compose-context-policy nil))
(provide 'init-mu4e)
;;; init-mu4e ends here
|
[
{
"context": "/project/etc buffers\n;;\n;; Copyright (C) 2011-2016 Vitalie Spinu\n;; Author: Vitalie Spinu <spinuvit.list[ aaattt ",
"end": 125,
"score": 0.9998937845230103,
"start": 112,
"tag": "NAME",
"value": "Vitalie Spinu"
},
{
"context": "; Copyright (C) 2011-2016 Vitalie Spinu\n;; Author: Vitalie Spinu <spinuvit.list[ aaattt ]gmail[ dot ]com>\n;; Vers",
"end": 150,
"score": 0.9998942613601685,
"start": 137,
"tag": "NAME",
"value": "Vitalie Spinu"
},
{
"context": "ords: ido, imenu, tags\n;; URL: https://github.com/vitoshka/imenu-anywhere\n;; Package-Requires: ((cl-lib \"0.5",
"end": 310,
"score": 0.9958775639533997,
"start": 302,
"tag": "USERNAME",
"value": "vitoshka"
}
] | elpa/imenu-anywhere-20170805.1855/imenu-anywhere.el | llacom/emacs.d | 0 | ;;; imenu-anywhere.el --- ido/ivy/helm imenu across same mode/project/etc buffers
;;
;; Copyright (C) 2011-2016 Vitalie Spinu
;; Author: Vitalie Spinu <spinuvit.list[ aaattt ]gmail[ dot ]com>
;; Version: 1.1.4
;; Package-Version: 20170805.1855
;; Keywords: ido, imenu, tags
;; URL: https://github.com/vitoshka/imenu-anywhere
;; Package-Requires: ((cl-lib "0.5"))
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; `imenu-anywhere` provides navigation for imenu tags across all buffers that
;; satisfy grouping criteria. Available criteria include - all buffers with the
;; same major mode, same project buffers and user defined list of friendly mode
;; buffers.
;;
;; To activate, just bind `imenu-anywhere' to a convenient key:
;;
;; (global-set-key (kbd "C-.") 'imenu-anywhere)
;;
;; By default `imenu-anywhere' uses plain `completing-read'. `ido-imenu-anywhere',
;; `ivy-imenu-anywhere' and `helm-imenu-anywhere' are specialized interfaces.
;;
;; Several filtering strategies are available - same-mode buffers, same-project
;; buffers and user defined friendly buffers. See
;; `imenu-anywhere-buffer-filter-functions' and `imenu-anywhere-friendly-modes'.
;;
;;; Code:
(require 'imenu)
(require 'cl-lib)
;;; Customization
(defgroup imenu-anywhere nil
"Imenu tag selection across multiple buffers."
:group 'tools
:group 'convenience)
(defcustom imenu-anywhere-friendly-modes
'((clojure-mode clojurex-mode clojurec-mode clojurescript-mode cider-repl-mode cider-clojure-interaction-mode)
(emacs-lisp-mode inferior-emacs-lisp-mode lisp-interaction-mode)
(ess-mode inferior-ess-mode)
(python-mode inferior-python-mode))
"List of lists of friendly modes.
Each sub-lists contains set of modes which are mutually
accessible. That is, if mode A and B are in the same sub-list
then imenu items from buffer with mode B are accessible from
buffer with mode A and vice versa."
:group 'imenu-anywhere
:type '(repeat (repeat symbol)))
(defcustom imenu-anywhere-buffer-filter-functions
'(imenu-anywhere-same-mode-p
imenu-anywhere-friendly-mode-p
imenu-anywhere-same-project-p)
"Functions returning non-nil if buffer's imenu tags are accessible.
Each function takes two arguments CURRENT-BUFFER and
OTHER-BUFFER. If any of the functions returns non-nil, imenu
items from OTHER-BUFFER are accessible from the
CURRENT-BUFFER. Filters defined in this package are:
`imenu-anywhere-same-mode-p', `imenu-anywhere-friendly-mode-p'
and `imenu-anywhere-same-project-p'. See also
`imenu-anywhere-buffer-list-function' for extra flexibility."
:group 'imenu-anywhere
:type '(repeat symbol))
(defvar imenu-anywhere-preprocess-entry-function 'imenu-anywhere-preprocess-for-completion
"Holds a function to process each entry.
Function must accept two arguments - entry and entry name. See
the code for `imenu-anywhere-preprocess-for-completion' and
`imenu-anywhere-preprocess-for-listing' for examples.")
(defvar-local imenu-anywhere-buffer-list-function 'buffer-list
"Function that returns the list of buffers for `imenu-anywhere' to consider.
Any buffers that are not on this list will be ignored. This
function is called before filters in
`imenu-anywhere-buffer-filter-functions'.")
(defvar imenu-anywhere-delimiter "/")
(defvar imenu-anywhere--project-buffers nil)
(defvar-local imenu-anywhere--cached-candidates nil)
(defvar-local imenu-anywhere--cached-tick nil)
(defvar-local imenu-anywhere--cached-prep-function nil)
(defun imenu-anywhere-same-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have same mode."
(eq (buffer-local-value 'major-mode current)
(buffer-local-value 'major-mode other)))
(defun imenu-anywhere-friendly-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have friendly modes.
Friendly modes are defined by `imenu-anywhere-friendly-modes'."
(let ((cmode (buffer-local-value 'major-mode current))
(omode (buffer-local-value 'major-mode other)))
(cl-some (lambda (mlist)
(and (member cmode mlist)
(member omode mlist)))
imenu-anywhere-friendly-modes)))
(defun imenu-anywhere-same-project-p (current other)
"Return non-nil if buffers CURRENT and OTHER are part of the same project.
Currently only projectile projects are supported."
(unless imenu-anywhere--project-buffers
(when (fboundp 'projectile-project-buffers)
(let (projectile-require-project-root)
(setq-local imenu-anywhere--project-buffers
(or (funcall 'projectile-project-buffers)
(list nil))))))
(member other imenu-anywhere--project-buffers))
(defun imenu-anywhere--reachable-buffer-p (buffer)
(cl-some (lambda (fun)
(funcall fun (current-buffer) buffer))
imenu-anywhere-buffer-filter-functions))
(defun imenu-anywhere-candidates ()
"Return an alist of imenu tags from reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'."
(setq-local imenu-anywhere--project-buffers nil)
(let ((buffers (cl-loop for b in (funcall imenu-anywhere-buffer-list-function)
if (imenu-anywhere--reachable-buffer-p b)
collect b)))
(apply 'append
(mapcar (lambda (buff)
(with-current-buffer buff
(let ((tick (buffer-modified-tick buff)))
(if (and (eq imenu-anywhere--cached-tick tick)
(eq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function))
;; return cached
imenu-anywhere--cached-candidates
;; else update the indexes if in imenu buffer
(setq imenu-anywhere--cached-tick tick)
(setq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function)
(setq imenu-anywhere--cached-candidates
(imenu-anywhere-buffer-candidates))))))
buffers))))
(defun imenu-anywhere-buffer-candidates ()
"Return an alist of candidates in the current buffer."
;; avoid imenu throwing ugly messages
(when (or imenu-generic-expression
(and imenu-prev-index-position-function
imenu-extract-index-name-function)
(not (eq imenu-create-index-function 'imenu-default-create-index-function)))
(let* ((old-index imenu--index-alist)
(index (condition-case err
(progn
(setq imenu--index-alist nil)
(imenu--make-index-alist t))
(error
(message "Imenu error in %s. Keeping old index. (%s)" (current-buffer) (error-message-string err))
(setq imenu--index-alist old-index)))))
(when index
(cl-delete-if (lambda (el) (null (car el)))
(sort (cl-mapcan 'imenu-anywhere--candidates-from-entry
index)
(lambda (a b) (< (length (car a)) (length (car b))))))))))
(defun imenu-anywhere--candidates-from-entry (entry &optional inner-p)
"Create candidates from imenu ENTRY.
Return a list of entries when entry is a `imenu--subalist-p' or a
list of one entry otherwise."
(let ((ecdr (cdr entry))
(prep-fun imenu-anywhere-preprocess-entry-function))
(cond ((imenu--subalist-p entry)
(mapcar (lambda (sub-entry)
(funcall prep-fun sub-entry (car entry)))
(cl-mapcan (lambda (el) (imenu-anywhere--candidates-from-entry el t))
(cdr entry))))
((integerp ecdr)
(when (> ecdr 0) ;; drop (*Rescan* . -99)
(let ((entry (cons (car entry) (copy-marker ecdr))))
(list (if inner-p entry (funcall prep-fun entry nil))))))
((and (listp ecdr) (eq (car ecdr) 'IGNORE)) nil)
(t (list (if inner-p entry (funcall prep-fun entry nil)))))))
(defun imenu-anywhere-preprocess-for-completion (entry parent-name)
"Default function for `imenu-anywhere-preprocess-entry-function'.
Concatenate imenu ENTRY and PARENT-NAME in a meaningful way. This
pre-processing is suitable for minibuffer completion mechanisms
such as `completing-read' or `ido-completing-read'."
(when entry
(let* ((entry-name (replace-regexp-in-string "\\c-*$" "" (car entry)))
;; in python hierarchical entry is defined as ("foo"
;; (*function-definition* ...) (sub-name ..)) where "foo" is the
;; ENTRY-NAME from above and *function-definition* is PREFIX. In this
;; case we need to reverse the position. We detect such entries by
;; assuming that they are enclosed in *..* and hope for the best.
(reverse (string-match-p "^\\*.*\\*$" entry-name))
(sep (and parent-name imenu-anywhere-delimiter)))
(setcar entry (if reverse
(concat parent-name sep entry-name)
(concat entry-name sep parent-name)))
entry)))
(defun imenu-anywhere-preprocess-for-listing (entry entry-name)
"Pre-processor of imenu ENTRY suitable for hierarchical listings.
ENTRY-NAME is commonly a class or type of the object. Helm and
IVY backends use this pre-processing strategy."
(when entry
(let ((bname (if (markerp (cdr entry))
(concat (buffer-name (marker-buffer (cdr entry))) ": ")
"")))
(setcar entry (concat bname
entry-name
(and entry-name
imenu-anywhere-delimiter)
(car entry))))
entry))
(defun imenu-anywhere--guess-default (index-alist str-at-pt)
"Guess a default choice from the given imenu list and string at point."
(let ((name (regexp-quote str-at-pt)))
(catch 'found
(dolist (regex (list (concat "\\`" name "\\'")
(concat "\\`" name)
(concat name "\\'")
name))
(dolist (item index-alist)
(if (string-match regex (car item))
(throw 'found (car item))))))))
(defun imenu-anywhere-goto (name position &optional rest)
"Function used as `imenu-default-goto-function'."
(let* ((is-overlay (overlayp position))
(buff (or (and is-overlay (overlay-buffer position))
(marker-buffer position)))
(position (or (and is-overlay (overlay-start position))
(marker-position position))))
(switch-to-buffer buff)
(when (or (< position (point-min))
(> position (point-max)))
(widen))
(goto-char position)))
;;;###autoload
(defun imenu-anywhere ()
"Go to imenu tag defined in all reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'.
Sorting is done within each buffer and takes into account items'
length. Thus more recent buffers in `buffer-list' and shorter
entries have higher priority."
(interactive)
(let ((imenu-default-goto-function 'imenu-anywhere-goto)
(index-alist (imenu-anywhere-candidates)))
(if (null index-alist)
(message "No imenu tags")
(let ((selection
(let* ((str-at-pt (thing-at-point 'symbol))
(default (and str-at-pt
(imenu-anywhere--guess-default index-alist str-at-pt)))
(names (mapcar 'car index-alist))
(name (completing-read "Imenu: " names nil t nil nil default)))
(assoc name index-alist))))
(imenu selection)))))
;;; IDO
;;;###autoload
(defun ido-imenu-anywhere ()
"IDO interface for `imenu-anywhere'.
This is a simple wrapper around `imenu-anywhere' which uses
`ido-completing-read' as `completing-read-function'. If you use
`ido-ubiquitous' you might be better off by using `ido-anywhere'
instead, but there should be little or no difference."
(interactive)
(require 'ido)
(let ((imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-completion)
(completing-read-function 'ido-completing-read))
(imenu-anywhere)))
;;; IVY
;;;###autoload
(defun ivy-imenu-anywhere ()
"IVY interface for `imenu-anywhere'
This is a simple wrapper around `imenu-anywhere' which uses
`ivy-completing-read' as `completing-read-function'."
(interactive)
(unless (require 'ivy nil t)
(error "[imenu-anywhere]: This command requires 'ivy' package"))
(let ((ivy-sort-functions-alist)
(imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-listing)
(completing-read-function 'ivy-completing-read))
(imenu-anywhere)))
;;; HELM
;; silence byte-compiler
(defvar helm-sources-using-default-as-input)
(defvar helm-imenu-fuzzy-match)
(defvar helm-current-buffer)
(declare-function helm "helm")
(declare-function helm-highlight-current-line "helm-utils")
(declare-function helm-make-source "helm-source")
(eval-after-load "helm"
'(progn
(require 'helm-imenu)
(defvar helm-source-imenu-anywhere
(helm-make-source "imenu-anywere" 'helm-source-sync
:candidates #'helm-imenu-anywhere-candidates
:persistent-action (lambda (elm)
(imenu-anywhere-goto "" elm)
(unless (fboundp 'semantic-imenu-tag-overlay)
(helm-highlight-current-line)))
:fuzzy-match helm-imenu-fuzzy-match
:persistent-help "Show this entry"
:action (lambda (elm) (imenu-anywhere-goto "" elm)))
"Helm source for `imenu-anywhere' (which see).")
(add-to-list 'helm-sources-using-default-as-input 'helm-source-imenu-anywhere)))
(defun helm-imenu-anywhere-candidates ()
;; don't use macro with-helm-current-buffer
(with-current-buffer (or (and (buffer-live-p helm-current-buffer) helm-current-buffer)
(setq helm-current-buffer (current-buffer)))
(let ((imenu-anywhere-preprocess-entry-function
'imenu-anywhere-preprocess-for-listing))
(imenu-anywhere-candidates))))
;;;###autoload
(defun helm-imenu-anywhere ()
"`helm' interface for `imenu-anywhere'.
Sorting is in increasing length of imenu symbols within each
buffer. The pyramidal view allows distinguishing different
buffers."
(interactive)
(unless (require 'helm nil t)
(error "[imenu-anywhere]: This command requires 'helm' package"))
(let ((imenu-default-goto-function 'imenu-anywhere-goto))
(helm :sources 'helm-source-imenu-anywhere
:default (thing-at-point 'symbol)
:buffer "*helm imenu-anywhere*")))
(provide 'imenu-anywhere)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; imenu-anywhere.el ends here
| 49719 | ;;; imenu-anywhere.el --- ido/ivy/helm imenu across same mode/project/etc buffers
;;
;; Copyright (C) 2011-2016 <NAME>
;; Author: <NAME> <spinuvit.list[ aaattt ]gmail[ dot ]com>
;; Version: 1.1.4
;; Package-Version: 20170805.1855
;; Keywords: ido, imenu, tags
;; URL: https://github.com/vitoshka/imenu-anywhere
;; Package-Requires: ((cl-lib "0.5"))
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; `imenu-anywhere` provides navigation for imenu tags across all buffers that
;; satisfy grouping criteria. Available criteria include - all buffers with the
;; same major mode, same project buffers and user defined list of friendly mode
;; buffers.
;;
;; To activate, just bind `imenu-anywhere' to a convenient key:
;;
;; (global-set-key (kbd "C-.") 'imenu-anywhere)
;;
;; By default `imenu-anywhere' uses plain `completing-read'. `ido-imenu-anywhere',
;; `ivy-imenu-anywhere' and `helm-imenu-anywhere' are specialized interfaces.
;;
;; Several filtering strategies are available - same-mode buffers, same-project
;; buffers and user defined friendly buffers. See
;; `imenu-anywhere-buffer-filter-functions' and `imenu-anywhere-friendly-modes'.
;;
;;; Code:
(require 'imenu)
(require 'cl-lib)
;;; Customization
(defgroup imenu-anywhere nil
"Imenu tag selection across multiple buffers."
:group 'tools
:group 'convenience)
(defcustom imenu-anywhere-friendly-modes
'((clojure-mode clojurex-mode clojurec-mode clojurescript-mode cider-repl-mode cider-clojure-interaction-mode)
(emacs-lisp-mode inferior-emacs-lisp-mode lisp-interaction-mode)
(ess-mode inferior-ess-mode)
(python-mode inferior-python-mode))
"List of lists of friendly modes.
Each sub-lists contains set of modes which are mutually
accessible. That is, if mode A and B are in the same sub-list
then imenu items from buffer with mode B are accessible from
buffer with mode A and vice versa."
:group 'imenu-anywhere
:type '(repeat (repeat symbol)))
(defcustom imenu-anywhere-buffer-filter-functions
'(imenu-anywhere-same-mode-p
imenu-anywhere-friendly-mode-p
imenu-anywhere-same-project-p)
"Functions returning non-nil if buffer's imenu tags are accessible.
Each function takes two arguments CURRENT-BUFFER and
OTHER-BUFFER. If any of the functions returns non-nil, imenu
items from OTHER-BUFFER are accessible from the
CURRENT-BUFFER. Filters defined in this package are:
`imenu-anywhere-same-mode-p', `imenu-anywhere-friendly-mode-p'
and `imenu-anywhere-same-project-p'. See also
`imenu-anywhere-buffer-list-function' for extra flexibility."
:group 'imenu-anywhere
:type '(repeat symbol))
(defvar imenu-anywhere-preprocess-entry-function 'imenu-anywhere-preprocess-for-completion
"Holds a function to process each entry.
Function must accept two arguments - entry and entry name. See
the code for `imenu-anywhere-preprocess-for-completion' and
`imenu-anywhere-preprocess-for-listing' for examples.")
(defvar-local imenu-anywhere-buffer-list-function 'buffer-list
"Function that returns the list of buffers for `imenu-anywhere' to consider.
Any buffers that are not on this list will be ignored. This
function is called before filters in
`imenu-anywhere-buffer-filter-functions'.")
(defvar imenu-anywhere-delimiter "/")
(defvar imenu-anywhere--project-buffers nil)
(defvar-local imenu-anywhere--cached-candidates nil)
(defvar-local imenu-anywhere--cached-tick nil)
(defvar-local imenu-anywhere--cached-prep-function nil)
(defun imenu-anywhere-same-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have same mode."
(eq (buffer-local-value 'major-mode current)
(buffer-local-value 'major-mode other)))
(defun imenu-anywhere-friendly-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have friendly modes.
Friendly modes are defined by `imenu-anywhere-friendly-modes'."
(let ((cmode (buffer-local-value 'major-mode current))
(omode (buffer-local-value 'major-mode other)))
(cl-some (lambda (mlist)
(and (member cmode mlist)
(member omode mlist)))
imenu-anywhere-friendly-modes)))
(defun imenu-anywhere-same-project-p (current other)
"Return non-nil if buffers CURRENT and OTHER are part of the same project.
Currently only projectile projects are supported."
(unless imenu-anywhere--project-buffers
(when (fboundp 'projectile-project-buffers)
(let (projectile-require-project-root)
(setq-local imenu-anywhere--project-buffers
(or (funcall 'projectile-project-buffers)
(list nil))))))
(member other imenu-anywhere--project-buffers))
(defun imenu-anywhere--reachable-buffer-p (buffer)
(cl-some (lambda (fun)
(funcall fun (current-buffer) buffer))
imenu-anywhere-buffer-filter-functions))
(defun imenu-anywhere-candidates ()
"Return an alist of imenu tags from reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'."
(setq-local imenu-anywhere--project-buffers nil)
(let ((buffers (cl-loop for b in (funcall imenu-anywhere-buffer-list-function)
if (imenu-anywhere--reachable-buffer-p b)
collect b)))
(apply 'append
(mapcar (lambda (buff)
(with-current-buffer buff
(let ((tick (buffer-modified-tick buff)))
(if (and (eq imenu-anywhere--cached-tick tick)
(eq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function))
;; return cached
imenu-anywhere--cached-candidates
;; else update the indexes if in imenu buffer
(setq imenu-anywhere--cached-tick tick)
(setq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function)
(setq imenu-anywhere--cached-candidates
(imenu-anywhere-buffer-candidates))))))
buffers))))
(defun imenu-anywhere-buffer-candidates ()
"Return an alist of candidates in the current buffer."
;; avoid imenu throwing ugly messages
(when (or imenu-generic-expression
(and imenu-prev-index-position-function
imenu-extract-index-name-function)
(not (eq imenu-create-index-function 'imenu-default-create-index-function)))
(let* ((old-index imenu--index-alist)
(index (condition-case err
(progn
(setq imenu--index-alist nil)
(imenu--make-index-alist t))
(error
(message "Imenu error in %s. Keeping old index. (%s)" (current-buffer) (error-message-string err))
(setq imenu--index-alist old-index)))))
(when index
(cl-delete-if (lambda (el) (null (car el)))
(sort (cl-mapcan 'imenu-anywhere--candidates-from-entry
index)
(lambda (a b) (< (length (car a)) (length (car b))))))))))
(defun imenu-anywhere--candidates-from-entry (entry &optional inner-p)
"Create candidates from imenu ENTRY.
Return a list of entries when entry is a `imenu--subalist-p' or a
list of one entry otherwise."
(let ((ecdr (cdr entry))
(prep-fun imenu-anywhere-preprocess-entry-function))
(cond ((imenu--subalist-p entry)
(mapcar (lambda (sub-entry)
(funcall prep-fun sub-entry (car entry)))
(cl-mapcan (lambda (el) (imenu-anywhere--candidates-from-entry el t))
(cdr entry))))
((integerp ecdr)
(when (> ecdr 0) ;; drop (*Rescan* . -99)
(let ((entry (cons (car entry) (copy-marker ecdr))))
(list (if inner-p entry (funcall prep-fun entry nil))))))
((and (listp ecdr) (eq (car ecdr) 'IGNORE)) nil)
(t (list (if inner-p entry (funcall prep-fun entry nil)))))))
(defun imenu-anywhere-preprocess-for-completion (entry parent-name)
"Default function for `imenu-anywhere-preprocess-entry-function'.
Concatenate imenu ENTRY and PARENT-NAME in a meaningful way. This
pre-processing is suitable for minibuffer completion mechanisms
such as `completing-read' or `ido-completing-read'."
(when entry
(let* ((entry-name (replace-regexp-in-string "\\c-*$" "" (car entry)))
;; in python hierarchical entry is defined as ("foo"
;; (*function-definition* ...) (sub-name ..)) where "foo" is the
;; ENTRY-NAME from above and *function-definition* is PREFIX. In this
;; case we need to reverse the position. We detect such entries by
;; assuming that they are enclosed in *..* and hope for the best.
(reverse (string-match-p "^\\*.*\\*$" entry-name))
(sep (and parent-name imenu-anywhere-delimiter)))
(setcar entry (if reverse
(concat parent-name sep entry-name)
(concat entry-name sep parent-name)))
entry)))
(defun imenu-anywhere-preprocess-for-listing (entry entry-name)
"Pre-processor of imenu ENTRY suitable for hierarchical listings.
ENTRY-NAME is commonly a class or type of the object. Helm and
IVY backends use this pre-processing strategy."
(when entry
(let ((bname (if (markerp (cdr entry))
(concat (buffer-name (marker-buffer (cdr entry))) ": ")
"")))
(setcar entry (concat bname
entry-name
(and entry-name
imenu-anywhere-delimiter)
(car entry))))
entry))
(defun imenu-anywhere--guess-default (index-alist str-at-pt)
"Guess a default choice from the given imenu list and string at point."
(let ((name (regexp-quote str-at-pt)))
(catch 'found
(dolist (regex (list (concat "\\`" name "\\'")
(concat "\\`" name)
(concat name "\\'")
name))
(dolist (item index-alist)
(if (string-match regex (car item))
(throw 'found (car item))))))))
(defun imenu-anywhere-goto (name position &optional rest)
"Function used as `imenu-default-goto-function'."
(let* ((is-overlay (overlayp position))
(buff (or (and is-overlay (overlay-buffer position))
(marker-buffer position)))
(position (or (and is-overlay (overlay-start position))
(marker-position position))))
(switch-to-buffer buff)
(when (or (< position (point-min))
(> position (point-max)))
(widen))
(goto-char position)))
;;;###autoload
(defun imenu-anywhere ()
"Go to imenu tag defined in all reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'.
Sorting is done within each buffer and takes into account items'
length. Thus more recent buffers in `buffer-list' and shorter
entries have higher priority."
(interactive)
(let ((imenu-default-goto-function 'imenu-anywhere-goto)
(index-alist (imenu-anywhere-candidates)))
(if (null index-alist)
(message "No imenu tags")
(let ((selection
(let* ((str-at-pt (thing-at-point 'symbol))
(default (and str-at-pt
(imenu-anywhere--guess-default index-alist str-at-pt)))
(names (mapcar 'car index-alist))
(name (completing-read "Imenu: " names nil t nil nil default)))
(assoc name index-alist))))
(imenu selection)))))
;;; IDO
;;;###autoload
(defun ido-imenu-anywhere ()
"IDO interface for `imenu-anywhere'.
This is a simple wrapper around `imenu-anywhere' which uses
`ido-completing-read' as `completing-read-function'. If you use
`ido-ubiquitous' you might be better off by using `ido-anywhere'
instead, but there should be little or no difference."
(interactive)
(require 'ido)
(let ((imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-completion)
(completing-read-function 'ido-completing-read))
(imenu-anywhere)))
;;; IVY
;;;###autoload
(defun ivy-imenu-anywhere ()
"IVY interface for `imenu-anywhere'
This is a simple wrapper around `imenu-anywhere' which uses
`ivy-completing-read' as `completing-read-function'."
(interactive)
(unless (require 'ivy nil t)
(error "[imenu-anywhere]: This command requires 'ivy' package"))
(let ((ivy-sort-functions-alist)
(imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-listing)
(completing-read-function 'ivy-completing-read))
(imenu-anywhere)))
;;; HELM
;; silence byte-compiler
(defvar helm-sources-using-default-as-input)
(defvar helm-imenu-fuzzy-match)
(defvar helm-current-buffer)
(declare-function helm "helm")
(declare-function helm-highlight-current-line "helm-utils")
(declare-function helm-make-source "helm-source")
(eval-after-load "helm"
'(progn
(require 'helm-imenu)
(defvar helm-source-imenu-anywhere
(helm-make-source "imenu-anywere" 'helm-source-sync
:candidates #'helm-imenu-anywhere-candidates
:persistent-action (lambda (elm)
(imenu-anywhere-goto "" elm)
(unless (fboundp 'semantic-imenu-tag-overlay)
(helm-highlight-current-line)))
:fuzzy-match helm-imenu-fuzzy-match
:persistent-help "Show this entry"
:action (lambda (elm) (imenu-anywhere-goto "" elm)))
"Helm source for `imenu-anywhere' (which see).")
(add-to-list 'helm-sources-using-default-as-input 'helm-source-imenu-anywhere)))
(defun helm-imenu-anywhere-candidates ()
;; don't use macro with-helm-current-buffer
(with-current-buffer (or (and (buffer-live-p helm-current-buffer) helm-current-buffer)
(setq helm-current-buffer (current-buffer)))
(let ((imenu-anywhere-preprocess-entry-function
'imenu-anywhere-preprocess-for-listing))
(imenu-anywhere-candidates))))
;;;###autoload
(defun helm-imenu-anywhere ()
"`helm' interface for `imenu-anywhere'.
Sorting is in increasing length of imenu symbols within each
buffer. The pyramidal view allows distinguishing different
buffers."
(interactive)
(unless (require 'helm nil t)
(error "[imenu-anywhere]: This command requires 'helm' package"))
(let ((imenu-default-goto-function 'imenu-anywhere-goto))
(helm :sources 'helm-source-imenu-anywhere
:default (thing-at-point 'symbol)
:buffer "*helm imenu-anywhere*")))
(provide 'imenu-anywhere)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; imenu-anywhere.el ends here
| true | ;;; imenu-anywhere.el --- ido/ivy/helm imenu across same mode/project/etc buffers
;;
;; Copyright (C) 2011-2016 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <spinuvit.list[ aaattt ]gmail[ dot ]com>
;; Version: 1.1.4
;; Package-Version: 20170805.1855
;; Keywords: ido, imenu, tags
;; URL: https://github.com/vitoshka/imenu-anywhere
;; Package-Requires: ((cl-lib "0.5"))
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; `imenu-anywhere` provides navigation for imenu tags across all buffers that
;; satisfy grouping criteria. Available criteria include - all buffers with the
;; same major mode, same project buffers and user defined list of friendly mode
;; buffers.
;;
;; To activate, just bind `imenu-anywhere' to a convenient key:
;;
;; (global-set-key (kbd "C-.") 'imenu-anywhere)
;;
;; By default `imenu-anywhere' uses plain `completing-read'. `ido-imenu-anywhere',
;; `ivy-imenu-anywhere' and `helm-imenu-anywhere' are specialized interfaces.
;;
;; Several filtering strategies are available - same-mode buffers, same-project
;; buffers and user defined friendly buffers. See
;; `imenu-anywhere-buffer-filter-functions' and `imenu-anywhere-friendly-modes'.
;;
;;; Code:
(require 'imenu)
(require 'cl-lib)
;;; Customization
(defgroup imenu-anywhere nil
"Imenu tag selection across multiple buffers."
:group 'tools
:group 'convenience)
(defcustom imenu-anywhere-friendly-modes
'((clojure-mode clojurex-mode clojurec-mode clojurescript-mode cider-repl-mode cider-clojure-interaction-mode)
(emacs-lisp-mode inferior-emacs-lisp-mode lisp-interaction-mode)
(ess-mode inferior-ess-mode)
(python-mode inferior-python-mode))
"List of lists of friendly modes.
Each sub-lists contains set of modes which are mutually
accessible. That is, if mode A and B are in the same sub-list
then imenu items from buffer with mode B are accessible from
buffer with mode A and vice versa."
:group 'imenu-anywhere
:type '(repeat (repeat symbol)))
(defcustom imenu-anywhere-buffer-filter-functions
'(imenu-anywhere-same-mode-p
imenu-anywhere-friendly-mode-p
imenu-anywhere-same-project-p)
"Functions returning non-nil if buffer's imenu tags are accessible.
Each function takes two arguments CURRENT-BUFFER and
OTHER-BUFFER. If any of the functions returns non-nil, imenu
items from OTHER-BUFFER are accessible from the
CURRENT-BUFFER. Filters defined in this package are:
`imenu-anywhere-same-mode-p', `imenu-anywhere-friendly-mode-p'
and `imenu-anywhere-same-project-p'. See also
`imenu-anywhere-buffer-list-function' for extra flexibility."
:group 'imenu-anywhere
:type '(repeat symbol))
(defvar imenu-anywhere-preprocess-entry-function 'imenu-anywhere-preprocess-for-completion
"Holds a function to process each entry.
Function must accept two arguments - entry and entry name. See
the code for `imenu-anywhere-preprocess-for-completion' and
`imenu-anywhere-preprocess-for-listing' for examples.")
(defvar-local imenu-anywhere-buffer-list-function 'buffer-list
"Function that returns the list of buffers for `imenu-anywhere' to consider.
Any buffers that are not on this list will be ignored. This
function is called before filters in
`imenu-anywhere-buffer-filter-functions'.")
(defvar imenu-anywhere-delimiter "/")
(defvar imenu-anywhere--project-buffers nil)
(defvar-local imenu-anywhere--cached-candidates nil)
(defvar-local imenu-anywhere--cached-tick nil)
(defvar-local imenu-anywhere--cached-prep-function nil)
(defun imenu-anywhere-same-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have same mode."
(eq (buffer-local-value 'major-mode current)
(buffer-local-value 'major-mode other)))
(defun imenu-anywhere-friendly-mode-p (current other)
"Return non-nil if buffers CURRENT and OTHER have friendly modes.
Friendly modes are defined by `imenu-anywhere-friendly-modes'."
(let ((cmode (buffer-local-value 'major-mode current))
(omode (buffer-local-value 'major-mode other)))
(cl-some (lambda (mlist)
(and (member cmode mlist)
(member omode mlist)))
imenu-anywhere-friendly-modes)))
(defun imenu-anywhere-same-project-p (current other)
"Return non-nil if buffers CURRENT and OTHER are part of the same project.
Currently only projectile projects are supported."
(unless imenu-anywhere--project-buffers
(when (fboundp 'projectile-project-buffers)
(let (projectile-require-project-root)
(setq-local imenu-anywhere--project-buffers
(or (funcall 'projectile-project-buffers)
(list nil))))))
(member other imenu-anywhere--project-buffers))
(defun imenu-anywhere--reachable-buffer-p (buffer)
(cl-some (lambda (fun)
(funcall fun (current-buffer) buffer))
imenu-anywhere-buffer-filter-functions))
(defun imenu-anywhere-candidates ()
"Return an alist of imenu tags from reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'."
(setq-local imenu-anywhere--project-buffers nil)
(let ((buffers (cl-loop for b in (funcall imenu-anywhere-buffer-list-function)
if (imenu-anywhere--reachable-buffer-p b)
collect b)))
(apply 'append
(mapcar (lambda (buff)
(with-current-buffer buff
(let ((tick (buffer-modified-tick buff)))
(if (and (eq imenu-anywhere--cached-tick tick)
(eq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function))
;; return cached
imenu-anywhere--cached-candidates
;; else update the indexes if in imenu buffer
(setq imenu-anywhere--cached-tick tick)
(setq imenu-anywhere--cached-prep-function
imenu-anywhere-preprocess-entry-function)
(setq imenu-anywhere--cached-candidates
(imenu-anywhere-buffer-candidates))))))
buffers))))
(defun imenu-anywhere-buffer-candidates ()
"Return an alist of candidates in the current buffer."
;; avoid imenu throwing ugly messages
(when (or imenu-generic-expression
(and imenu-prev-index-position-function
imenu-extract-index-name-function)
(not (eq imenu-create-index-function 'imenu-default-create-index-function)))
(let* ((old-index imenu--index-alist)
(index (condition-case err
(progn
(setq imenu--index-alist nil)
(imenu--make-index-alist t))
(error
(message "Imenu error in %s. Keeping old index. (%s)" (current-buffer) (error-message-string err))
(setq imenu--index-alist old-index)))))
(when index
(cl-delete-if (lambda (el) (null (car el)))
(sort (cl-mapcan 'imenu-anywhere--candidates-from-entry
index)
(lambda (a b) (< (length (car a)) (length (car b))))))))))
(defun imenu-anywhere--candidates-from-entry (entry &optional inner-p)
"Create candidates from imenu ENTRY.
Return a list of entries when entry is a `imenu--subalist-p' or a
list of one entry otherwise."
(let ((ecdr (cdr entry))
(prep-fun imenu-anywhere-preprocess-entry-function))
(cond ((imenu--subalist-p entry)
(mapcar (lambda (sub-entry)
(funcall prep-fun sub-entry (car entry)))
(cl-mapcan (lambda (el) (imenu-anywhere--candidates-from-entry el t))
(cdr entry))))
((integerp ecdr)
(when (> ecdr 0) ;; drop (*Rescan* . -99)
(let ((entry (cons (car entry) (copy-marker ecdr))))
(list (if inner-p entry (funcall prep-fun entry nil))))))
((and (listp ecdr) (eq (car ecdr) 'IGNORE)) nil)
(t (list (if inner-p entry (funcall prep-fun entry nil)))))))
(defun imenu-anywhere-preprocess-for-completion (entry parent-name)
"Default function for `imenu-anywhere-preprocess-entry-function'.
Concatenate imenu ENTRY and PARENT-NAME in a meaningful way. This
pre-processing is suitable for minibuffer completion mechanisms
such as `completing-read' or `ido-completing-read'."
(when entry
(let* ((entry-name (replace-regexp-in-string "\\c-*$" "" (car entry)))
;; in python hierarchical entry is defined as ("foo"
;; (*function-definition* ...) (sub-name ..)) where "foo" is the
;; ENTRY-NAME from above and *function-definition* is PREFIX. In this
;; case we need to reverse the position. We detect such entries by
;; assuming that they are enclosed in *..* and hope for the best.
(reverse (string-match-p "^\\*.*\\*$" entry-name))
(sep (and parent-name imenu-anywhere-delimiter)))
(setcar entry (if reverse
(concat parent-name sep entry-name)
(concat entry-name sep parent-name)))
entry)))
(defun imenu-anywhere-preprocess-for-listing (entry entry-name)
"Pre-processor of imenu ENTRY suitable for hierarchical listings.
ENTRY-NAME is commonly a class or type of the object. Helm and
IVY backends use this pre-processing strategy."
(when entry
(let ((bname (if (markerp (cdr entry))
(concat (buffer-name (marker-buffer (cdr entry))) ": ")
"")))
(setcar entry (concat bname
entry-name
(and entry-name
imenu-anywhere-delimiter)
(car entry))))
entry))
(defun imenu-anywhere--guess-default (index-alist str-at-pt)
"Guess a default choice from the given imenu list and string at point."
(let ((name (regexp-quote str-at-pt)))
(catch 'found
(dolist (regex (list (concat "\\`" name "\\'")
(concat "\\`" name)
(concat name "\\'")
name))
(dolist (item index-alist)
(if (string-match regex (car item))
(throw 'found (car item))))))))
(defun imenu-anywhere-goto (name position &optional rest)
"Function used as `imenu-default-goto-function'."
(let* ((is-overlay (overlayp position))
(buff (or (and is-overlay (overlay-buffer position))
(marker-buffer position)))
(position (or (and is-overlay (overlay-start position))
(marker-position position))))
(switch-to-buffer buff)
(when (or (< position (point-min))
(> position (point-max)))
(widen))
(goto-char position)))
;;;###autoload
(defun imenu-anywhere ()
"Go to imenu tag defined in all reachable buffers.
Reachable buffers are determined by applying functions in
`imenu-anywhere-buffer-filter-functions' to all buffers returned
by `imenu-anywhere-buffer-list-function'.
Sorting is done within each buffer and takes into account items'
length. Thus more recent buffers in `buffer-list' and shorter
entries have higher priority."
(interactive)
(let ((imenu-default-goto-function 'imenu-anywhere-goto)
(index-alist (imenu-anywhere-candidates)))
(if (null index-alist)
(message "No imenu tags")
(let ((selection
(let* ((str-at-pt (thing-at-point 'symbol))
(default (and str-at-pt
(imenu-anywhere--guess-default index-alist str-at-pt)))
(names (mapcar 'car index-alist))
(name (completing-read "Imenu: " names nil t nil nil default)))
(assoc name index-alist))))
(imenu selection)))))
;;; IDO
;;;###autoload
(defun ido-imenu-anywhere ()
"IDO interface for `imenu-anywhere'.
This is a simple wrapper around `imenu-anywhere' which uses
`ido-completing-read' as `completing-read-function'. If you use
`ido-ubiquitous' you might be better off by using `ido-anywhere'
instead, but there should be little or no difference."
(interactive)
(require 'ido)
(let ((imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-completion)
(completing-read-function 'ido-completing-read))
(imenu-anywhere)))
;;; IVY
;;;###autoload
(defun ivy-imenu-anywhere ()
"IVY interface for `imenu-anywhere'
This is a simple wrapper around `imenu-anywhere' which uses
`ivy-completing-read' as `completing-read-function'."
(interactive)
(unless (require 'ivy nil t)
(error "[imenu-anywhere]: This command requires 'ivy' package"))
(let ((ivy-sort-functions-alist)
(imenu-anywhere-preprocess-entry-function #'imenu-anywhere-preprocess-for-listing)
(completing-read-function 'ivy-completing-read))
(imenu-anywhere)))
;;; HELM
;; silence byte-compiler
(defvar helm-sources-using-default-as-input)
(defvar helm-imenu-fuzzy-match)
(defvar helm-current-buffer)
(declare-function helm "helm")
(declare-function helm-highlight-current-line "helm-utils")
(declare-function helm-make-source "helm-source")
(eval-after-load "helm"
'(progn
(require 'helm-imenu)
(defvar helm-source-imenu-anywhere
(helm-make-source "imenu-anywere" 'helm-source-sync
:candidates #'helm-imenu-anywhere-candidates
:persistent-action (lambda (elm)
(imenu-anywhere-goto "" elm)
(unless (fboundp 'semantic-imenu-tag-overlay)
(helm-highlight-current-line)))
:fuzzy-match helm-imenu-fuzzy-match
:persistent-help "Show this entry"
:action (lambda (elm) (imenu-anywhere-goto "" elm)))
"Helm source for `imenu-anywhere' (which see).")
(add-to-list 'helm-sources-using-default-as-input 'helm-source-imenu-anywhere)))
(defun helm-imenu-anywhere-candidates ()
;; don't use macro with-helm-current-buffer
(with-current-buffer (or (and (buffer-live-p helm-current-buffer) helm-current-buffer)
(setq helm-current-buffer (current-buffer)))
(let ((imenu-anywhere-preprocess-entry-function
'imenu-anywhere-preprocess-for-listing))
(imenu-anywhere-candidates))))
;;;###autoload
(defun helm-imenu-anywhere ()
"`helm' interface for `imenu-anywhere'.
Sorting is in increasing length of imenu symbols within each
buffer. The pyramidal view allows distinguishing different
buffers."
(interactive)
(unless (require 'helm nil t)
(error "[imenu-anywhere]: This command requires 'helm' package"))
(let ((imenu-default-goto-function 'imenu-anywhere-goto))
(helm :sources 'helm-source-imenu-anywhere
:default (thing-at-point 'symbol)
:buffer "*helm imenu-anywhere*")))
(provide 'imenu-anywhere)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; imenu-anywhere.el ends here
|
[
{
"context": "s File for Spacemacs\n;;\n;; Copyright (c) 2012-2014 Sylvain Benner\n;; Copyright (c) 2015 Ben Hayden\n;;\n;; Author: Be",
"end": 105,
"score": 0.9998878240585327,
"start": 91,
"tag": "NAME",
"value": "Sylvain Benner"
},
{
"context": "(c) 2012-2014 Sylvain Benner\n;; Copyright (c) 2015 Ben Hayden\n;;\n;; Author: Ben Hayden <hayden767@gmail.com>\n;;",
"end": 138,
"score": 0.999875009059906,
"start": 128,
"tag": "NAME",
"value": "Ben Hayden"
},
{
"context": "ner\n;; Copyright (c) 2015 Ben Hayden\n;;\n;; Author: Ben Hayden <hayden767@gmail.com>\n;; URL: https://github.com/",
"end": 163,
"score": 0.9998846650123596,
"start": 153,
"tag": "NAME",
"value": "Ben Hayden"
},
{
"context": "ght (c) 2015 Ben Hayden\n;;\n;; Author: Ben Hayden <hayden767@gmail.com>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;",
"end": 184,
"score": 0.999932587146759,
"start": 165,
"tag": "EMAIL",
"value": "hayden767@gmail.com"
},
{
"context": " <hayden767@gmail.com>\n;; URL: https://github.com/syl20bnr/spacemacs\n;; Salt mode URL: https://github.com/be",
"end": 221,
"score": 0.9877048134803772,
"start": 213,
"tag": "USERNAME",
"value": "syl20bnr"
},
{
"context": "nr/spacemacs\n;; Salt mode URL: https://github.com/beardedprojamz/salt-mode\n;;\n;; This file is not part of GNU Emac",
"end": 283,
"score": 0.9671410322189331,
"start": 269,
"tag": "USERNAME",
"value": "beardedprojamz"
}
] | layers/+config-files/salt/packages.el | chwin/.emacs.d | 1 | ;;; packages.el --- Salt Layer extensions File for Spacemacs
;;
;; Copyright (c) 2012-2014 Sylvain Benner
;; Copyright (c) 2015 Ben Hayden
;;
;; Author: Ben Hayden <hayden767@gmail.com>
;; URL: https://github.com/syl20bnr/spacemacs
;; Salt mode URL: https://github.com/beardedprojamz/salt-mode
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq salt-packages '(salt-mode
smartparens))
(defun salt/init-salt-mode ()
(use-package salt-mode
:defer t
:config (evil-leader/set-key-for-mode 'salt-mode "mpb" 'mmm-parse-buffer)))
(defun salt/pre-init-smartparens ()
(add-hook 'salt-mode-hook 'smartparens-mode)
(spacemacs|use-package-add-hook smartparens
:post-config
(progn
(sp-local-pair 'salt-mode "{{" " }}")
(sp-local-pair 'salt-mode "{%" " %}")
(sp-local-pair 'salt-mode "{#" " #}"))))
| 42996 | ;;; packages.el --- Salt Layer extensions File for Spacemacs
;;
;; Copyright (c) 2012-2014 <NAME>
;; Copyright (c) 2015 <NAME>
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/syl20bnr/spacemacs
;; Salt mode URL: https://github.com/beardedprojamz/salt-mode
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq salt-packages '(salt-mode
smartparens))
(defun salt/init-salt-mode ()
(use-package salt-mode
:defer t
:config (evil-leader/set-key-for-mode 'salt-mode "mpb" 'mmm-parse-buffer)))
(defun salt/pre-init-smartparens ()
(add-hook 'salt-mode-hook 'smartparens-mode)
(spacemacs|use-package-add-hook smartparens
:post-config
(progn
(sp-local-pair 'salt-mode "{{" " }}")
(sp-local-pair 'salt-mode "{%" " %}")
(sp-local-pair 'salt-mode "{#" " #}"))))
| true | ;;; packages.el --- Salt Layer extensions File for Spacemacs
;;
;; Copyright (c) 2012-2014 PI:NAME:<NAME>END_PI
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/syl20bnr/spacemacs
;; Salt mode URL: https://github.com/beardedprojamz/salt-mode
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq salt-packages '(salt-mode
smartparens))
(defun salt/init-salt-mode ()
(use-package salt-mode
:defer t
:config (evil-leader/set-key-for-mode 'salt-mode "mpb" 'mmm-parse-buffer)))
(defun salt/pre-init-smartparens ()
(add-hook 'salt-mode-hook 'smartparens-mode)
(spacemacs|use-package-add-hook smartparens
:post-config
(progn
(sp-local-pair 'salt-mode "{{" " }}")
(sp-local-pair 'salt-mode "{%" " %}")
(sp-local-pair 'salt-mode "{#" " #}"))))
|
[
{
"context": "ht the selected buffer\n\n;; Copyright (C) 2017-2020 Neil Okamoto\n\n;; Filename: dimmer.el\n;; Author: Neil Okamoto\n;",
"end": 97,
"score": 0.9998785257339478,
"start": 85,
"tag": "NAME",
"value": "Neil Okamoto"
},
{
"context": "20 Neil Okamoto\n\n;; Filename: dimmer.el\n;; Author: Neil Okamoto\n;; Version: 0.4.2\n;; Package-Version: 20200329.35",
"end": 145,
"score": 0.9998828768730164,
"start": 133,
"tag": "NAME",
"value": "Neil Okamoto"
},
{
"context": "ires: ((emacs \"25.1\"))\n;; URL: https://github.com/gonewest818/dimmer.el\n;; Keywords: faces, editing\n;;\n;; This ",
"end": 272,
"score": 0.9991645216941833,
"start": 261,
"tag": "USERNAME",
"value": "gonewest818"
},
{
"context": "link '(url-link :tag \"GitHub\" \"https://github.com/gonewest818/dimmer.el\"))\n\n(define-obsolete-variable-alias 'di",
"end": 4947,
"score": 0.9994010329246521,
"start": 4936,
"tag": "USERNAME",
"value": "gonewest818"
}
] | .emacs.d/elpa-27.0/dimmer-20200329.35/dimmer.el | ikidder/configs | 0 | ;;; dimmer.el --- Visually highlight the selected buffer
;; Copyright (C) 2017-2020 Neil Okamoto
;; Filename: dimmer.el
;; Author: Neil Okamoto
;; Version: 0.4.2
;; Package-Version: 20200329.35
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/gonewest818/dimmer.el
;; Keywords: faces, editing
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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 3 of the
;; License, 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; This module provides a minor mode that indicates which buffer is
;; currently active by dimming the faces in the other buffers. It
;; does this nondestructively, and computes the dimmed faces
;; dynamically such that your overall color scheme is shown in a muted
;; form without requiring you to define what is a "dim" version of
;; every face.
;;
;; `dimmer.el' can be configured to adjust foreground colors (default),
;; background colors, or both.
;;
;; Usage:
;;
;; (require 'dimmer)
;; (dimmer-configure-which-key)
;; (dimmer-configure-helm)
;; (dimmer-mode t)
;;
;; Configuration:
;;
;; By default dimmer excludes the minibuffer and echo areas from
;; consideration, so that most packages that use the minibuffer for
;; interaction will behave as users expect.
;;
;; `dimmer-configure-company-box' is a convenience function for users
;; of company-box. It prevents dimming the buffer you are editing when
;; a company-box popup is displayed.
;;
;; `dimmer-configure-helm' is a convenience function for helm users to
;; ensure helm buffers are not dimmed.
;;
;; `dimmer-configure-gnus' is a convenience function for gnus users to
;; ensure article buffers are not dimmed.
;;
;; `dimmer-configure-hydra' is a convenience function for hydra users to
;; ensure "*LV*" buffers are not dimmed.
;;
;; `dimmer-configure-magit' is a convenience function for magit users to
;; ensure transients are not dimmed.
;;
;; `dimmer-configure-org' is a convenience function for org users to
;; ensure org-mode buffers are not dimmed.
;;
;; `dimmer-configure-posframe' is a convenience function for posframe
;; users to ensure posframe buffers are not dimmed.
;;
;; `dimmer-configure-which-key' is a convenience function for which-key
;; users to ensure which-key popups are not dimmed.
;;
;; Please submit pull requests with configurations for other packages!
;;
;; Customization:
;;
;; `dimmer-adjustment-mode' controls what aspect of the color scheme is adjusted
;; when dimming. Choices are :foreground (default), :background, or :both.
;;
;; `dimmer-fraction' controls the degree to which buffers are dimmed.
;; Range is 0.0 - 1.0, and default is 0.20. Increase value if you
;; like the other buffers to be more dim.
;;
;; `dimmer-buffer-exclusion-regexps' can be used to specify buffers that
;; should never be dimmed. If the buffer name matches any regexp in
;; this list then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-buffer-exclusion-predicates' can be used to specify buffers that
;; should never be dimmed. If any predicate function in this list
;; returns true for the buffer then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-prevent-dimming-predicates' can be used to prevent dimmer from
;; altering the dimmed buffer list. This can be used to detect cases
;; where a package pops up a window temporarily, and we don't want the
;; dimming to change. If any function in this list returns a non-nil
;; value, dimming state will not be changed.
;;
;; `dimmer-watch-frame-focus-events' controls whether dimmer will dim all
;; buffers when Emacs no longer has focus in the windowing system. This
;; is enabled by default. Some users may prefer to set this to nil, and
;; have the dimmed / not dimmed buffers stay as-is even when Emacs
;; doesn't have focus.
;;
;; `dimmer-use-colorspace' allows you to specify what color space the
;; dimming calculation is performed in. In the majority of cases you
;; won't need to touch this setting. See the docstring below for more
;; information.
;;
;;; Code:
(require 'cl-lib)
(require 'color)
(require 'face-remap)
(require 'seq)
(require 'subr-x)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; customization
(defgroup dimmer nil
"Highlight the current buffer by dimming the colors on the others."
:prefix "dimmer-"
:group 'convenience
:link '(url-link :tag "GitHub" "https://github.com/gonewest818/dimmer.el"))
(define-obsolete-variable-alias 'dimmer-percent 'dimmer-fraction)
(defcustom dimmer-fraction 0.20
"Control the degree to which buffers are dimmed (0.0 - 1.0)."
:type '(float)
:group 'dimmer)
(defcustom dimmer-adjustment-mode :foreground
"Control what aspect of the color scheme is adjusted when dimming.
Choices are :foreground (default), :background, or :both."
:type '(radio (const :tag "Foreground colors are dimmed" :foreground)
(const :tag "Background colors are dimmed" :background)
(const :tag "Foreground and background are dimmed" :both))
:group 'dimmer)
(make-obsolete-variable
'dimmer-exclusion-regexp
"`dimmer-exclusion-regexp` is obsolete and has no effect in this session.
The variable has been superseded by `dimmer-buffer-exclusion-regexps`.
See documentation for details."
"v0.4.0")
(define-obsolete-variable-alias
'dimmer-exclusion-regexp-list 'dimmer-buffer-exclusion-regexps)
(defcustom dimmer-buffer-exclusion-regexps '("^ \\*Minibuf-[0-9]+\\*$"
"^ \\*Echo.*\\*$")
"List of regular expressions describing buffer names that are never dimmed."
:type '(repeat (choice regexp))
:group 'dimmer)
(defcustom dimmer-buffer-exclusion-predicates '()
"List of predicate functions indicating buffers that are never dimmed.
Functions in the list are called while visiting each available
buffer. If the predicate function returns a truthy value, then
the buffer is not dimmed."
:type '(repeat (choice function))
:group 'dimmer)
(define-obsolete-variable-alias
'dimmer-exclusion-predicates 'dimmer-prevent-dimming-predicates)
(defcustom dimmer-prevent-dimming-predicates '(window-minibuffer-p)
"List of functions which prevent dimmer from altering dimmed buffer set.
Functions in this list are called in turn with no arguments. If any function
returns a non-nil value, no buffers will be added to or removed from the set
of dimmed buffers."
:type '(repeat (choice function))
:group 'dimmer)
(defcustom dimmer-watch-frame-focus-events t
"Should windows be dimmed when all Emacs frame(s) lose focus?
Restart Emacs after changing this configuration."
:type '(boolean)
:group 'dimmer)
(defcustom dimmer-use-colorspace :cielab
"Colorspace in which dimming calculations are performed.
Choices are :cielab (default), :hsl, or :rgb.
CIELAB is the default, and in most cases should serve perfectly
well. As a colorspace it attempts to be uniform to the human
eye, meaning the degree of dimming should be roughly the same for
all your foreground colors.
Bottom line: If CIELAB is working for you, then you don't need to
experiment with the other choices.
However, interpolating in CIELAB introduces one wrinkle, in that
mathematically it's possible to generate a color that isn't
representable on your RGB display (colors having one or more RGB
channel values < 0.0 or > 1.0). When dimmer finds an
\"impossible\" RGB value like that it simply clamps that value to
fit in the range 0.0 - 1.0. Clamping like this can lead to some
colors looking \"wrong\". If you think the dimmed values look
wrong, then try HSL or RGB instead."
:type '(radio (const :tag "Interpolate in CIELAB 1976" :cielab)
(const :tag "Interpolate in HSL" :hsl)
(const :tag "Interpolate in RGB" :rgb))
:group 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; configuration
;;;###autoload
(defun dimmer-configure-company-box ()
"Convenience setting for company-box users.
This predicate prevents dimming the buffer you are editing when
company-box pops up a list of completion."
(add-to-list
'dimmer-prevent-dimming-predicates
(lambda () (string-prefix-p " *company-box-" (buffer-name)))))
;;;###autoload
(defun dimmer-configure-helm ()
"Convenience settings for helm users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^\\*[h|H]elm.*\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'helm--alive-p)))
;;;###autoload
(defun dimmer-configure-gnus ()
"Convenience settings for gnus users."
(add-to-list
'dimmer-exclusion-regexp-list "^\\*Article .*\\*$"))
;;;###autoload
(defun dimmer-configure-hydra ()
"Convenience settings for hydra users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*LV\\*$"))
;;;###autoload
(defun dimmer-configure-magit ()
"Convenience settings for magit users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*transient\\*$"))
;;;###autoload
(defun dimmer-configure-org ()
"Convenience settings for org users."
(add-to-list 'dimmer-exclusion-regexp-list "^\\*Org Select\\*$")
(add-to-list 'dimmer-exclusion-regexp-list "^ \\*Agenda Commands\\*$"))
;;;###autoload
(defun dimmer-configure-posframe ()
"Convenience settings for packages depending on posframe.
Note, packages that use posframe aren't required to be consistent
about how they name their buffers, but many of them tend to
include the words \"posframe\" and \"buffer\" in the buffer's
name. Examples include:
- \" *ivy-posframe-buffer*\"
- \" *company-posframe-buffer*\"
- \" *flycheck-posframe-buffer*\"
- \" *ddskk-posframe-buffer*\"
If this setting doesn't work for you, you still have the option
of adding another regular expression to catch more things, or
in some cases you can customize the other package and ensure it
uses a buffer name that fits this pattern."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*.*posframe.*buffer.*\\*$"))
;;;###autoload
(defun dimmer-configure-which-key ()
"Convenience settings for which-key-users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*which-key\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'which-key--popup-showing-p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; implementation
(defvar dimmer-last-buffer nil
"Identity of the last buffer to be made current.")
(defvar dimmer-debug-messages 0
"Control debugging output to *Messages* buffer.
Set 0 to disable all output, 1 for basic output, or a larger
integer for more verbosity.")
(defvar-local dimmer-buffer-face-remaps nil
"Per-buffer face remappings needed for later clean up.")
;; don't allow major mode change to kill the local variable
(put 'dimmer-buffer-face-remaps 'permanent-local t)
(defconst dimmer-dimmed-faces (make-hash-table :test 'equal)
"Cache of face names with their computed dimmed values.")
(defun dimmer-lerp (frac c0 c1)
"Use FRAC to compute a linear interpolation of C0 and C1."
(+ (* c0 (- 1.0 frac))
(* c1 frac)))
(defun dimmer-lerp-in-rgb (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in RGB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar (apply-partially 'dimmer-lerp frac) c0 c1)))
(defun dimmer-lerp-in-hsl (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in HSL space.
FRAC controls the interpolation."
;; Implementation note: We must handle this case carefully to ensure the
;; hue is interpolated over the "shortest" arc around the color wheel.
(apply 'color-rgb-to-hex
(apply 'color-hsl-to-rgb
(cl-destructuring-bind (h0 s0 l0)
(apply 'color-rgb-to-hsl c0)
(cl-destructuring-bind (h1 s1 l1)
(apply 'color-rgb-to-hsl c1)
(if (> (abs (- h1 h0)) 0.5)
;; shortest arc "wraps around"
(list (mod (dimmer-lerp (- 1.0 frac) h1 (+ 1.0 h0)) 1.0)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))
;; shortest arc is the natural one
(list (dimmer-lerp frac h0 h1)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))))))))
(defun dimmer-lerp-in-cielab (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in CIELAB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar 'color-clamp
(apply 'color-lab-to-srgb
(cl-mapcar (apply-partially 'dimmer-lerp frac)
(apply 'color-srgb-to-lab c0)
(apply 'color-srgb-to-lab c1))))))
(defun dimmer-compute-rgb (c0 c1 frac colorspace)
"Compute a \"dimmed\" color via linear interpolation.
Blends the two colors, C0 and C1, using FRAC to control the
interpolation. When FRAC is 0.0, the result is equal to C0. When
FRAC is 1.0, the result is equal to C1.
Any other value for FRAC means the result's hue, saturation, and
value will be adjusted linearly so that the color sits somewhere
between C0 and C1.
The interpolation is performed in a COLORSPACE which is specified
with a symbol, :rgb, :hsl, or :cielab."
(pcase colorspace
(:rgb (dimmer-lerp-in-rgb c0 c1 frac))
(:hsl (dimmer-lerp-in-hsl c0 c1 frac))
(:cielab (dimmer-lerp-in-cielab c0 c1 frac))
(_ (dimmer-lerp-in-cielab c0 c1 frac))))
(defun dimmer-cached-compute-rgb (c0 c1 frac colorspace)
"Lookup a \"dimmed\" color value from cache, else compute a value.
This is essentially a memoization of `dimmer-compute-rgb` via a hash
using the arguments C0, C1, FRAC, and COLORSPACE as the key."
(let ((key (format "%s-%s-%f-%s" c0 c1 frac dimmer-use-colorspace)))
(or (gethash key dimmer-dimmed-faces)
(let ((rgb (dimmer-compute-rgb (color-name-to-rgb c0)
(color-name-to-rgb c1)
frac
dimmer-use-colorspace)))
(when rgb
(puthash key rgb dimmer-dimmed-faces)
rgb)))))
(defun dimmer-face-color (f frac)
"Compute a dimmed version of the foreground color of face F.
If `dimmer-adjust-background-color` is true, adjust the
background color as well. FRAC is the amount of dimming where
0.0 is no change and 1.0 is maximum change. Returns a plist
containing the new foreground (and if needed, new background)
suitable for use with `face-remap-add-relative`."
(let ((fg (face-foreground f))
(bg (face-background f))
(def-fg (face-foreground 'default))
(def-bg (face-background 'default))
;; when mode is :both, the perceptual effect is "doubled"
(my-frac (if (eq dimmer-adjustment-mode :both)
(/ frac 2.0)
frac))
(result '()))
;; We shift the desired components of F by FRAC amount toward the `default`
;; color, thereby dimming or desaturating the overall appearance:
;; * When the `dimmer-adjustment-mode` is `:foreground` we move the
;; foreground component toward the `default` background.
;; * When the `dimmer-adjustment-mode` is :background we mofe the
;; background component of F toward the `default` foreground.`
(when (and (or (eq dimmer-adjustment-mode :foreground)
(eq dimmer-adjustment-mode :both))
fg (color-defined-p fg)
def-bg (color-defined-p def-bg))
(setq result
(plist-put result :foreground
(dimmer-cached-compute-rgb fg
def-bg
my-frac
dimmer-use-colorspace))))
(when (and (or (eq dimmer-adjustment-mode :background)
(eq dimmer-adjustment-mode :both))
bg (color-defined-p bg)
def-fg (color-defined-p def-fg))
(setq result
(plist-put result :background
(dimmer-cached-compute-rgb bg
def-fg
my-frac
dimmer-use-colorspace))))
result))
(defun dimmer-filtered-face-list ()
"Return a filtered version of `face-list`.
Filtering is needed to exclude faces that shouldn't be dimmed."
;; `fringe` is problematic because it is shared for all windows,
;; so for now we just leave it alone.
(remove 'fringe (face-list)))
(defun dimmer-dim-buffer (buf frac)
"Dim all the faces defined in the buffer BUF.
FRAC controls the dimming as defined in ‘dimmer-face-color’."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-dim-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(unless dimmer-buffer-face-remaps
(dolist (f (dimmer-filtered-face-list))
(let ((c (dimmer-face-color f frac)))
(when c ; e.g. "(when-let* ((c (...)))" in Emacs 26
(push (face-remap-add-relative f c) dimmer-buffer-face-remaps)))))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-dim-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-restore-buffer (buf)
"Restore the un-dimmed faces in the buffer BUF."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-restore-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(when dimmer-buffer-face-remaps
(mapc 'face-remap-remove-relative dimmer-buffer-face-remaps)
(setq dimmer-buffer-face-remaps nil))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-restore-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-filtered-buffer-list ()
"Get filtered subset of all visible buffers in all frames."
(let (buffers)
(walk-windows
(lambda (win)
(let* ((buf (window-buffer win))
(name (buffer-name buf)))
(unless (or (member buf buffers)
(cl-some (lambda (rxp) (string-match-p rxp name))
dimmer-buffer-exclusion-regexps)
(cl-some (lambda (f) (funcall f buf))
dimmer-buffer-exclusion-predicates))
(push buf buffers))))
nil
t)
(dimmer--dbg 3 "dimmer-filtered-buffer-list: %s" buffers)
buffers))
(defun dimmer-process-all (&optional force)
"Process all buffers and dim or un-dim each.
When FORCE is true some special logic applies. Namely, we must
process all buffers regardless of the various dimming predicates.
While performing this scan, any buffer that would have been
excluded due to the predicates before should be un-dimmed now."
(dimmer--dbg-buffers 1 "dimmer-process-all")
(let ((selected (current-buffer))
(ignore (cl-some (lambda (f) (and (fboundp f) (funcall f)))
dimmer-prevent-dimming-predicates))
(filtbufs (dimmer-filtered-buffer-list)))
(dimmer--dbg 1 "dimmer-process-all: force %s" force)
(setq dimmer-last-buffer selected)
(when (or force (not ignore))
(dolist (buf (if force (buffer-list) filtbufs))
(dimmer--dbg 2 "dimmer-process-all: buf %s" buf)
(if (or (eq buf selected)
(and force (not (memq buf filtbufs))))
(dimmer-restore-buffer buf)
(dimmer-dim-buffer buf dimmer-fraction))))))
(defun dimmer-dim-all ()
"Dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-dim-all")
(mapc (lambda (buf)
(dimmer-dim-buffer buf dimmer-fraction))
(buffer-list)))
(defun dimmer-restore-all ()
"Un-dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-restore-all")
(mapc 'dimmer-restore-buffer (buffer-list)))
(defun dimmer-command-handler ()
"Process all buffers if current buffer has changed."
(dimmer--dbg-buffers 1 "dimmer-command-handler")
(unless (eq (window-buffer) dimmer-last-buffer)
(dimmer-process-all)))
(defun dimmer-config-change-handler ()
"Process all buffers if window configuration has changed."
(dimmer--dbg-buffers 1 "dimmer-config-change-handler")
(dimmer-process-all t))
(defun dimmer-after-focus-change-handler ()
"Handle cases where a frame may have gained or last focus.
Walk the `frame-list` and check the state of each one. If none
of the frames has focus then dim them all. If any frame has
focus then dim the others. Used in Emacs >= 27.0 only."
(dimmer--dbg-buffers 1 "dimmer-after-focus-change-handler")
(let ((focus-out t))
(with-no-warnings
(dolist (f (frame-list) focus-out)
(setq focus-out (and focus-out (not (frame-focus-state f))))))
(if focus-out
(dimmer-dim-all)
(dimmer-process-all t))))
(defun dimmer-manage-frame-focus-hooks (install)
"Manage the frame focus in/out hooks for dimmer.
When INSTALL is t, install the appropriate hooks to catch focus
events. Otherwise remove the hooks. This function has no effect
when `dimmer-watch-frame-focus-events` is nil."
(when dimmer-watch-frame-focus-events
(if (boundp 'after-focus-change-function)
;; emacs-version >= 27.0
(if install
(add-function :before
after-focus-change-function
#'dimmer-after-focus-change-handler)
(remove-function after-focus-change-function
#'dimmer-after-focus-change-handler))
;; else emacs-version < 27.0
(if install
(with-no-warnings
(add-hook 'focus-in-hook #'dimmer-config-change-handler)
(add-hook 'focus-out-hook #'dimmer-dim-all))
(with-no-warnings
(remove-hook 'focus-in-hook #'dimmer-config-change-handler)
(remove-hook 'focus-out-hook #'dimmer-dim-all))))))
;;;###autoload
(define-minor-mode dimmer-mode
"visually highlight the selected buffer"
nil
:lighter ""
:global t
:require 'dimmer
(if dimmer-mode
(progn
(dimmer-manage-frame-focus-hooks t)
(add-hook 'post-command-hook #'dimmer-command-handler)
(add-hook 'window-configuration-change-hook
#'dimmer-config-change-handler))
(dimmer-manage-frame-focus-hooks nil)
(remove-hook 'post-command-hook #'dimmer-command-handler)
(remove-hook 'window-configuration-change-hook
#'dimmer-config-change-handler)
(dimmer-restore-all)))
;;;###autoload
(define-obsolete-function-alias 'dimmer-activate 'dimmer-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; debugging - call from *scratch*, ielm, or eshell
(defun dimmer--debug-face-remapping-alist (name &optional clear)
"Display 'face-remapping-alist' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq face-remapping-alist nil)
face-remapping-alist)))
(defun dimmer--debug-buffer-face-remaps (name &optional clear)
"Display 'dimmer-buffer-face-remaps' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq dimmer-buffer-face-remaps nil)
dimmer-buffer-face-remaps)))
(defun dimmer--debug-reset (name)
"Clear 'face-remapping-alist' and 'dimmer-buffer-face-remaps' for NAME."
(dimmer--debug-face-remapping-alist name t)
(dimmer--debug-buffer-face-remaps name t)
(redraw-display))
(defun dimmer--dbg (v fmt &rest args)
"Print debug message at verbosity V, filling format string FMT with ARGS."
(when (>= dimmer-debug-messages v)
(apply #'message fmt args)))
(defun dimmer--dbg-buffers (v label)
"Print debug buffer state at verbosity V and the given LABEL."
(when (>= dimmer-debug-messages v)
(let ((inhibit-message t)
(cb (current-buffer))
(wb (window-buffer)))
(message "%s: cb '%s' <== lb '%s' %s" label cb dimmer-last-buffer
(if (not (eq cb wb))
(format "wb '%s' **" wb)
"")))))
(provide 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; dimmer.el ends here
| 39878 | ;;; dimmer.el --- Visually highlight the selected buffer
;; Copyright (C) 2017-2020 <NAME>
;; Filename: dimmer.el
;; Author: <NAME>
;; Version: 0.4.2
;; Package-Version: 20200329.35
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/gonewest818/dimmer.el
;; Keywords: faces, editing
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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 3 of the
;; License, 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; This module provides a minor mode that indicates which buffer is
;; currently active by dimming the faces in the other buffers. It
;; does this nondestructively, and computes the dimmed faces
;; dynamically such that your overall color scheme is shown in a muted
;; form without requiring you to define what is a "dim" version of
;; every face.
;;
;; `dimmer.el' can be configured to adjust foreground colors (default),
;; background colors, or both.
;;
;; Usage:
;;
;; (require 'dimmer)
;; (dimmer-configure-which-key)
;; (dimmer-configure-helm)
;; (dimmer-mode t)
;;
;; Configuration:
;;
;; By default dimmer excludes the minibuffer and echo areas from
;; consideration, so that most packages that use the minibuffer for
;; interaction will behave as users expect.
;;
;; `dimmer-configure-company-box' is a convenience function for users
;; of company-box. It prevents dimming the buffer you are editing when
;; a company-box popup is displayed.
;;
;; `dimmer-configure-helm' is a convenience function for helm users to
;; ensure helm buffers are not dimmed.
;;
;; `dimmer-configure-gnus' is a convenience function for gnus users to
;; ensure article buffers are not dimmed.
;;
;; `dimmer-configure-hydra' is a convenience function for hydra users to
;; ensure "*LV*" buffers are not dimmed.
;;
;; `dimmer-configure-magit' is a convenience function for magit users to
;; ensure transients are not dimmed.
;;
;; `dimmer-configure-org' is a convenience function for org users to
;; ensure org-mode buffers are not dimmed.
;;
;; `dimmer-configure-posframe' is a convenience function for posframe
;; users to ensure posframe buffers are not dimmed.
;;
;; `dimmer-configure-which-key' is a convenience function for which-key
;; users to ensure which-key popups are not dimmed.
;;
;; Please submit pull requests with configurations for other packages!
;;
;; Customization:
;;
;; `dimmer-adjustment-mode' controls what aspect of the color scheme is adjusted
;; when dimming. Choices are :foreground (default), :background, or :both.
;;
;; `dimmer-fraction' controls the degree to which buffers are dimmed.
;; Range is 0.0 - 1.0, and default is 0.20. Increase value if you
;; like the other buffers to be more dim.
;;
;; `dimmer-buffer-exclusion-regexps' can be used to specify buffers that
;; should never be dimmed. If the buffer name matches any regexp in
;; this list then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-buffer-exclusion-predicates' can be used to specify buffers that
;; should never be dimmed. If any predicate function in this list
;; returns true for the buffer then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-prevent-dimming-predicates' can be used to prevent dimmer from
;; altering the dimmed buffer list. This can be used to detect cases
;; where a package pops up a window temporarily, and we don't want the
;; dimming to change. If any function in this list returns a non-nil
;; value, dimming state will not be changed.
;;
;; `dimmer-watch-frame-focus-events' controls whether dimmer will dim all
;; buffers when Emacs no longer has focus in the windowing system. This
;; is enabled by default. Some users may prefer to set this to nil, and
;; have the dimmed / not dimmed buffers stay as-is even when Emacs
;; doesn't have focus.
;;
;; `dimmer-use-colorspace' allows you to specify what color space the
;; dimming calculation is performed in. In the majority of cases you
;; won't need to touch this setting. See the docstring below for more
;; information.
;;
;;; Code:
(require 'cl-lib)
(require 'color)
(require 'face-remap)
(require 'seq)
(require 'subr-x)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; customization
(defgroup dimmer nil
"Highlight the current buffer by dimming the colors on the others."
:prefix "dimmer-"
:group 'convenience
:link '(url-link :tag "GitHub" "https://github.com/gonewest818/dimmer.el"))
(define-obsolete-variable-alias 'dimmer-percent 'dimmer-fraction)
(defcustom dimmer-fraction 0.20
"Control the degree to which buffers are dimmed (0.0 - 1.0)."
:type '(float)
:group 'dimmer)
(defcustom dimmer-adjustment-mode :foreground
"Control what aspect of the color scheme is adjusted when dimming.
Choices are :foreground (default), :background, or :both."
:type '(radio (const :tag "Foreground colors are dimmed" :foreground)
(const :tag "Background colors are dimmed" :background)
(const :tag "Foreground and background are dimmed" :both))
:group 'dimmer)
(make-obsolete-variable
'dimmer-exclusion-regexp
"`dimmer-exclusion-regexp` is obsolete and has no effect in this session.
The variable has been superseded by `dimmer-buffer-exclusion-regexps`.
See documentation for details."
"v0.4.0")
(define-obsolete-variable-alias
'dimmer-exclusion-regexp-list 'dimmer-buffer-exclusion-regexps)
(defcustom dimmer-buffer-exclusion-regexps '("^ \\*Minibuf-[0-9]+\\*$"
"^ \\*Echo.*\\*$")
"List of regular expressions describing buffer names that are never dimmed."
:type '(repeat (choice regexp))
:group 'dimmer)
(defcustom dimmer-buffer-exclusion-predicates '()
"List of predicate functions indicating buffers that are never dimmed.
Functions in the list are called while visiting each available
buffer. If the predicate function returns a truthy value, then
the buffer is not dimmed."
:type '(repeat (choice function))
:group 'dimmer)
(define-obsolete-variable-alias
'dimmer-exclusion-predicates 'dimmer-prevent-dimming-predicates)
(defcustom dimmer-prevent-dimming-predicates '(window-minibuffer-p)
"List of functions which prevent dimmer from altering dimmed buffer set.
Functions in this list are called in turn with no arguments. If any function
returns a non-nil value, no buffers will be added to or removed from the set
of dimmed buffers."
:type '(repeat (choice function))
:group 'dimmer)
(defcustom dimmer-watch-frame-focus-events t
"Should windows be dimmed when all Emacs frame(s) lose focus?
Restart Emacs after changing this configuration."
:type '(boolean)
:group 'dimmer)
(defcustom dimmer-use-colorspace :cielab
"Colorspace in which dimming calculations are performed.
Choices are :cielab (default), :hsl, or :rgb.
CIELAB is the default, and in most cases should serve perfectly
well. As a colorspace it attempts to be uniform to the human
eye, meaning the degree of dimming should be roughly the same for
all your foreground colors.
Bottom line: If CIELAB is working for you, then you don't need to
experiment with the other choices.
However, interpolating in CIELAB introduces one wrinkle, in that
mathematically it's possible to generate a color that isn't
representable on your RGB display (colors having one or more RGB
channel values < 0.0 or > 1.0). When dimmer finds an
\"impossible\" RGB value like that it simply clamps that value to
fit in the range 0.0 - 1.0. Clamping like this can lead to some
colors looking \"wrong\". If you think the dimmed values look
wrong, then try HSL or RGB instead."
:type '(radio (const :tag "Interpolate in CIELAB 1976" :cielab)
(const :tag "Interpolate in HSL" :hsl)
(const :tag "Interpolate in RGB" :rgb))
:group 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; configuration
;;;###autoload
(defun dimmer-configure-company-box ()
"Convenience setting for company-box users.
This predicate prevents dimming the buffer you are editing when
company-box pops up a list of completion."
(add-to-list
'dimmer-prevent-dimming-predicates
(lambda () (string-prefix-p " *company-box-" (buffer-name)))))
;;;###autoload
(defun dimmer-configure-helm ()
"Convenience settings for helm users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^\\*[h|H]elm.*\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'helm--alive-p)))
;;;###autoload
(defun dimmer-configure-gnus ()
"Convenience settings for gnus users."
(add-to-list
'dimmer-exclusion-regexp-list "^\\*Article .*\\*$"))
;;;###autoload
(defun dimmer-configure-hydra ()
"Convenience settings for hydra users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*LV\\*$"))
;;;###autoload
(defun dimmer-configure-magit ()
"Convenience settings for magit users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*transient\\*$"))
;;;###autoload
(defun dimmer-configure-org ()
"Convenience settings for org users."
(add-to-list 'dimmer-exclusion-regexp-list "^\\*Org Select\\*$")
(add-to-list 'dimmer-exclusion-regexp-list "^ \\*Agenda Commands\\*$"))
;;;###autoload
(defun dimmer-configure-posframe ()
"Convenience settings for packages depending on posframe.
Note, packages that use posframe aren't required to be consistent
about how they name their buffers, but many of them tend to
include the words \"posframe\" and \"buffer\" in the buffer's
name. Examples include:
- \" *ivy-posframe-buffer*\"
- \" *company-posframe-buffer*\"
- \" *flycheck-posframe-buffer*\"
- \" *ddskk-posframe-buffer*\"
If this setting doesn't work for you, you still have the option
of adding another regular expression to catch more things, or
in some cases you can customize the other package and ensure it
uses a buffer name that fits this pattern."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*.*posframe.*buffer.*\\*$"))
;;;###autoload
(defun dimmer-configure-which-key ()
"Convenience settings for which-key-users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*which-key\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'which-key--popup-showing-p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; implementation
(defvar dimmer-last-buffer nil
"Identity of the last buffer to be made current.")
(defvar dimmer-debug-messages 0
"Control debugging output to *Messages* buffer.
Set 0 to disable all output, 1 for basic output, or a larger
integer for more verbosity.")
(defvar-local dimmer-buffer-face-remaps nil
"Per-buffer face remappings needed for later clean up.")
;; don't allow major mode change to kill the local variable
(put 'dimmer-buffer-face-remaps 'permanent-local t)
(defconst dimmer-dimmed-faces (make-hash-table :test 'equal)
"Cache of face names with their computed dimmed values.")
(defun dimmer-lerp (frac c0 c1)
"Use FRAC to compute a linear interpolation of C0 and C1."
(+ (* c0 (- 1.0 frac))
(* c1 frac)))
(defun dimmer-lerp-in-rgb (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in RGB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar (apply-partially 'dimmer-lerp frac) c0 c1)))
(defun dimmer-lerp-in-hsl (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in HSL space.
FRAC controls the interpolation."
;; Implementation note: We must handle this case carefully to ensure the
;; hue is interpolated over the "shortest" arc around the color wheel.
(apply 'color-rgb-to-hex
(apply 'color-hsl-to-rgb
(cl-destructuring-bind (h0 s0 l0)
(apply 'color-rgb-to-hsl c0)
(cl-destructuring-bind (h1 s1 l1)
(apply 'color-rgb-to-hsl c1)
(if (> (abs (- h1 h0)) 0.5)
;; shortest arc "wraps around"
(list (mod (dimmer-lerp (- 1.0 frac) h1 (+ 1.0 h0)) 1.0)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))
;; shortest arc is the natural one
(list (dimmer-lerp frac h0 h1)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))))))))
(defun dimmer-lerp-in-cielab (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in CIELAB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar 'color-clamp
(apply 'color-lab-to-srgb
(cl-mapcar (apply-partially 'dimmer-lerp frac)
(apply 'color-srgb-to-lab c0)
(apply 'color-srgb-to-lab c1))))))
(defun dimmer-compute-rgb (c0 c1 frac colorspace)
"Compute a \"dimmed\" color via linear interpolation.
Blends the two colors, C0 and C1, using FRAC to control the
interpolation. When FRAC is 0.0, the result is equal to C0. When
FRAC is 1.0, the result is equal to C1.
Any other value for FRAC means the result's hue, saturation, and
value will be adjusted linearly so that the color sits somewhere
between C0 and C1.
The interpolation is performed in a COLORSPACE which is specified
with a symbol, :rgb, :hsl, or :cielab."
(pcase colorspace
(:rgb (dimmer-lerp-in-rgb c0 c1 frac))
(:hsl (dimmer-lerp-in-hsl c0 c1 frac))
(:cielab (dimmer-lerp-in-cielab c0 c1 frac))
(_ (dimmer-lerp-in-cielab c0 c1 frac))))
(defun dimmer-cached-compute-rgb (c0 c1 frac colorspace)
"Lookup a \"dimmed\" color value from cache, else compute a value.
This is essentially a memoization of `dimmer-compute-rgb` via a hash
using the arguments C0, C1, FRAC, and COLORSPACE as the key."
(let ((key (format "%s-%s-%f-%s" c0 c1 frac dimmer-use-colorspace)))
(or (gethash key dimmer-dimmed-faces)
(let ((rgb (dimmer-compute-rgb (color-name-to-rgb c0)
(color-name-to-rgb c1)
frac
dimmer-use-colorspace)))
(when rgb
(puthash key rgb dimmer-dimmed-faces)
rgb)))))
(defun dimmer-face-color (f frac)
"Compute a dimmed version of the foreground color of face F.
If `dimmer-adjust-background-color` is true, adjust the
background color as well. FRAC is the amount of dimming where
0.0 is no change and 1.0 is maximum change. Returns a plist
containing the new foreground (and if needed, new background)
suitable for use with `face-remap-add-relative`."
(let ((fg (face-foreground f))
(bg (face-background f))
(def-fg (face-foreground 'default))
(def-bg (face-background 'default))
;; when mode is :both, the perceptual effect is "doubled"
(my-frac (if (eq dimmer-adjustment-mode :both)
(/ frac 2.0)
frac))
(result '()))
;; We shift the desired components of F by FRAC amount toward the `default`
;; color, thereby dimming or desaturating the overall appearance:
;; * When the `dimmer-adjustment-mode` is `:foreground` we move the
;; foreground component toward the `default` background.
;; * When the `dimmer-adjustment-mode` is :background we mofe the
;; background component of F toward the `default` foreground.`
(when (and (or (eq dimmer-adjustment-mode :foreground)
(eq dimmer-adjustment-mode :both))
fg (color-defined-p fg)
def-bg (color-defined-p def-bg))
(setq result
(plist-put result :foreground
(dimmer-cached-compute-rgb fg
def-bg
my-frac
dimmer-use-colorspace))))
(when (and (or (eq dimmer-adjustment-mode :background)
(eq dimmer-adjustment-mode :both))
bg (color-defined-p bg)
def-fg (color-defined-p def-fg))
(setq result
(plist-put result :background
(dimmer-cached-compute-rgb bg
def-fg
my-frac
dimmer-use-colorspace))))
result))
(defun dimmer-filtered-face-list ()
"Return a filtered version of `face-list`.
Filtering is needed to exclude faces that shouldn't be dimmed."
;; `fringe` is problematic because it is shared for all windows,
;; so for now we just leave it alone.
(remove 'fringe (face-list)))
(defun dimmer-dim-buffer (buf frac)
"Dim all the faces defined in the buffer BUF.
FRAC controls the dimming as defined in ‘dimmer-face-color’."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-dim-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(unless dimmer-buffer-face-remaps
(dolist (f (dimmer-filtered-face-list))
(let ((c (dimmer-face-color f frac)))
(when c ; e.g. "(when-let* ((c (...)))" in Emacs 26
(push (face-remap-add-relative f c) dimmer-buffer-face-remaps)))))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-dim-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-restore-buffer (buf)
"Restore the un-dimmed faces in the buffer BUF."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-restore-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(when dimmer-buffer-face-remaps
(mapc 'face-remap-remove-relative dimmer-buffer-face-remaps)
(setq dimmer-buffer-face-remaps nil))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-restore-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-filtered-buffer-list ()
"Get filtered subset of all visible buffers in all frames."
(let (buffers)
(walk-windows
(lambda (win)
(let* ((buf (window-buffer win))
(name (buffer-name buf)))
(unless (or (member buf buffers)
(cl-some (lambda (rxp) (string-match-p rxp name))
dimmer-buffer-exclusion-regexps)
(cl-some (lambda (f) (funcall f buf))
dimmer-buffer-exclusion-predicates))
(push buf buffers))))
nil
t)
(dimmer--dbg 3 "dimmer-filtered-buffer-list: %s" buffers)
buffers))
(defun dimmer-process-all (&optional force)
"Process all buffers and dim or un-dim each.
When FORCE is true some special logic applies. Namely, we must
process all buffers regardless of the various dimming predicates.
While performing this scan, any buffer that would have been
excluded due to the predicates before should be un-dimmed now."
(dimmer--dbg-buffers 1 "dimmer-process-all")
(let ((selected (current-buffer))
(ignore (cl-some (lambda (f) (and (fboundp f) (funcall f)))
dimmer-prevent-dimming-predicates))
(filtbufs (dimmer-filtered-buffer-list)))
(dimmer--dbg 1 "dimmer-process-all: force %s" force)
(setq dimmer-last-buffer selected)
(when (or force (not ignore))
(dolist (buf (if force (buffer-list) filtbufs))
(dimmer--dbg 2 "dimmer-process-all: buf %s" buf)
(if (or (eq buf selected)
(and force (not (memq buf filtbufs))))
(dimmer-restore-buffer buf)
(dimmer-dim-buffer buf dimmer-fraction))))))
(defun dimmer-dim-all ()
"Dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-dim-all")
(mapc (lambda (buf)
(dimmer-dim-buffer buf dimmer-fraction))
(buffer-list)))
(defun dimmer-restore-all ()
"Un-dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-restore-all")
(mapc 'dimmer-restore-buffer (buffer-list)))
(defun dimmer-command-handler ()
"Process all buffers if current buffer has changed."
(dimmer--dbg-buffers 1 "dimmer-command-handler")
(unless (eq (window-buffer) dimmer-last-buffer)
(dimmer-process-all)))
(defun dimmer-config-change-handler ()
"Process all buffers if window configuration has changed."
(dimmer--dbg-buffers 1 "dimmer-config-change-handler")
(dimmer-process-all t))
(defun dimmer-after-focus-change-handler ()
"Handle cases where a frame may have gained or last focus.
Walk the `frame-list` and check the state of each one. If none
of the frames has focus then dim them all. If any frame has
focus then dim the others. Used in Emacs >= 27.0 only."
(dimmer--dbg-buffers 1 "dimmer-after-focus-change-handler")
(let ((focus-out t))
(with-no-warnings
(dolist (f (frame-list) focus-out)
(setq focus-out (and focus-out (not (frame-focus-state f))))))
(if focus-out
(dimmer-dim-all)
(dimmer-process-all t))))
(defun dimmer-manage-frame-focus-hooks (install)
"Manage the frame focus in/out hooks for dimmer.
When INSTALL is t, install the appropriate hooks to catch focus
events. Otherwise remove the hooks. This function has no effect
when `dimmer-watch-frame-focus-events` is nil."
(when dimmer-watch-frame-focus-events
(if (boundp 'after-focus-change-function)
;; emacs-version >= 27.0
(if install
(add-function :before
after-focus-change-function
#'dimmer-after-focus-change-handler)
(remove-function after-focus-change-function
#'dimmer-after-focus-change-handler))
;; else emacs-version < 27.0
(if install
(with-no-warnings
(add-hook 'focus-in-hook #'dimmer-config-change-handler)
(add-hook 'focus-out-hook #'dimmer-dim-all))
(with-no-warnings
(remove-hook 'focus-in-hook #'dimmer-config-change-handler)
(remove-hook 'focus-out-hook #'dimmer-dim-all))))))
;;;###autoload
(define-minor-mode dimmer-mode
"visually highlight the selected buffer"
nil
:lighter ""
:global t
:require 'dimmer
(if dimmer-mode
(progn
(dimmer-manage-frame-focus-hooks t)
(add-hook 'post-command-hook #'dimmer-command-handler)
(add-hook 'window-configuration-change-hook
#'dimmer-config-change-handler))
(dimmer-manage-frame-focus-hooks nil)
(remove-hook 'post-command-hook #'dimmer-command-handler)
(remove-hook 'window-configuration-change-hook
#'dimmer-config-change-handler)
(dimmer-restore-all)))
;;;###autoload
(define-obsolete-function-alias 'dimmer-activate 'dimmer-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; debugging - call from *scratch*, ielm, or eshell
(defun dimmer--debug-face-remapping-alist (name &optional clear)
"Display 'face-remapping-alist' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq face-remapping-alist nil)
face-remapping-alist)))
(defun dimmer--debug-buffer-face-remaps (name &optional clear)
"Display 'dimmer-buffer-face-remaps' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq dimmer-buffer-face-remaps nil)
dimmer-buffer-face-remaps)))
(defun dimmer--debug-reset (name)
"Clear 'face-remapping-alist' and 'dimmer-buffer-face-remaps' for NAME."
(dimmer--debug-face-remapping-alist name t)
(dimmer--debug-buffer-face-remaps name t)
(redraw-display))
(defun dimmer--dbg (v fmt &rest args)
"Print debug message at verbosity V, filling format string FMT with ARGS."
(when (>= dimmer-debug-messages v)
(apply #'message fmt args)))
(defun dimmer--dbg-buffers (v label)
"Print debug buffer state at verbosity V and the given LABEL."
(when (>= dimmer-debug-messages v)
(let ((inhibit-message t)
(cb (current-buffer))
(wb (window-buffer)))
(message "%s: cb '%s' <== lb '%s' %s" label cb dimmer-last-buffer
(if (not (eq cb wb))
(format "wb '%s' **" wb)
"")))))
(provide 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; dimmer.el ends here
| true | ;;; dimmer.el --- Visually highlight the selected buffer
;; Copyright (C) 2017-2020 PI:NAME:<NAME>END_PI
;; Filename: dimmer.el
;; Author: PI:NAME:<NAME>END_PI
;; Version: 0.4.2
;; Package-Version: 20200329.35
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/gonewest818/dimmer.el
;; Keywords: faces, editing
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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 3 of the
;; License, 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;
;;; Commentary:
;;
;; This module provides a minor mode that indicates which buffer is
;; currently active by dimming the faces in the other buffers. It
;; does this nondestructively, and computes the dimmed faces
;; dynamically such that your overall color scheme is shown in a muted
;; form without requiring you to define what is a "dim" version of
;; every face.
;;
;; `dimmer.el' can be configured to adjust foreground colors (default),
;; background colors, or both.
;;
;; Usage:
;;
;; (require 'dimmer)
;; (dimmer-configure-which-key)
;; (dimmer-configure-helm)
;; (dimmer-mode t)
;;
;; Configuration:
;;
;; By default dimmer excludes the minibuffer and echo areas from
;; consideration, so that most packages that use the minibuffer for
;; interaction will behave as users expect.
;;
;; `dimmer-configure-company-box' is a convenience function for users
;; of company-box. It prevents dimming the buffer you are editing when
;; a company-box popup is displayed.
;;
;; `dimmer-configure-helm' is a convenience function for helm users to
;; ensure helm buffers are not dimmed.
;;
;; `dimmer-configure-gnus' is a convenience function for gnus users to
;; ensure article buffers are not dimmed.
;;
;; `dimmer-configure-hydra' is a convenience function for hydra users to
;; ensure "*LV*" buffers are not dimmed.
;;
;; `dimmer-configure-magit' is a convenience function for magit users to
;; ensure transients are not dimmed.
;;
;; `dimmer-configure-org' is a convenience function for org users to
;; ensure org-mode buffers are not dimmed.
;;
;; `dimmer-configure-posframe' is a convenience function for posframe
;; users to ensure posframe buffers are not dimmed.
;;
;; `dimmer-configure-which-key' is a convenience function for which-key
;; users to ensure which-key popups are not dimmed.
;;
;; Please submit pull requests with configurations for other packages!
;;
;; Customization:
;;
;; `dimmer-adjustment-mode' controls what aspect of the color scheme is adjusted
;; when dimming. Choices are :foreground (default), :background, or :both.
;;
;; `dimmer-fraction' controls the degree to which buffers are dimmed.
;; Range is 0.0 - 1.0, and default is 0.20. Increase value if you
;; like the other buffers to be more dim.
;;
;; `dimmer-buffer-exclusion-regexps' can be used to specify buffers that
;; should never be dimmed. If the buffer name matches any regexp in
;; this list then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-buffer-exclusion-predicates' can be used to specify buffers that
;; should never be dimmed. If any predicate function in this list
;; returns true for the buffer then `dimmer.el' will not dim that buffer.
;;
;; `dimmer-prevent-dimming-predicates' can be used to prevent dimmer from
;; altering the dimmed buffer list. This can be used to detect cases
;; where a package pops up a window temporarily, and we don't want the
;; dimming to change. If any function in this list returns a non-nil
;; value, dimming state will not be changed.
;;
;; `dimmer-watch-frame-focus-events' controls whether dimmer will dim all
;; buffers when Emacs no longer has focus in the windowing system. This
;; is enabled by default. Some users may prefer to set this to nil, and
;; have the dimmed / not dimmed buffers stay as-is even when Emacs
;; doesn't have focus.
;;
;; `dimmer-use-colorspace' allows you to specify what color space the
;; dimming calculation is performed in. In the majority of cases you
;; won't need to touch this setting. See the docstring below for more
;; information.
;;
;;; Code:
(require 'cl-lib)
(require 'color)
(require 'face-remap)
(require 'seq)
(require 'subr-x)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; customization
(defgroup dimmer nil
"Highlight the current buffer by dimming the colors on the others."
:prefix "dimmer-"
:group 'convenience
:link '(url-link :tag "GitHub" "https://github.com/gonewest818/dimmer.el"))
(define-obsolete-variable-alias 'dimmer-percent 'dimmer-fraction)
(defcustom dimmer-fraction 0.20
"Control the degree to which buffers are dimmed (0.0 - 1.0)."
:type '(float)
:group 'dimmer)
(defcustom dimmer-adjustment-mode :foreground
"Control what aspect of the color scheme is adjusted when dimming.
Choices are :foreground (default), :background, or :both."
:type '(radio (const :tag "Foreground colors are dimmed" :foreground)
(const :tag "Background colors are dimmed" :background)
(const :tag "Foreground and background are dimmed" :both))
:group 'dimmer)
(make-obsolete-variable
'dimmer-exclusion-regexp
"`dimmer-exclusion-regexp` is obsolete and has no effect in this session.
The variable has been superseded by `dimmer-buffer-exclusion-regexps`.
See documentation for details."
"v0.4.0")
(define-obsolete-variable-alias
'dimmer-exclusion-regexp-list 'dimmer-buffer-exclusion-regexps)
(defcustom dimmer-buffer-exclusion-regexps '("^ \\*Minibuf-[0-9]+\\*$"
"^ \\*Echo.*\\*$")
"List of regular expressions describing buffer names that are never dimmed."
:type '(repeat (choice regexp))
:group 'dimmer)
(defcustom dimmer-buffer-exclusion-predicates '()
"List of predicate functions indicating buffers that are never dimmed.
Functions in the list are called while visiting each available
buffer. If the predicate function returns a truthy value, then
the buffer is not dimmed."
:type '(repeat (choice function))
:group 'dimmer)
(define-obsolete-variable-alias
'dimmer-exclusion-predicates 'dimmer-prevent-dimming-predicates)
(defcustom dimmer-prevent-dimming-predicates '(window-minibuffer-p)
"List of functions which prevent dimmer from altering dimmed buffer set.
Functions in this list are called in turn with no arguments. If any function
returns a non-nil value, no buffers will be added to or removed from the set
of dimmed buffers."
:type '(repeat (choice function))
:group 'dimmer)
(defcustom dimmer-watch-frame-focus-events t
"Should windows be dimmed when all Emacs frame(s) lose focus?
Restart Emacs after changing this configuration."
:type '(boolean)
:group 'dimmer)
(defcustom dimmer-use-colorspace :cielab
"Colorspace in which dimming calculations are performed.
Choices are :cielab (default), :hsl, or :rgb.
CIELAB is the default, and in most cases should serve perfectly
well. As a colorspace it attempts to be uniform to the human
eye, meaning the degree of dimming should be roughly the same for
all your foreground colors.
Bottom line: If CIELAB is working for you, then you don't need to
experiment with the other choices.
However, interpolating in CIELAB introduces one wrinkle, in that
mathematically it's possible to generate a color that isn't
representable on your RGB display (colors having one or more RGB
channel values < 0.0 or > 1.0). When dimmer finds an
\"impossible\" RGB value like that it simply clamps that value to
fit in the range 0.0 - 1.0. Clamping like this can lead to some
colors looking \"wrong\". If you think the dimmed values look
wrong, then try HSL or RGB instead."
:type '(radio (const :tag "Interpolate in CIELAB 1976" :cielab)
(const :tag "Interpolate in HSL" :hsl)
(const :tag "Interpolate in RGB" :rgb))
:group 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; configuration
;;;###autoload
(defun dimmer-configure-company-box ()
"Convenience setting for company-box users.
This predicate prevents dimming the buffer you are editing when
company-box pops up a list of completion."
(add-to-list
'dimmer-prevent-dimming-predicates
(lambda () (string-prefix-p " *company-box-" (buffer-name)))))
;;;###autoload
(defun dimmer-configure-helm ()
"Convenience settings for helm users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^\\*[h|H]elm.*\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'helm--alive-p)))
;;;###autoload
(defun dimmer-configure-gnus ()
"Convenience settings for gnus users."
(add-to-list
'dimmer-exclusion-regexp-list "^\\*Article .*\\*$"))
;;;###autoload
(defun dimmer-configure-hydra ()
"Convenience settings for hydra users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*LV\\*$"))
;;;###autoload
(defun dimmer-configure-magit ()
"Convenience settings for magit users."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*transient\\*$"))
;;;###autoload
(defun dimmer-configure-org ()
"Convenience settings for org users."
(add-to-list 'dimmer-exclusion-regexp-list "^\\*Org Select\\*$")
(add-to-list 'dimmer-exclusion-regexp-list "^ \\*Agenda Commands\\*$"))
;;;###autoload
(defun dimmer-configure-posframe ()
"Convenience settings for packages depending on posframe.
Note, packages that use posframe aren't required to be consistent
about how they name their buffers, but many of them tend to
include the words \"posframe\" and \"buffer\" in the buffer's
name. Examples include:
- \" *ivy-posframe-buffer*\"
- \" *company-posframe-buffer*\"
- \" *flycheck-posframe-buffer*\"
- \" *ddskk-posframe-buffer*\"
If this setting doesn't work for you, you still have the option
of adding another regular expression to catch more things, or
in some cases you can customize the other package and ensure it
uses a buffer name that fits this pattern."
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*.*posframe.*buffer.*\\*$"))
;;;###autoload
(defun dimmer-configure-which-key ()
"Convenience settings for which-key-users."
(with-no-warnings
(add-to-list
'dimmer-exclusion-regexp-list "^ \\*which-key\\*$")
(add-to-list
'dimmer-prevent-dimming-predicates #'which-key--popup-showing-p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; implementation
(defvar dimmer-last-buffer nil
"Identity of the last buffer to be made current.")
(defvar dimmer-debug-messages 0
"Control debugging output to *Messages* buffer.
Set 0 to disable all output, 1 for basic output, or a larger
integer for more verbosity.")
(defvar-local dimmer-buffer-face-remaps nil
"Per-buffer face remappings needed for later clean up.")
;; don't allow major mode change to kill the local variable
(put 'dimmer-buffer-face-remaps 'permanent-local t)
(defconst dimmer-dimmed-faces (make-hash-table :test 'equal)
"Cache of face names with their computed dimmed values.")
(defun dimmer-lerp (frac c0 c1)
"Use FRAC to compute a linear interpolation of C0 and C1."
(+ (* c0 (- 1.0 frac))
(* c1 frac)))
(defun dimmer-lerp-in-rgb (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in RGB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar (apply-partially 'dimmer-lerp frac) c0 c1)))
(defun dimmer-lerp-in-hsl (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in HSL space.
FRAC controls the interpolation."
;; Implementation note: We must handle this case carefully to ensure the
;; hue is interpolated over the "shortest" arc around the color wheel.
(apply 'color-rgb-to-hex
(apply 'color-hsl-to-rgb
(cl-destructuring-bind (h0 s0 l0)
(apply 'color-rgb-to-hsl c0)
(cl-destructuring-bind (h1 s1 l1)
(apply 'color-rgb-to-hsl c1)
(if (> (abs (- h1 h0)) 0.5)
;; shortest arc "wraps around"
(list (mod (dimmer-lerp (- 1.0 frac) h1 (+ 1.0 h0)) 1.0)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))
;; shortest arc is the natural one
(list (dimmer-lerp frac h0 h1)
(dimmer-lerp frac s0 s1)
(dimmer-lerp frac l0 l1))))))))
(defun dimmer-lerp-in-cielab (c0 c1 frac)
"Compute linear interpolation of C0 and C1 in CIELAB space.
FRAC controls the interpolation."
(apply 'color-rgb-to-hex
(cl-mapcar 'color-clamp
(apply 'color-lab-to-srgb
(cl-mapcar (apply-partially 'dimmer-lerp frac)
(apply 'color-srgb-to-lab c0)
(apply 'color-srgb-to-lab c1))))))
(defun dimmer-compute-rgb (c0 c1 frac colorspace)
"Compute a \"dimmed\" color via linear interpolation.
Blends the two colors, C0 and C1, using FRAC to control the
interpolation. When FRAC is 0.0, the result is equal to C0. When
FRAC is 1.0, the result is equal to C1.
Any other value for FRAC means the result's hue, saturation, and
value will be adjusted linearly so that the color sits somewhere
between C0 and C1.
The interpolation is performed in a COLORSPACE which is specified
with a symbol, :rgb, :hsl, or :cielab."
(pcase colorspace
(:rgb (dimmer-lerp-in-rgb c0 c1 frac))
(:hsl (dimmer-lerp-in-hsl c0 c1 frac))
(:cielab (dimmer-lerp-in-cielab c0 c1 frac))
(_ (dimmer-lerp-in-cielab c0 c1 frac))))
(defun dimmer-cached-compute-rgb (c0 c1 frac colorspace)
"Lookup a \"dimmed\" color value from cache, else compute a value.
This is essentially a memoization of `dimmer-compute-rgb` via a hash
using the arguments C0, C1, FRAC, and COLORSPACE as the key."
(let ((key (format "%s-%s-%f-%s" c0 c1 frac dimmer-use-colorspace)))
(or (gethash key dimmer-dimmed-faces)
(let ((rgb (dimmer-compute-rgb (color-name-to-rgb c0)
(color-name-to-rgb c1)
frac
dimmer-use-colorspace)))
(when rgb
(puthash key rgb dimmer-dimmed-faces)
rgb)))))
(defun dimmer-face-color (f frac)
"Compute a dimmed version of the foreground color of face F.
If `dimmer-adjust-background-color` is true, adjust the
background color as well. FRAC is the amount of dimming where
0.0 is no change and 1.0 is maximum change. Returns a plist
containing the new foreground (and if needed, new background)
suitable for use with `face-remap-add-relative`."
(let ((fg (face-foreground f))
(bg (face-background f))
(def-fg (face-foreground 'default))
(def-bg (face-background 'default))
;; when mode is :both, the perceptual effect is "doubled"
(my-frac (if (eq dimmer-adjustment-mode :both)
(/ frac 2.0)
frac))
(result '()))
;; We shift the desired components of F by FRAC amount toward the `default`
;; color, thereby dimming or desaturating the overall appearance:
;; * When the `dimmer-adjustment-mode` is `:foreground` we move the
;; foreground component toward the `default` background.
;; * When the `dimmer-adjustment-mode` is :background we mofe the
;; background component of F toward the `default` foreground.`
(when (and (or (eq dimmer-adjustment-mode :foreground)
(eq dimmer-adjustment-mode :both))
fg (color-defined-p fg)
def-bg (color-defined-p def-bg))
(setq result
(plist-put result :foreground
(dimmer-cached-compute-rgb fg
def-bg
my-frac
dimmer-use-colorspace))))
(when (and (or (eq dimmer-adjustment-mode :background)
(eq dimmer-adjustment-mode :both))
bg (color-defined-p bg)
def-fg (color-defined-p def-fg))
(setq result
(plist-put result :background
(dimmer-cached-compute-rgb bg
def-fg
my-frac
dimmer-use-colorspace))))
result))
(defun dimmer-filtered-face-list ()
"Return a filtered version of `face-list`.
Filtering is needed to exclude faces that shouldn't be dimmed."
;; `fringe` is problematic because it is shared for all windows,
;; so for now we just leave it alone.
(remove 'fringe (face-list)))
(defun dimmer-dim-buffer (buf frac)
"Dim all the faces defined in the buffer BUF.
FRAC controls the dimming as defined in ‘dimmer-face-color’."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-dim-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(unless dimmer-buffer-face-remaps
(dolist (f (dimmer-filtered-face-list))
(let ((c (dimmer-face-color f frac)))
(when c ; e.g. "(when-let* ((c (...)))" in Emacs 26
(push (face-remap-add-relative f c) dimmer-buffer-face-remaps)))))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-dim-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-restore-buffer (buf)
"Restore the un-dimmed faces in the buffer BUF."
(with-current-buffer buf
(dimmer--dbg 1 "dimmer-restore-buffer: BEFORE '%s' (%s)" buf
(alist-get 'default face-remapping-alist))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(when dimmer-buffer-face-remaps
(mapc 'face-remap-remove-relative dimmer-buffer-face-remaps)
(setq dimmer-buffer-face-remaps nil))
(dimmer--dbg 2 "dimmer-buffer-face-remaps: %s"
(alist-get 'default dimmer-buffer-face-remaps))
(dimmer--dbg 2 "dimmer-restore-buffer: AFTER '%s' (%s)" buf
(alist-get 'default face-remapping-alist))))
(defun dimmer-filtered-buffer-list ()
"Get filtered subset of all visible buffers in all frames."
(let (buffers)
(walk-windows
(lambda (win)
(let* ((buf (window-buffer win))
(name (buffer-name buf)))
(unless (or (member buf buffers)
(cl-some (lambda (rxp) (string-match-p rxp name))
dimmer-buffer-exclusion-regexps)
(cl-some (lambda (f) (funcall f buf))
dimmer-buffer-exclusion-predicates))
(push buf buffers))))
nil
t)
(dimmer--dbg 3 "dimmer-filtered-buffer-list: %s" buffers)
buffers))
(defun dimmer-process-all (&optional force)
"Process all buffers and dim or un-dim each.
When FORCE is true some special logic applies. Namely, we must
process all buffers regardless of the various dimming predicates.
While performing this scan, any buffer that would have been
excluded due to the predicates before should be un-dimmed now."
(dimmer--dbg-buffers 1 "dimmer-process-all")
(let ((selected (current-buffer))
(ignore (cl-some (lambda (f) (and (fboundp f) (funcall f)))
dimmer-prevent-dimming-predicates))
(filtbufs (dimmer-filtered-buffer-list)))
(dimmer--dbg 1 "dimmer-process-all: force %s" force)
(setq dimmer-last-buffer selected)
(when (or force (not ignore))
(dolist (buf (if force (buffer-list) filtbufs))
(dimmer--dbg 2 "dimmer-process-all: buf %s" buf)
(if (or (eq buf selected)
(and force (not (memq buf filtbufs))))
(dimmer-restore-buffer buf)
(dimmer-dim-buffer buf dimmer-fraction))))))
(defun dimmer-dim-all ()
"Dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-dim-all")
(mapc (lambda (buf)
(dimmer-dim-buffer buf dimmer-fraction))
(buffer-list)))
(defun dimmer-restore-all ()
"Un-dim all buffers."
(dimmer--dbg-buffers 1 "dimmer-restore-all")
(mapc 'dimmer-restore-buffer (buffer-list)))
(defun dimmer-command-handler ()
"Process all buffers if current buffer has changed."
(dimmer--dbg-buffers 1 "dimmer-command-handler")
(unless (eq (window-buffer) dimmer-last-buffer)
(dimmer-process-all)))
(defun dimmer-config-change-handler ()
"Process all buffers if window configuration has changed."
(dimmer--dbg-buffers 1 "dimmer-config-change-handler")
(dimmer-process-all t))
(defun dimmer-after-focus-change-handler ()
"Handle cases where a frame may have gained or last focus.
Walk the `frame-list` and check the state of each one. If none
of the frames has focus then dim them all. If any frame has
focus then dim the others. Used in Emacs >= 27.0 only."
(dimmer--dbg-buffers 1 "dimmer-after-focus-change-handler")
(let ((focus-out t))
(with-no-warnings
(dolist (f (frame-list) focus-out)
(setq focus-out (and focus-out (not (frame-focus-state f))))))
(if focus-out
(dimmer-dim-all)
(dimmer-process-all t))))
(defun dimmer-manage-frame-focus-hooks (install)
"Manage the frame focus in/out hooks for dimmer.
When INSTALL is t, install the appropriate hooks to catch focus
events. Otherwise remove the hooks. This function has no effect
when `dimmer-watch-frame-focus-events` is nil."
(when dimmer-watch-frame-focus-events
(if (boundp 'after-focus-change-function)
;; emacs-version >= 27.0
(if install
(add-function :before
after-focus-change-function
#'dimmer-after-focus-change-handler)
(remove-function after-focus-change-function
#'dimmer-after-focus-change-handler))
;; else emacs-version < 27.0
(if install
(with-no-warnings
(add-hook 'focus-in-hook #'dimmer-config-change-handler)
(add-hook 'focus-out-hook #'dimmer-dim-all))
(with-no-warnings
(remove-hook 'focus-in-hook #'dimmer-config-change-handler)
(remove-hook 'focus-out-hook #'dimmer-dim-all))))))
;;;###autoload
(define-minor-mode dimmer-mode
"visually highlight the selected buffer"
nil
:lighter ""
:global t
:require 'dimmer
(if dimmer-mode
(progn
(dimmer-manage-frame-focus-hooks t)
(add-hook 'post-command-hook #'dimmer-command-handler)
(add-hook 'window-configuration-change-hook
#'dimmer-config-change-handler))
(dimmer-manage-frame-focus-hooks nil)
(remove-hook 'post-command-hook #'dimmer-command-handler)
(remove-hook 'window-configuration-change-hook
#'dimmer-config-change-handler)
(dimmer-restore-all)))
;;;###autoload
(define-obsolete-function-alias 'dimmer-activate 'dimmer-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; debugging - call from *scratch*, ielm, or eshell
(defun dimmer--debug-face-remapping-alist (name &optional clear)
"Display 'face-remapping-alist' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq face-remapping-alist nil)
face-remapping-alist)))
(defun dimmer--debug-buffer-face-remaps (name &optional clear)
"Display 'dimmer-buffer-face-remaps' for buffer NAME (or clear if CLEAR)."
(with-current-buffer name
(if clear
(setq dimmer-buffer-face-remaps nil)
dimmer-buffer-face-remaps)))
(defun dimmer--debug-reset (name)
"Clear 'face-remapping-alist' and 'dimmer-buffer-face-remaps' for NAME."
(dimmer--debug-face-remapping-alist name t)
(dimmer--debug-buffer-face-remaps name t)
(redraw-display))
(defun dimmer--dbg (v fmt &rest args)
"Print debug message at verbosity V, filling format string FMT with ARGS."
(when (>= dimmer-debug-messages v)
(apply #'message fmt args)))
(defun dimmer--dbg-buffers (v label)
"Print debug buffer state at verbosity V and the given LABEL."
(when (>= dimmer-debug-messages v)
(let ((inhibit-message t)
(cb (current-buffer))
(wb (window-buffer)))
(message "%s: cb '%s' <== lb '%s' %s" label cb dimmer-last-buffer
(if (not (eq cb wb))
(format "wb '%s' **" wb)
"")))))
(provide 'dimmer)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; dimmer.el ends here
|
[
{
"context": "ooth-theme\n Created : Tue Jul 17 18:21:38 2012 - Jason Milkins. \n licence : MIT\n\n An amalgam of muted color ",
"end": 85,
"score": 0.9998518228530884,
"start": 72,
"tag": "NAME",
"value": "Jason Milkins"
}
] | themes/soothe-theme.el | ben-lerner/emacs | 3 | (deftheme soothe
"sooth-theme
Created : Tue Jul 17 18:21:38 2012 - Jason Milkins.
licence : MIT
An amalgam of muted color tones and highlighted backgrounds.
Also has support for rainbow-delimiters")
(let (
;; mode-line-font - tighten up the modeline by making it
;; variable pitch. This theme also uses powerline.el
(mode-line-font "Droid Sans")
;; named colors
(gray-1 "#828282")
(gray-1bg "#0a0a0a")
(gray-2 "#333333")
(gray-2bg "#111111")
(gray-3 "#aaaaaa")
(gray-3bg "#141414")
(gray-4 "#252525")
(gray-4bg "#171717")
(gray-5 "#2a2a2a")
(gray-5bg "#1a1a1a")
(gray-6 "#202020")
(gray-6bg "#1e1e1e")
(red-1 "#d13120")
(red-1bg "#1D1515")
(red-2 "#b23f1e")
(red-2bg "#251c1e")
(brown-1 "#9f621d")
(brown-1bg "#2a1f1f")
(orange-1 "#d97a35")
(orange-1bg "#1F1710")
(yellow-1 "#deae3e")
(yellow-1bg "#18140C")
(green-1 "#81af34")
(green-1bg "#1a2321")
(green-2 "#4e9f75")
(green-2bg "#1a2321")
(turquoise-1 "#11535F")
(turquoise-2 "#07272D")
(turquoise-1bg "#05181C")
(turquoise-2bg "#041316")
(blue-1 "#7e9fc9")
(blue-1bg "#1e252f")
(blue-2 "#417598")
(blue-2bg "#1b333e")
(blue-3 "#00959e")
(blue-3bg "#132228")
(blue-4 "#365e7a")
(blue-4bg "#172028")
(purple-1 "#a878b5")
(purple-1bg "#1D1B25")
;; special colors
(background "#110F13")
(alt-background "#111013")
(foreground "#dcdddd")
(hl-line "#11151a")
(selection "#311500")
)
(custom-theme-set-faces
'soothe
;; Basics
`(default ((t (:foreground ,foreground :background ,background ))))
`(cursor ((t ( :background ,red-2 ))))
`(region ((t (:foreground nil :background ,selection ))))
`(highlight ((t (:foreground ,blue-3 :background ,blue-3bg ))))
`(hl-line ((t ( :background ,hl-line ))))
`(minibuffer-prompt ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(escape-glyph ((t (:foreground ,red-1 :background ,purple-1bg ))))
;; Font-lock stuff
`(font-lock-builtin-face ((t (:foreground ,red-2 :background ,red-1bg ))))
`(font-lock-constant-face ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(font-lock-comment-face ((t (:foreground ,turquoise-1 :background ,alt-background :italic t ))))
`(font-lock-comment-delimiter-face ((t (:foreground ,turquoise-2 :background ,alt-background :italic t ))))
`(font-lock-doc-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-doc-string-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-function-name-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(font-lock-keyword-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-negation-char-face ((t (:foreground ,yellow-1 :background ,yellow-1bg ))))
`(font-lock-preprocessor-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-string-face ((t (:foreground ,turquoise-1 :background ,turquoise-2bg ))))
`(font-lock-type-face ((t (:foreground ,red-2 :background ,red-2bg :bold nil ))))
`(font-lock-variable-name-face ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(font-lock-warning-face ((t (:foreground ,red-2 :background ,red-2bg ))))
;; UI related
`(link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(fringe ((t ( :background ,gray-3bg ))))
`(mode-line ((t (:foreground ,gray-1 :background ,gray-3bg :box nil :height 85 :family ,mode-line-font ))))
`(mode-line-inactive ((t (:foreground ,gray-6 :background ,gray-3bg :box nil :height 85 ))))
`(vertical-border ((t (:foreground ,gray-5 :background ,background ))))
;; Linum
`(linum ((t (:foreground ,gray-5bg :background ,alt-background :height 90 ))))
;; show-paren-mode
`(show-paren-match ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(show-paren-mismatch ((t (:foreground ,red-2bg :background ,red-2 ))))
;; ido
`(ido-only-match ((t (:foreground ,green-1 :background ,green-1bg ))))
`(ido-subdir ((t (:foreground ,purple-1 :background ,purple-1bg ))))
;; whitespace-mode
`(whitespace-empty ((t (:foreground ,yellow-1bg :background ,yellow-1 ))))
`(whitespace-hspace ((t (:foreground ,gray-2 ))))
`(whitespace-indentation ((t (:foreground ,gray-2 ))))
`(whitespace-line ((t ( :background ,gray-2 ))))
`(whitespace-newline ((t (:foreground ,gray-2 ))))
`(whitespace-space ((t (:foreground ,gray-2 ))))
`(whitespace-space-after-tab ((t (:foreground ,gray-2 ))))
`(whitespace-tab ((t (:foreground ,gray-2 ))))
`(whitespace-trailing ((t (:foreground ,red-1bg :background ,red-1 ))))
;; flyspell-mode
`(flyspell-incorrect ((t (:underline ,red-2 ))))
`(flyspell-duplicate ((t (:underline ,red-2 ))))
;; magit
`(magit-diff-add ((t (:foreground ,green-1 ))))
`(magit-diff-del ((t (:foreground ,red-2 ))))
`(magit-item-highlight ((t ( :background ,gray-1bg ))))
;; highlight-indentation-mode
`(highlight-indentation-face ((t ( :background ,gray-1bg ))))
`(highlight-indentation-current-column-face ((t ( :background ,gray-4 ))))
;; ECB
`(ecb-default-general-face ((t (:foreground ,gray-3 :background ,gray-1bg ))))
`(ecb-default-highlight-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-method-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-tag-header-face ((t ( :background ,blue-2bg ))))
;; org-mode
`(org-date ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(org-done ((t (:foreground ,green-1 :background ,green-1bg ))))
`(org-hide ((t (:foreground ,gray-2 :background ,gray-1bg ))))
`(org-link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(org-todo ((t (:foreground ,red-1 :background ,red-1bg ))))
)
(custom-theme-set-variables
'soothe
`(powerline-color1 ,gray-6)
`(powerline-color2 ,gray-3bg)
`(Linum-format "%7i ")
`(fringe-mode 4)
;; Fill Column Indicator mode
`(fci-rule-color ,gray-6)
`(fci-rule-character-color ,gray-6)
`(ansi-color-names-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
`(ansi-term-color-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[unspecified ,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
)
)
;; Rainbow delimiters
(defun soothe-rainbow-delim-set-face ()
(set-face-attribute 'rainbow-delimiters-depth-1-face nil :foreground "#30828F" )
;; (set-face-attribute 'rainbow-delimiters-depth-2-face nil :foreground "#2c7580" )
;; (set-face-attribute 'rainbow-delimiters-depth-3-face nil :foreground "#276872" )
;; (set-face-attribute 'rainbow-delimiters-depth-4-face nil :foreground "#225B64" )
;; (set-face-attribute 'rainbow-delimiters-depth-5-face nil :foreground "#1D4E55" )
;; (set-face-attribute 'rainbow-delimiters-depth-6-face nil :foreground "#184147" )
;; (set-face-attribute 'rainbow-delimiters-depth-7-face nil :foreground "#133439" )
;; (set-face-attribute 'rainbow-delimiters-unmatched-face nil :foreground "#eF3000" )
)
;;(eval-after-load "rainbow-delimiters" '(soothe-rainbow-delim-set-face))
;;;###autoload
(when load-file-name
(add-to-list 'custom-theme-load-path
(file-name-as-directory (file-name-directory load-file-name))))
(provide-theme 'soothe)
| 46952 | (deftheme soothe
"sooth-theme
Created : Tue Jul 17 18:21:38 2012 - <NAME>.
licence : MIT
An amalgam of muted color tones and highlighted backgrounds.
Also has support for rainbow-delimiters")
(let (
;; mode-line-font - tighten up the modeline by making it
;; variable pitch. This theme also uses powerline.el
(mode-line-font "Droid Sans")
;; named colors
(gray-1 "#828282")
(gray-1bg "#0a0a0a")
(gray-2 "#333333")
(gray-2bg "#111111")
(gray-3 "#aaaaaa")
(gray-3bg "#141414")
(gray-4 "#252525")
(gray-4bg "#171717")
(gray-5 "#2a2a2a")
(gray-5bg "#1a1a1a")
(gray-6 "#202020")
(gray-6bg "#1e1e1e")
(red-1 "#d13120")
(red-1bg "#1D1515")
(red-2 "#b23f1e")
(red-2bg "#251c1e")
(brown-1 "#9f621d")
(brown-1bg "#2a1f1f")
(orange-1 "#d97a35")
(orange-1bg "#1F1710")
(yellow-1 "#deae3e")
(yellow-1bg "#18140C")
(green-1 "#81af34")
(green-1bg "#1a2321")
(green-2 "#4e9f75")
(green-2bg "#1a2321")
(turquoise-1 "#11535F")
(turquoise-2 "#07272D")
(turquoise-1bg "#05181C")
(turquoise-2bg "#041316")
(blue-1 "#7e9fc9")
(blue-1bg "#1e252f")
(blue-2 "#417598")
(blue-2bg "#1b333e")
(blue-3 "#00959e")
(blue-3bg "#132228")
(blue-4 "#365e7a")
(blue-4bg "#172028")
(purple-1 "#a878b5")
(purple-1bg "#1D1B25")
;; special colors
(background "#110F13")
(alt-background "#111013")
(foreground "#dcdddd")
(hl-line "#11151a")
(selection "#311500")
)
(custom-theme-set-faces
'soothe
;; Basics
`(default ((t (:foreground ,foreground :background ,background ))))
`(cursor ((t ( :background ,red-2 ))))
`(region ((t (:foreground nil :background ,selection ))))
`(highlight ((t (:foreground ,blue-3 :background ,blue-3bg ))))
`(hl-line ((t ( :background ,hl-line ))))
`(minibuffer-prompt ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(escape-glyph ((t (:foreground ,red-1 :background ,purple-1bg ))))
;; Font-lock stuff
`(font-lock-builtin-face ((t (:foreground ,red-2 :background ,red-1bg ))))
`(font-lock-constant-face ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(font-lock-comment-face ((t (:foreground ,turquoise-1 :background ,alt-background :italic t ))))
`(font-lock-comment-delimiter-face ((t (:foreground ,turquoise-2 :background ,alt-background :italic t ))))
`(font-lock-doc-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-doc-string-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-function-name-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(font-lock-keyword-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-negation-char-face ((t (:foreground ,yellow-1 :background ,yellow-1bg ))))
`(font-lock-preprocessor-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-string-face ((t (:foreground ,turquoise-1 :background ,turquoise-2bg ))))
`(font-lock-type-face ((t (:foreground ,red-2 :background ,red-2bg :bold nil ))))
`(font-lock-variable-name-face ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(font-lock-warning-face ((t (:foreground ,red-2 :background ,red-2bg ))))
;; UI related
`(link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(fringe ((t ( :background ,gray-3bg ))))
`(mode-line ((t (:foreground ,gray-1 :background ,gray-3bg :box nil :height 85 :family ,mode-line-font ))))
`(mode-line-inactive ((t (:foreground ,gray-6 :background ,gray-3bg :box nil :height 85 ))))
`(vertical-border ((t (:foreground ,gray-5 :background ,background ))))
;; Linum
`(linum ((t (:foreground ,gray-5bg :background ,alt-background :height 90 ))))
;; show-paren-mode
`(show-paren-match ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(show-paren-mismatch ((t (:foreground ,red-2bg :background ,red-2 ))))
;; ido
`(ido-only-match ((t (:foreground ,green-1 :background ,green-1bg ))))
`(ido-subdir ((t (:foreground ,purple-1 :background ,purple-1bg ))))
;; whitespace-mode
`(whitespace-empty ((t (:foreground ,yellow-1bg :background ,yellow-1 ))))
`(whitespace-hspace ((t (:foreground ,gray-2 ))))
`(whitespace-indentation ((t (:foreground ,gray-2 ))))
`(whitespace-line ((t ( :background ,gray-2 ))))
`(whitespace-newline ((t (:foreground ,gray-2 ))))
`(whitespace-space ((t (:foreground ,gray-2 ))))
`(whitespace-space-after-tab ((t (:foreground ,gray-2 ))))
`(whitespace-tab ((t (:foreground ,gray-2 ))))
`(whitespace-trailing ((t (:foreground ,red-1bg :background ,red-1 ))))
;; flyspell-mode
`(flyspell-incorrect ((t (:underline ,red-2 ))))
`(flyspell-duplicate ((t (:underline ,red-2 ))))
;; magit
`(magit-diff-add ((t (:foreground ,green-1 ))))
`(magit-diff-del ((t (:foreground ,red-2 ))))
`(magit-item-highlight ((t ( :background ,gray-1bg ))))
;; highlight-indentation-mode
`(highlight-indentation-face ((t ( :background ,gray-1bg ))))
`(highlight-indentation-current-column-face ((t ( :background ,gray-4 ))))
;; ECB
`(ecb-default-general-face ((t (:foreground ,gray-3 :background ,gray-1bg ))))
`(ecb-default-highlight-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-method-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-tag-header-face ((t ( :background ,blue-2bg ))))
;; org-mode
`(org-date ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(org-done ((t (:foreground ,green-1 :background ,green-1bg ))))
`(org-hide ((t (:foreground ,gray-2 :background ,gray-1bg ))))
`(org-link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(org-todo ((t (:foreground ,red-1 :background ,red-1bg ))))
)
(custom-theme-set-variables
'soothe
`(powerline-color1 ,gray-6)
`(powerline-color2 ,gray-3bg)
`(Linum-format "%7i ")
`(fringe-mode 4)
;; Fill Column Indicator mode
`(fci-rule-color ,gray-6)
`(fci-rule-character-color ,gray-6)
`(ansi-color-names-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
`(ansi-term-color-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[unspecified ,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
)
)
;; Rainbow delimiters
(defun soothe-rainbow-delim-set-face ()
(set-face-attribute 'rainbow-delimiters-depth-1-face nil :foreground "#30828F" )
;; (set-face-attribute 'rainbow-delimiters-depth-2-face nil :foreground "#2c7580" )
;; (set-face-attribute 'rainbow-delimiters-depth-3-face nil :foreground "#276872" )
;; (set-face-attribute 'rainbow-delimiters-depth-4-face nil :foreground "#225B64" )
;; (set-face-attribute 'rainbow-delimiters-depth-5-face nil :foreground "#1D4E55" )
;; (set-face-attribute 'rainbow-delimiters-depth-6-face nil :foreground "#184147" )
;; (set-face-attribute 'rainbow-delimiters-depth-7-face nil :foreground "#133439" )
;; (set-face-attribute 'rainbow-delimiters-unmatched-face nil :foreground "#eF3000" )
)
;;(eval-after-load "rainbow-delimiters" '(soothe-rainbow-delim-set-face))
;;;###autoload
(when load-file-name
(add-to-list 'custom-theme-load-path
(file-name-as-directory (file-name-directory load-file-name))))
(provide-theme 'soothe)
| true | (deftheme soothe
"sooth-theme
Created : Tue Jul 17 18:21:38 2012 - PI:NAME:<NAME>END_PI.
licence : MIT
An amalgam of muted color tones and highlighted backgrounds.
Also has support for rainbow-delimiters")
(let (
;; mode-line-font - tighten up the modeline by making it
;; variable pitch. This theme also uses powerline.el
(mode-line-font "Droid Sans")
;; named colors
(gray-1 "#828282")
(gray-1bg "#0a0a0a")
(gray-2 "#333333")
(gray-2bg "#111111")
(gray-3 "#aaaaaa")
(gray-3bg "#141414")
(gray-4 "#252525")
(gray-4bg "#171717")
(gray-5 "#2a2a2a")
(gray-5bg "#1a1a1a")
(gray-6 "#202020")
(gray-6bg "#1e1e1e")
(red-1 "#d13120")
(red-1bg "#1D1515")
(red-2 "#b23f1e")
(red-2bg "#251c1e")
(brown-1 "#9f621d")
(brown-1bg "#2a1f1f")
(orange-1 "#d97a35")
(orange-1bg "#1F1710")
(yellow-1 "#deae3e")
(yellow-1bg "#18140C")
(green-1 "#81af34")
(green-1bg "#1a2321")
(green-2 "#4e9f75")
(green-2bg "#1a2321")
(turquoise-1 "#11535F")
(turquoise-2 "#07272D")
(turquoise-1bg "#05181C")
(turquoise-2bg "#041316")
(blue-1 "#7e9fc9")
(blue-1bg "#1e252f")
(blue-2 "#417598")
(blue-2bg "#1b333e")
(blue-3 "#00959e")
(blue-3bg "#132228")
(blue-4 "#365e7a")
(blue-4bg "#172028")
(purple-1 "#a878b5")
(purple-1bg "#1D1B25")
;; special colors
(background "#110F13")
(alt-background "#111013")
(foreground "#dcdddd")
(hl-line "#11151a")
(selection "#311500")
)
(custom-theme-set-faces
'soothe
;; Basics
`(default ((t (:foreground ,foreground :background ,background ))))
`(cursor ((t ( :background ,red-2 ))))
`(region ((t (:foreground nil :background ,selection ))))
`(highlight ((t (:foreground ,blue-3 :background ,blue-3bg ))))
`(hl-line ((t ( :background ,hl-line ))))
`(minibuffer-prompt ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(escape-glyph ((t (:foreground ,red-1 :background ,purple-1bg ))))
;; Font-lock stuff
`(font-lock-builtin-face ((t (:foreground ,red-2 :background ,red-1bg ))))
`(font-lock-constant-face ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(font-lock-comment-face ((t (:foreground ,turquoise-1 :background ,alt-background :italic t ))))
`(font-lock-comment-delimiter-face ((t (:foreground ,turquoise-2 :background ,alt-background :italic t ))))
`(font-lock-doc-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-doc-string-face ((t (:foreground ,blue-3 :background ,gray-1bg ))))
`(font-lock-function-name-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(font-lock-keyword-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-negation-char-face ((t (:foreground ,yellow-1 :background ,yellow-1bg ))))
`(font-lock-preprocessor-face ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(font-lock-string-face ((t (:foreground ,turquoise-1 :background ,turquoise-2bg ))))
`(font-lock-type-face ((t (:foreground ,red-2 :background ,red-2bg :bold nil ))))
`(font-lock-variable-name-face ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(font-lock-warning-face ((t (:foreground ,red-2 :background ,red-2bg ))))
;; UI related
`(link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(fringe ((t ( :background ,gray-3bg ))))
`(mode-line ((t (:foreground ,gray-1 :background ,gray-3bg :box nil :height 85 :family ,mode-line-font ))))
`(mode-line-inactive ((t (:foreground ,gray-6 :background ,gray-3bg :box nil :height 85 ))))
`(vertical-border ((t (:foreground ,gray-5 :background ,background ))))
;; Linum
`(linum ((t (:foreground ,gray-5bg :background ,alt-background :height 90 ))))
;; show-paren-mode
`(show-paren-match ((t (:foreground ,orange-1 :background ,orange-1bg ))))
`(show-paren-mismatch ((t (:foreground ,red-2bg :background ,red-2 ))))
;; ido
`(ido-only-match ((t (:foreground ,green-1 :background ,green-1bg ))))
`(ido-subdir ((t (:foreground ,purple-1 :background ,purple-1bg ))))
;; whitespace-mode
`(whitespace-empty ((t (:foreground ,yellow-1bg :background ,yellow-1 ))))
`(whitespace-hspace ((t (:foreground ,gray-2 ))))
`(whitespace-indentation ((t (:foreground ,gray-2 ))))
`(whitespace-line ((t ( :background ,gray-2 ))))
`(whitespace-newline ((t (:foreground ,gray-2 ))))
`(whitespace-space ((t (:foreground ,gray-2 ))))
`(whitespace-space-after-tab ((t (:foreground ,gray-2 ))))
`(whitespace-tab ((t (:foreground ,gray-2 ))))
`(whitespace-trailing ((t (:foreground ,red-1bg :background ,red-1 ))))
;; flyspell-mode
`(flyspell-incorrect ((t (:underline ,red-2 ))))
`(flyspell-duplicate ((t (:underline ,red-2 ))))
;; magit
`(magit-diff-add ((t (:foreground ,green-1 ))))
`(magit-diff-del ((t (:foreground ,red-2 ))))
`(magit-item-highlight ((t ( :background ,gray-1bg ))))
;; highlight-indentation-mode
`(highlight-indentation-face ((t ( :background ,gray-1bg ))))
`(highlight-indentation-current-column-face ((t ( :background ,gray-4 ))))
;; ECB
`(ecb-default-general-face ((t (:foreground ,gray-3 :background ,gray-1bg ))))
`(ecb-default-highlight-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-method-face ((t (:foreground ,red-1 :background ,red-1bg ))))
`(ecb-tag-header-face ((t ( :background ,blue-2bg ))))
;; org-mode
`(org-date ((t (:foreground ,purple-1 :background ,purple-1bg ))))
`(org-done ((t (:foreground ,green-1 :background ,green-1bg ))))
`(org-hide ((t (:foreground ,gray-2 :background ,gray-1bg ))))
`(org-link ((t (:foreground ,blue-1 :background ,blue-1bg ))))
`(org-todo ((t (:foreground ,red-1 :background ,red-1bg ))))
)
(custom-theme-set-variables
'soothe
`(powerline-color1 ,gray-6)
`(powerline-color2 ,gray-3bg)
`(Linum-format "%7i ")
`(fringe-mode 4)
;; Fill Column Indicator mode
`(fci-rule-color ,gray-6)
`(fci-rule-character-color ,gray-6)
`(ansi-color-names-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
`(ansi-term-color-vector
;; black, red, green, yellow, blue, magenta, cyan, white
[unspecified ,background ,red-1 ,green-1 ,yellow-1 ,blue-1 ,purple-1 ,blue-1 ,foreground])
)
)
;; Rainbow delimiters
(defun soothe-rainbow-delim-set-face ()
(set-face-attribute 'rainbow-delimiters-depth-1-face nil :foreground "#30828F" )
;; (set-face-attribute 'rainbow-delimiters-depth-2-face nil :foreground "#2c7580" )
;; (set-face-attribute 'rainbow-delimiters-depth-3-face nil :foreground "#276872" )
;; (set-face-attribute 'rainbow-delimiters-depth-4-face nil :foreground "#225B64" )
;; (set-face-attribute 'rainbow-delimiters-depth-5-face nil :foreground "#1D4E55" )
;; (set-face-attribute 'rainbow-delimiters-depth-6-face nil :foreground "#184147" )
;; (set-face-attribute 'rainbow-delimiters-depth-7-face nil :foreground "#133439" )
;; (set-face-attribute 'rainbow-delimiters-unmatched-face nil :foreground "#eF3000" )
)
;;(eval-after-load "rainbow-delimiters" '(soothe-rainbow-delim-set-face))
;;;###autoload
(when load-file-name
(add-to-list 'custom-theme-load-path
(file-name-as-directory (file-name-directory load-file-name))))
(provide-theme 'soothe)
|
[
{
"context": ";; Copyright (c) 2020-2021 Jiacheng Huang\n\n;; Permission is hereby granted, free of charge,",
"end": 41,
"score": 0.9998272061347961,
"start": 27,
"tag": "NAME",
"value": "Jiacheng Huang"
},
{
"context": "-install package-selected-packages))\n\n;; Bootstrap John Wigley's \"use-package\"\n(unless (package-installed-p 'use",
"end": 2831,
"score": 0.9943997859954834,
"start": 2820,
"tag": "NAME",
"value": "John Wigley"
}
] | init.el | vodjia/emofacs | 0 | ;; Copyright (c) 2020-2021 Jiacheng Huang
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; Package Setup
(setq package-archives '(("melpa" . "http://melpa.org/packages/")
("gnu" . "http://elpa.gnu.org/packages/")))
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
;; Comment/uncomment this line to enable MELPA Stable if desired. See `package-archive-priorities`
;; and `package-pinned-packages`. Most users will not need or want to do this.
;; (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(package-initialize)
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
'("e6df46d5085fde0ad56a46ef69ebb388193080cc9819e2d6024c9c6e27388ba9" default))
'(package-selected-packages
'(zenburn-theme ido-completing-read+ iedit lsp-ivy lsp-ui latex-preview-pane counsel-projectile powerline zoom treemacs-all-the-icons org-dashboard dashboard lsp-python-ms lsp-java dap-mode which-key magit go-mode exec-path-from-shell rustic rust-mode yasnippet-snippets yasnippet treemacs-projectile treemacs projectile lsp-mode counsel ivy flycheck company smartparens)))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
(when (cl-find-if-not #'package-installed-p package-selected-packages)
(package-refresh-contents)
(mapc #'package-install package-selected-packages))
;; Bootstrap John Wigley's "use-package"
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Ensure environment variables inside Emacs look the same as in the user's shell
(when (memq window-system '(mac ns x))
(exec-path-from-shell-initialize))
(when (daemonp)
(exec-path-from-shell-initialize))
;; Zenburn
(load-theme 'zenburn t)
;; All The Icons
(require 'all-the-icons)
(when (display-graphic-p)
(unless (member "all-the-icons" (font-family-list)) (all-the-icons-install-fonts)))
;; Power Line
(require 'powerline)
(powerline-default-theme)
;; Dashboard
(require 'dashboard)
(dashboard-setup-startup-hook)
(setq dashboard-banner-logo-title "E + mofa + cs")
(setq dashboard-center-content t)
(setq dashboard-items '((projects . 8)
(recents . 8)))
(setq dashboard-startup-banner 'logo)
(setq dashboard-set-heading-icons t)
(setq dashboard-set-file-icons t)
(setq dashboard-set-navigator t)
(setq dashboard-set-init-info t)
(setq dashboard-projects-switch-function 'counsel-projectile-switch-project-by-name)
;; Zoom
(zoom-mode)
(setq zoom-size '(0.618 . 0.618))
;; Projectile
(projectile-mode 1)
(define-key projectile-mode-map (kbd "s-p") 'projectile-command-map)
(define-key projectile-mode-map (kbd "C-c p") 'projectile-command-map)
;; Iedit
(require 'iedit)
;; Ido
(ido-mode 1)
(ido-everywhere 1)
;; Ido Completing Read Plus
(require 'ido-completing-read+)
(ido-ubiquitous-mode 1)
;; Ivy
(ivy-mode)
(counsel-mode)
(counsel-projectile-mode)
(setq ivy-use-virtual-buffers t)
(setq enable-recursive-minibuffers t)
(setq search-default-mode #'char-fold-to-regexp)
(global-set-key "\C-s" 'swiper)
;; Treemacs
(require 'treemacs)
(treemacs-follow-mode t)
(treemacs-filewatch-mode t)
(treemacs-fringe-indicator-mode t)
(setq treemacs-show-cursor t)
(setq treemacs-width 32)
(define-key treemacs-mode-map [mouse-1] #'treemacs-single-click-expand-action)
(define-key global-map (kbd "M-0") 'treemacs-select-window)
;; Treemacs All The Icons
(require 'treemacs-all-the-icons)
(treemacs-load-theme "all-the-icons")
;; Treemacs Projectile
(require 'treemacs-projectile)
;; Company
(add-hook 'after-init-hook 'global-company-mode)
(setq company-idle-delay 0)
(setq company-minimum-prefix-length 1)
(setq company-show-numbers t)
;; Which Key
(which-key-mode)
;; YASnippet
(yas-global-mode 1)
(defvar my-company-point nil)
(advice-add 'company-complete-common
:before (lambda () (setq my-company-point (point))))
(advice-add 'company-complete-common
:after (lambda ()
(when (equal my-company-point (point))
(yas-expand))))
;; LSP
(add-hook 'c-mode-hook 'lsp)
(add-hook 'c++-mode-hook 'lsp)
(add-hook 'go-mode-hook 'lsp)
(require 'lsp-java)
(add-hook 'java-mode-hook #'lsp)
(add-hook 'js-mode-hook 'lsp)
(require 'lsp-python-ms)
(setq lsp-python-ms-auto-install-server t)
(add-hook 'python-mode-hook #'lsp)
(use-package lsp-python-ms
:ensure t
:init (setq lsp-python-ms-auto-install-server t)
:hook (python-mode . (lambda ()
(require 'lsp-python-ms)
(lsp))))
(add-hook 'rust-mode-hook 'lsp)
(add-hook 'latex-mode-hook 'lsp)
(add-hook 'markdown-mode-hook 'lsp)
(setq lsp-clients-clangd-args
'("--header-insertion=never"
"--header-insertion-decorators=0"))
(with-eval-after-load 'lsp-mode
(add-hook 'lsp-mode-hook #'lsp-enable-which-key-integration)
(require 'dap-cpptools)
(yas-global-mode))
;; Flycheck
(add-hook 'c-mode-hook #'flycheck-mode)
(add-hook 'c++-mode-hook #'flycheck-mode)
(add-hook 'go-mode-hook #'flycheck-mode)
(add-hook 'java-mode-hook #'flycheck-mode)
(add-hook 'js-mode-hook #'flycheck-mode)
(add-hook 'python-mode-hook #'flycheck-mode)
(add-hook 'rust-mode-hook #'flycheck-mode)
;; Smartparens
(require 'smartparens-config)
(add-hook 'asm-mode-hook #'smartparens-mode)
(add-hook 'c-mode-hook #'smartparens-mode)
(add-hook 'c++-mode-hook #'smartparens-mode)
(add-hook 'emacs-lisp-mode-hook #'smartparens-mode)
(add-hook 'go-mode-hook #'smartparens-mode)
(add-hook 'java-mode-hook #'smartparens-mode)
(add-hook 'js-mode-hook #'smartparens-mode)
(add-hook 'python-mode-hook #'smartparens-mode)
(add-hook 'rust-mode-hook #'smartparens-mode)
(add-hook 'rustic-mode-hook #'smartparens-mode)
(add-hook 'verilog-mode #'smartparens-mode)
;; When you press RET, the curly braces automatically add another newline.
(sp-with-modes '(asm-mode c-mode c++-mode emacs-lisp-mode java-mode js-mode python-mode rust-mode rustic-mode verilog-mode)
(sp-local-pair "{" nil :post-handlers '(("||\n[i]" "RET")))
(sp-local-pair "/*" "*/" :post-handlers '(("| " "SPC") ("* ||\n[i]" "RET"))))
(setq sp-escape-quotes-after-insert nil)
;; Windmove
(when (fboundp 'windmove-default-keybindings)
(windmove-default-keybindings))
;; Ace Window
(global-set-key (kbd "M-o") 'ace-window)
;; Winner
(when (fboundp 'winner-mode)
(winner-mode 1))
;; Alarm Bell
(setq ring-bell-function 'ignore)
;; Window Resize
(global-set-key (kbd "S-C-<left>") 'shrink-window-horizontally)
(global-set-key (kbd "S-C-<right>") 'enlarge-window-horizontally)
(global-set-key (kbd "S-C-<down>") 'shrink-window)
(global-set-key (kbd "S-C-<up>") 'enlarge-window)
;; Line Number Mode
(if (version<= "26.0.50" emacs-version)
(global-display-line-numbers-mode)
(global-linum-mode 1))
;; Column Number Mode
(column-number-mode 1)
;; Start Emacs in fullscreen mode
(add-hook 'emacs-startup-hook 'toggle-frame-fullscreen)
;; Place auto-save files into system's temporary file
(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))
;; Delete Selection Mode
(delete-selection-mode 1)
;; No Tabs
(setq-default indent-tabs-mode nil)
;; Org Mode
(eval-after-load "org"
'(require 'ox-md nil t))
(setq org-adapt-indentation nil)
;; CC Mode
(require 'cc-mode)
(setq c-default-style "user")
;; Rust Mode
(require 'rust-mode)
(setq rust-format-on-save t)
(define-key rust-mode-map (kbd "C-c C-c") 'rust-run)
;; Rustic Mode
(use-package rustic)
;; JavaScript Mode
(setq-default js-indent-level 2)
;; CSS Mode
(setq-default css-indent-offset 2)
| 23372 | ;; Copyright (c) 2020-2021 <NAME>
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; Package Setup
(setq package-archives '(("melpa" . "http://melpa.org/packages/")
("gnu" . "http://elpa.gnu.org/packages/")))
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
;; Comment/uncomment this line to enable MELPA Stable if desired. See `package-archive-priorities`
;; and `package-pinned-packages`. Most users will not need or want to do this.
;; (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(package-initialize)
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
'("e6df46d5085fde0ad56a46ef69ebb388193080cc9819e2d6024c9c6e27388ba9" default))
'(package-selected-packages
'(zenburn-theme ido-completing-read+ iedit lsp-ivy lsp-ui latex-preview-pane counsel-projectile powerline zoom treemacs-all-the-icons org-dashboard dashboard lsp-python-ms lsp-java dap-mode which-key magit go-mode exec-path-from-shell rustic rust-mode yasnippet-snippets yasnippet treemacs-projectile treemacs projectile lsp-mode counsel ivy flycheck company smartparens)))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
(when (cl-find-if-not #'package-installed-p package-selected-packages)
(package-refresh-contents)
(mapc #'package-install package-selected-packages))
;; Bootstrap <NAME>'s "use-package"
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Ensure environment variables inside Emacs look the same as in the user's shell
(when (memq window-system '(mac ns x))
(exec-path-from-shell-initialize))
(when (daemonp)
(exec-path-from-shell-initialize))
;; Zenburn
(load-theme 'zenburn t)
;; All The Icons
(require 'all-the-icons)
(when (display-graphic-p)
(unless (member "all-the-icons" (font-family-list)) (all-the-icons-install-fonts)))
;; Power Line
(require 'powerline)
(powerline-default-theme)
;; Dashboard
(require 'dashboard)
(dashboard-setup-startup-hook)
(setq dashboard-banner-logo-title "E + mofa + cs")
(setq dashboard-center-content t)
(setq dashboard-items '((projects . 8)
(recents . 8)))
(setq dashboard-startup-banner 'logo)
(setq dashboard-set-heading-icons t)
(setq dashboard-set-file-icons t)
(setq dashboard-set-navigator t)
(setq dashboard-set-init-info t)
(setq dashboard-projects-switch-function 'counsel-projectile-switch-project-by-name)
;; Zoom
(zoom-mode)
(setq zoom-size '(0.618 . 0.618))
;; Projectile
(projectile-mode 1)
(define-key projectile-mode-map (kbd "s-p") 'projectile-command-map)
(define-key projectile-mode-map (kbd "C-c p") 'projectile-command-map)
;; Iedit
(require 'iedit)
;; Ido
(ido-mode 1)
(ido-everywhere 1)
;; Ido Completing Read Plus
(require 'ido-completing-read+)
(ido-ubiquitous-mode 1)
;; Ivy
(ivy-mode)
(counsel-mode)
(counsel-projectile-mode)
(setq ivy-use-virtual-buffers t)
(setq enable-recursive-minibuffers t)
(setq search-default-mode #'char-fold-to-regexp)
(global-set-key "\C-s" 'swiper)
;; Treemacs
(require 'treemacs)
(treemacs-follow-mode t)
(treemacs-filewatch-mode t)
(treemacs-fringe-indicator-mode t)
(setq treemacs-show-cursor t)
(setq treemacs-width 32)
(define-key treemacs-mode-map [mouse-1] #'treemacs-single-click-expand-action)
(define-key global-map (kbd "M-0") 'treemacs-select-window)
;; Treemacs All The Icons
(require 'treemacs-all-the-icons)
(treemacs-load-theme "all-the-icons")
;; Treemacs Projectile
(require 'treemacs-projectile)
;; Company
(add-hook 'after-init-hook 'global-company-mode)
(setq company-idle-delay 0)
(setq company-minimum-prefix-length 1)
(setq company-show-numbers t)
;; Which Key
(which-key-mode)
;; YASnippet
(yas-global-mode 1)
(defvar my-company-point nil)
(advice-add 'company-complete-common
:before (lambda () (setq my-company-point (point))))
(advice-add 'company-complete-common
:after (lambda ()
(when (equal my-company-point (point))
(yas-expand))))
;; LSP
(add-hook 'c-mode-hook 'lsp)
(add-hook 'c++-mode-hook 'lsp)
(add-hook 'go-mode-hook 'lsp)
(require 'lsp-java)
(add-hook 'java-mode-hook #'lsp)
(add-hook 'js-mode-hook 'lsp)
(require 'lsp-python-ms)
(setq lsp-python-ms-auto-install-server t)
(add-hook 'python-mode-hook #'lsp)
(use-package lsp-python-ms
:ensure t
:init (setq lsp-python-ms-auto-install-server t)
:hook (python-mode . (lambda ()
(require 'lsp-python-ms)
(lsp))))
(add-hook 'rust-mode-hook 'lsp)
(add-hook 'latex-mode-hook 'lsp)
(add-hook 'markdown-mode-hook 'lsp)
(setq lsp-clients-clangd-args
'("--header-insertion=never"
"--header-insertion-decorators=0"))
(with-eval-after-load 'lsp-mode
(add-hook 'lsp-mode-hook #'lsp-enable-which-key-integration)
(require 'dap-cpptools)
(yas-global-mode))
;; Flycheck
(add-hook 'c-mode-hook #'flycheck-mode)
(add-hook 'c++-mode-hook #'flycheck-mode)
(add-hook 'go-mode-hook #'flycheck-mode)
(add-hook 'java-mode-hook #'flycheck-mode)
(add-hook 'js-mode-hook #'flycheck-mode)
(add-hook 'python-mode-hook #'flycheck-mode)
(add-hook 'rust-mode-hook #'flycheck-mode)
;; Smartparens
(require 'smartparens-config)
(add-hook 'asm-mode-hook #'smartparens-mode)
(add-hook 'c-mode-hook #'smartparens-mode)
(add-hook 'c++-mode-hook #'smartparens-mode)
(add-hook 'emacs-lisp-mode-hook #'smartparens-mode)
(add-hook 'go-mode-hook #'smartparens-mode)
(add-hook 'java-mode-hook #'smartparens-mode)
(add-hook 'js-mode-hook #'smartparens-mode)
(add-hook 'python-mode-hook #'smartparens-mode)
(add-hook 'rust-mode-hook #'smartparens-mode)
(add-hook 'rustic-mode-hook #'smartparens-mode)
(add-hook 'verilog-mode #'smartparens-mode)
;; When you press RET, the curly braces automatically add another newline.
(sp-with-modes '(asm-mode c-mode c++-mode emacs-lisp-mode java-mode js-mode python-mode rust-mode rustic-mode verilog-mode)
(sp-local-pair "{" nil :post-handlers '(("||\n[i]" "RET")))
(sp-local-pair "/*" "*/" :post-handlers '(("| " "SPC") ("* ||\n[i]" "RET"))))
(setq sp-escape-quotes-after-insert nil)
;; Windmove
(when (fboundp 'windmove-default-keybindings)
(windmove-default-keybindings))
;; Ace Window
(global-set-key (kbd "M-o") 'ace-window)
;; Winner
(when (fboundp 'winner-mode)
(winner-mode 1))
;; Alarm Bell
(setq ring-bell-function 'ignore)
;; Window Resize
(global-set-key (kbd "S-C-<left>") 'shrink-window-horizontally)
(global-set-key (kbd "S-C-<right>") 'enlarge-window-horizontally)
(global-set-key (kbd "S-C-<down>") 'shrink-window)
(global-set-key (kbd "S-C-<up>") 'enlarge-window)
;; Line Number Mode
(if (version<= "26.0.50" emacs-version)
(global-display-line-numbers-mode)
(global-linum-mode 1))
;; Column Number Mode
(column-number-mode 1)
;; Start Emacs in fullscreen mode
(add-hook 'emacs-startup-hook 'toggle-frame-fullscreen)
;; Place auto-save files into system's temporary file
(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))
;; Delete Selection Mode
(delete-selection-mode 1)
;; No Tabs
(setq-default indent-tabs-mode nil)
;; Org Mode
(eval-after-load "org"
'(require 'ox-md nil t))
(setq org-adapt-indentation nil)
;; CC Mode
(require 'cc-mode)
(setq c-default-style "user")
;; Rust Mode
(require 'rust-mode)
(setq rust-format-on-save t)
(define-key rust-mode-map (kbd "C-c C-c") 'rust-run)
;; Rustic Mode
(use-package rustic)
;; JavaScript Mode
(setq-default js-indent-level 2)
;; CSS Mode
(setq-default css-indent-offset 2)
| true | ;; Copyright (c) 2020-2021 PI:NAME:<NAME>END_PI
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;; Package Setup
(setq package-archives '(("melpa" . "http://melpa.org/packages/")
("gnu" . "http://elpa.gnu.org/packages/")))
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
;; Comment/uncomment this line to enable MELPA Stable if desired. See `package-archive-priorities`
;; and `package-pinned-packages`. Most users will not need or want to do this.
;; (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(package-initialize)
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
'("e6df46d5085fde0ad56a46ef69ebb388193080cc9819e2d6024c9c6e27388ba9" default))
'(package-selected-packages
'(zenburn-theme ido-completing-read+ iedit lsp-ivy lsp-ui latex-preview-pane counsel-projectile powerline zoom treemacs-all-the-icons org-dashboard dashboard lsp-python-ms lsp-java dap-mode which-key magit go-mode exec-path-from-shell rustic rust-mode yasnippet-snippets yasnippet treemacs-projectile treemacs projectile lsp-mode counsel ivy flycheck company smartparens)))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
(when (cl-find-if-not #'package-installed-p package-selected-packages)
(package-refresh-contents)
(mapc #'package-install package-selected-packages))
;; Bootstrap PI:NAME:<NAME>END_PI's "use-package"
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Ensure environment variables inside Emacs look the same as in the user's shell
(when (memq window-system '(mac ns x))
(exec-path-from-shell-initialize))
(when (daemonp)
(exec-path-from-shell-initialize))
;; Zenburn
(load-theme 'zenburn t)
;; All The Icons
(require 'all-the-icons)
(when (display-graphic-p)
(unless (member "all-the-icons" (font-family-list)) (all-the-icons-install-fonts)))
;; Power Line
(require 'powerline)
(powerline-default-theme)
;; Dashboard
(require 'dashboard)
(dashboard-setup-startup-hook)
(setq dashboard-banner-logo-title "E + mofa + cs")
(setq dashboard-center-content t)
(setq dashboard-items '((projects . 8)
(recents . 8)))
(setq dashboard-startup-banner 'logo)
(setq dashboard-set-heading-icons t)
(setq dashboard-set-file-icons t)
(setq dashboard-set-navigator t)
(setq dashboard-set-init-info t)
(setq dashboard-projects-switch-function 'counsel-projectile-switch-project-by-name)
;; Zoom
(zoom-mode)
(setq zoom-size '(0.618 . 0.618))
;; Projectile
(projectile-mode 1)
(define-key projectile-mode-map (kbd "s-p") 'projectile-command-map)
(define-key projectile-mode-map (kbd "C-c p") 'projectile-command-map)
;; Iedit
(require 'iedit)
;; Ido
(ido-mode 1)
(ido-everywhere 1)
;; Ido Completing Read Plus
(require 'ido-completing-read+)
(ido-ubiquitous-mode 1)
;; Ivy
(ivy-mode)
(counsel-mode)
(counsel-projectile-mode)
(setq ivy-use-virtual-buffers t)
(setq enable-recursive-minibuffers t)
(setq search-default-mode #'char-fold-to-regexp)
(global-set-key "\C-s" 'swiper)
;; Treemacs
(require 'treemacs)
(treemacs-follow-mode t)
(treemacs-filewatch-mode t)
(treemacs-fringe-indicator-mode t)
(setq treemacs-show-cursor t)
(setq treemacs-width 32)
(define-key treemacs-mode-map [mouse-1] #'treemacs-single-click-expand-action)
(define-key global-map (kbd "M-0") 'treemacs-select-window)
;; Treemacs All The Icons
(require 'treemacs-all-the-icons)
(treemacs-load-theme "all-the-icons")
;; Treemacs Projectile
(require 'treemacs-projectile)
;; Company
(add-hook 'after-init-hook 'global-company-mode)
(setq company-idle-delay 0)
(setq company-minimum-prefix-length 1)
(setq company-show-numbers t)
;; Which Key
(which-key-mode)
;; YASnippet
(yas-global-mode 1)
(defvar my-company-point nil)
(advice-add 'company-complete-common
:before (lambda () (setq my-company-point (point))))
(advice-add 'company-complete-common
:after (lambda ()
(when (equal my-company-point (point))
(yas-expand))))
;; LSP
(add-hook 'c-mode-hook 'lsp)
(add-hook 'c++-mode-hook 'lsp)
(add-hook 'go-mode-hook 'lsp)
(require 'lsp-java)
(add-hook 'java-mode-hook #'lsp)
(add-hook 'js-mode-hook 'lsp)
(require 'lsp-python-ms)
(setq lsp-python-ms-auto-install-server t)
(add-hook 'python-mode-hook #'lsp)
(use-package lsp-python-ms
:ensure t
:init (setq lsp-python-ms-auto-install-server t)
:hook (python-mode . (lambda ()
(require 'lsp-python-ms)
(lsp))))
(add-hook 'rust-mode-hook 'lsp)
(add-hook 'latex-mode-hook 'lsp)
(add-hook 'markdown-mode-hook 'lsp)
(setq lsp-clients-clangd-args
'("--header-insertion=never"
"--header-insertion-decorators=0"))
(with-eval-after-load 'lsp-mode
(add-hook 'lsp-mode-hook #'lsp-enable-which-key-integration)
(require 'dap-cpptools)
(yas-global-mode))
;; Flycheck
(add-hook 'c-mode-hook #'flycheck-mode)
(add-hook 'c++-mode-hook #'flycheck-mode)
(add-hook 'go-mode-hook #'flycheck-mode)
(add-hook 'java-mode-hook #'flycheck-mode)
(add-hook 'js-mode-hook #'flycheck-mode)
(add-hook 'python-mode-hook #'flycheck-mode)
(add-hook 'rust-mode-hook #'flycheck-mode)
;; Smartparens
(require 'smartparens-config)
(add-hook 'asm-mode-hook #'smartparens-mode)
(add-hook 'c-mode-hook #'smartparens-mode)
(add-hook 'c++-mode-hook #'smartparens-mode)
(add-hook 'emacs-lisp-mode-hook #'smartparens-mode)
(add-hook 'go-mode-hook #'smartparens-mode)
(add-hook 'java-mode-hook #'smartparens-mode)
(add-hook 'js-mode-hook #'smartparens-mode)
(add-hook 'python-mode-hook #'smartparens-mode)
(add-hook 'rust-mode-hook #'smartparens-mode)
(add-hook 'rustic-mode-hook #'smartparens-mode)
(add-hook 'verilog-mode #'smartparens-mode)
;; When you press RET, the curly braces automatically add another newline.
(sp-with-modes '(asm-mode c-mode c++-mode emacs-lisp-mode java-mode js-mode python-mode rust-mode rustic-mode verilog-mode)
(sp-local-pair "{" nil :post-handlers '(("||\n[i]" "RET")))
(sp-local-pair "/*" "*/" :post-handlers '(("| " "SPC") ("* ||\n[i]" "RET"))))
(setq sp-escape-quotes-after-insert nil)
;; Windmove
(when (fboundp 'windmove-default-keybindings)
(windmove-default-keybindings))
;; Ace Window
(global-set-key (kbd "M-o") 'ace-window)
;; Winner
(when (fboundp 'winner-mode)
(winner-mode 1))
;; Alarm Bell
(setq ring-bell-function 'ignore)
;; Window Resize
(global-set-key (kbd "S-C-<left>") 'shrink-window-horizontally)
(global-set-key (kbd "S-C-<right>") 'enlarge-window-horizontally)
(global-set-key (kbd "S-C-<down>") 'shrink-window)
(global-set-key (kbd "S-C-<up>") 'enlarge-window)
;; Line Number Mode
(if (version<= "26.0.50" emacs-version)
(global-display-line-numbers-mode)
(global-linum-mode 1))
;; Column Number Mode
(column-number-mode 1)
;; Start Emacs in fullscreen mode
(add-hook 'emacs-startup-hook 'toggle-frame-fullscreen)
;; Place auto-save files into system's temporary file
(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))
;; Delete Selection Mode
(delete-selection-mode 1)
;; No Tabs
(setq-default indent-tabs-mode nil)
;; Org Mode
(eval-after-load "org"
'(require 'ox-md nil t))
(setq org-adapt-indentation nil)
;; CC Mode
(require 'cc-mode)
(setq c-default-style "user")
;; Rust Mode
(require 'rust-mode)
(setq rust-format-on-save t)
(define-key rust-mode-map (kbd "C-c C-c") 'rust-run)
;; Rustic Mode
(use-package rustic)
;; JavaScript Mode
(setq-default js-indent-level 2)
;; CSS Mode
(setq-default css-indent-offset 2)
|
[
{
"context": "07-2015 Free Software Foundation, Inc.\n\n;; Author: Daiki Ueno <ueno@unixuser.org>\n;;\tKenichi OKADA <okada@opaop",
"end": 158,
"score": 0.999887228012085,
"start": 148,
"tag": "NAME",
"value": "Daiki Ueno"
},
{
"context": "Software Foundation, Inc.\n\n;; Author: Daiki Ueno <ueno@unixuser.org>\n;;\tKenichi OKADA <okada@opaopa.org>\n;; Keywords:",
"end": 177,
"score": 0.9999288320541382,
"start": 160,
"tag": "EMAIL",
"value": "ueno@unixuser.org"
},
{
"context": "nc.\n\n;; Author: Daiki Ueno <ueno@unixuser.org>\n;;\tKenichi OKADA <okada@opaopa.org>\n;; Keywords: SASL, DIGEST-MD5\n",
"end": 195,
"score": 0.9998855590820312,
"start": 182,
"tag": "NAME",
"value": "Kenichi OKADA"
},
{
"context": " Daiki Ueno <ueno@unixuser.org>\n;;\tKenichi OKADA <okada@opaopa.org>\n;; Keywords: SASL, DIGEST-MD5\n;; Package: sasl\n\n",
"end": 213,
"score": 0.9999313354492188,
"start": 197,
"tag": "EMAIL",
"value": "okada@opaopa.org"
}
] | emacs-24.5/lisp/net/sasl-digest.el | emacslisp/emacs | 0 | ;;; sasl-digest.el --- DIGEST-MD5 module for the SASL client framework
;; Copyright (C) 2000, 2007-2015 Free Software Foundation, Inc.
;; Author: Daiki Ueno <ueno@unixuser.org>
;; Kenichi OKADA <okada@opaopa.org>
;; Keywords: SASL, DIGEST-MD5
;; Package: sasl
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This program is implemented from draft-leach-digest-sasl-05.txt.
;;
;; It is caller's responsibility to base64-decode challenges and
;; base64-encode responses in IMAP4 AUTHENTICATE command.
;;
;; Passphrase should be longer than 16 bytes. (See RFC 2195)
;;; Commentary:
(require 'sasl)
(require 'hmac-md5)
(defvar sasl-digest-md5-nonce-count 1)
(defvar sasl-digest-md5-unique-id-function
sasl-unique-id-function)
(defvar sasl-digest-md5-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?= "." table)
(modify-syntax-entry ?, "." table)
table)
"A syntax table for parsing digest-challenge attributes.")
(defconst sasl-digest-md5-steps
'(ignore ;no initial response
sasl-digest-md5-response
ignore)) ;""
(defun sasl-digest-md5-parse-string (string)
"Parse STRING and return a property list.
The value is a cons cell of the form \(realm nonce qop-options stale maxbuf
charset algorithm cipher-opts auth-param)."
(with-temp-buffer
(set-syntax-table sasl-digest-md5-syntax-table)
(save-excursion
(insert string)
(goto-char (point-min))
(insert "(")
(while (progn (forward-sexp) (not (eobp)))
(delete-char 1)
(insert " "))
(insert ")")
(read (point-min-marker)))))
(defun sasl-digest-md5-digest-uri (serv-type host &optional serv-name)
(concat serv-type "/" host
(if (and serv-name
(not (string= host serv-name)))
(concat "/" serv-name))))
(defun sasl-digest-md5-cnonce ()
(let ((sasl-unique-id-function sasl-digest-md5-unique-id-function))
(sasl-unique-id)))
(defun sasl-digest-md5-response-value (username
realm
nonce
cnonce
nonce-count
qop
digest-uri
authzid)
(let ((passphrase
(sasl-read-passphrase
(format "DIGEST-MD5 passphrase for %s: "
username))))
(unwind-protect
(encode-hex-string
(md5-binary
(concat
(encode-hex-string
(md5-binary (concat (md5-binary
(concat username ":" realm ":" passphrase))
":" nonce ":" cnonce
(if authzid
(concat ":" authzid)))))
":" nonce
":" (format "%08x" nonce-count) ":" cnonce ":" qop ":"
(encode-hex-string
(md5-binary
(concat "AUTHENTICATE:" digest-uri
(if (member qop '("auth-int" "auth-conf"))
":00000000000000000000000000000000")))))))
(fillarray passphrase 0))))
(defun sasl-digest-md5-response (client step)
(let* ((plist
(sasl-digest-md5-parse-string (sasl-step-data step)))
(realm
(or (sasl-client-property client 'realm)
(plist-get plist 'realm))) ;need to check
(nonce-count
(or (sasl-client-property client 'nonce-count)
sasl-digest-md5-nonce-count))
(qop
(or (sasl-client-property client 'qop)
"auth"))
(digest-uri
(sasl-digest-md5-digest-uri
(sasl-client-service client)(sasl-client-server client)))
(cnonce
(or (sasl-client-property client 'cnonce)
(sasl-digest-md5-cnonce))))
(sasl-client-set-property client 'nonce-count (1+ nonce-count))
(unless (string= qop "auth")
(sasl-error (format "Unsupported \"qop-value\": %s" qop)))
(concat
"username=\"" (sasl-client-name client) "\","
"realm=\"" realm "\","
"nonce=\"" (plist-get plist 'nonce) "\","
"cnonce=\"" cnonce "\","
(format "nc=%08x," nonce-count)
"digest-uri=\"" digest-uri "\","
"qop=" qop ","
"response="
(sasl-digest-md5-response-value
(sasl-client-name client)
realm
(plist-get plist 'nonce)
cnonce
nonce-count
qop
digest-uri
(plist-get plist 'authzid)))))
(put 'sasl-digest 'sasl-mechanism
(sasl-make-mechanism "DIGEST-MD5" sasl-digest-md5-steps))
(provide 'sasl-digest)
;;; sasl-digest.el ends here
| 5674 | ;;; sasl-digest.el --- DIGEST-MD5 module for the SASL client framework
;; Copyright (C) 2000, 2007-2015 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; Keywords: SASL, DIGEST-MD5
;; Package: sasl
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This program is implemented from draft-leach-digest-sasl-05.txt.
;;
;; It is caller's responsibility to base64-decode challenges and
;; base64-encode responses in IMAP4 AUTHENTICATE command.
;;
;; Passphrase should be longer than 16 bytes. (See RFC 2195)
;;; Commentary:
(require 'sasl)
(require 'hmac-md5)
(defvar sasl-digest-md5-nonce-count 1)
(defvar sasl-digest-md5-unique-id-function
sasl-unique-id-function)
(defvar sasl-digest-md5-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?= "." table)
(modify-syntax-entry ?, "." table)
table)
"A syntax table for parsing digest-challenge attributes.")
(defconst sasl-digest-md5-steps
'(ignore ;no initial response
sasl-digest-md5-response
ignore)) ;""
(defun sasl-digest-md5-parse-string (string)
"Parse STRING and return a property list.
The value is a cons cell of the form \(realm nonce qop-options stale maxbuf
charset algorithm cipher-opts auth-param)."
(with-temp-buffer
(set-syntax-table sasl-digest-md5-syntax-table)
(save-excursion
(insert string)
(goto-char (point-min))
(insert "(")
(while (progn (forward-sexp) (not (eobp)))
(delete-char 1)
(insert " "))
(insert ")")
(read (point-min-marker)))))
(defun sasl-digest-md5-digest-uri (serv-type host &optional serv-name)
(concat serv-type "/" host
(if (and serv-name
(not (string= host serv-name)))
(concat "/" serv-name))))
(defun sasl-digest-md5-cnonce ()
(let ((sasl-unique-id-function sasl-digest-md5-unique-id-function))
(sasl-unique-id)))
(defun sasl-digest-md5-response-value (username
realm
nonce
cnonce
nonce-count
qop
digest-uri
authzid)
(let ((passphrase
(sasl-read-passphrase
(format "DIGEST-MD5 passphrase for %s: "
username))))
(unwind-protect
(encode-hex-string
(md5-binary
(concat
(encode-hex-string
(md5-binary (concat (md5-binary
(concat username ":" realm ":" passphrase))
":" nonce ":" cnonce
(if authzid
(concat ":" authzid)))))
":" nonce
":" (format "%08x" nonce-count) ":" cnonce ":" qop ":"
(encode-hex-string
(md5-binary
(concat "AUTHENTICATE:" digest-uri
(if (member qop '("auth-int" "auth-conf"))
":00000000000000000000000000000000")))))))
(fillarray passphrase 0))))
(defun sasl-digest-md5-response (client step)
(let* ((plist
(sasl-digest-md5-parse-string (sasl-step-data step)))
(realm
(or (sasl-client-property client 'realm)
(plist-get plist 'realm))) ;need to check
(nonce-count
(or (sasl-client-property client 'nonce-count)
sasl-digest-md5-nonce-count))
(qop
(or (sasl-client-property client 'qop)
"auth"))
(digest-uri
(sasl-digest-md5-digest-uri
(sasl-client-service client)(sasl-client-server client)))
(cnonce
(or (sasl-client-property client 'cnonce)
(sasl-digest-md5-cnonce))))
(sasl-client-set-property client 'nonce-count (1+ nonce-count))
(unless (string= qop "auth")
(sasl-error (format "Unsupported \"qop-value\": %s" qop)))
(concat
"username=\"" (sasl-client-name client) "\","
"realm=\"" realm "\","
"nonce=\"" (plist-get plist 'nonce) "\","
"cnonce=\"" cnonce "\","
(format "nc=%08x," nonce-count)
"digest-uri=\"" digest-uri "\","
"qop=" qop ","
"response="
(sasl-digest-md5-response-value
(sasl-client-name client)
realm
(plist-get plist 'nonce)
cnonce
nonce-count
qop
digest-uri
(plist-get plist 'authzid)))))
(put 'sasl-digest 'sasl-mechanism
(sasl-make-mechanism "DIGEST-MD5" sasl-digest-md5-steps))
(provide 'sasl-digest)
;;; sasl-digest.el ends here
| true | ;;; sasl-digest.el --- DIGEST-MD5 module for the SASL client framework
;; Copyright (C) 2000, 2007-2015 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: SASL, DIGEST-MD5
;; Package: sasl
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This program is implemented from draft-leach-digest-sasl-05.txt.
;;
;; It is caller's responsibility to base64-decode challenges and
;; base64-encode responses in IMAP4 AUTHENTICATE command.
;;
;; Passphrase should be longer than 16 bytes. (See RFC 2195)
;;; Commentary:
(require 'sasl)
(require 'hmac-md5)
(defvar sasl-digest-md5-nonce-count 1)
(defvar sasl-digest-md5-unique-id-function
sasl-unique-id-function)
(defvar sasl-digest-md5-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?= "." table)
(modify-syntax-entry ?, "." table)
table)
"A syntax table for parsing digest-challenge attributes.")
(defconst sasl-digest-md5-steps
'(ignore ;no initial response
sasl-digest-md5-response
ignore)) ;""
(defun sasl-digest-md5-parse-string (string)
"Parse STRING and return a property list.
The value is a cons cell of the form \(realm nonce qop-options stale maxbuf
charset algorithm cipher-opts auth-param)."
(with-temp-buffer
(set-syntax-table sasl-digest-md5-syntax-table)
(save-excursion
(insert string)
(goto-char (point-min))
(insert "(")
(while (progn (forward-sexp) (not (eobp)))
(delete-char 1)
(insert " "))
(insert ")")
(read (point-min-marker)))))
(defun sasl-digest-md5-digest-uri (serv-type host &optional serv-name)
(concat serv-type "/" host
(if (and serv-name
(not (string= host serv-name)))
(concat "/" serv-name))))
(defun sasl-digest-md5-cnonce ()
(let ((sasl-unique-id-function sasl-digest-md5-unique-id-function))
(sasl-unique-id)))
(defun sasl-digest-md5-response-value (username
realm
nonce
cnonce
nonce-count
qop
digest-uri
authzid)
(let ((passphrase
(sasl-read-passphrase
(format "DIGEST-MD5 passphrase for %s: "
username))))
(unwind-protect
(encode-hex-string
(md5-binary
(concat
(encode-hex-string
(md5-binary (concat (md5-binary
(concat username ":" realm ":" passphrase))
":" nonce ":" cnonce
(if authzid
(concat ":" authzid)))))
":" nonce
":" (format "%08x" nonce-count) ":" cnonce ":" qop ":"
(encode-hex-string
(md5-binary
(concat "AUTHENTICATE:" digest-uri
(if (member qop '("auth-int" "auth-conf"))
":00000000000000000000000000000000")))))))
(fillarray passphrase 0))))
(defun sasl-digest-md5-response (client step)
(let* ((plist
(sasl-digest-md5-parse-string (sasl-step-data step)))
(realm
(or (sasl-client-property client 'realm)
(plist-get plist 'realm))) ;need to check
(nonce-count
(or (sasl-client-property client 'nonce-count)
sasl-digest-md5-nonce-count))
(qop
(or (sasl-client-property client 'qop)
"auth"))
(digest-uri
(sasl-digest-md5-digest-uri
(sasl-client-service client)(sasl-client-server client)))
(cnonce
(or (sasl-client-property client 'cnonce)
(sasl-digest-md5-cnonce))))
(sasl-client-set-property client 'nonce-count (1+ nonce-count))
(unless (string= qop "auth")
(sasl-error (format "Unsupported \"qop-value\": %s" qop)))
(concat
"username=\"" (sasl-client-name client) "\","
"realm=\"" realm "\","
"nonce=\"" (plist-get plist 'nonce) "\","
"cnonce=\"" cnonce "\","
(format "nc=%08x," nonce-count)
"digest-uri=\"" digest-uri "\","
"qop=" qop ","
"response="
(sasl-digest-md5-response-value
(sasl-client-name client)
realm
(plist-get plist 'nonce)
cnonce
nonce-count
qop
digest-uri
(plist-get plist 'authzid)))))
(put 'sasl-digest 'sasl-mechanism
(sasl-make-mechanism "DIGEST-MD5" sasl-digest-md5-steps))
(provide 'sasl-digest)
;;; sasl-digest.el ends here
|
[
{
"context": " -*- lexical-binding: t -*-\n\n;; Copyright (C) 2020 Ioannis Canellos\n;; \n;; \n;; Licensed under the Apache License,",
"end": 99,
"score": 0.9998750686645508,
"start": 83,
"tag": "NAME",
"value": "Ioannis Canellos"
},
{
"context": " limitations under the License.\n;; \n\n\n\n\n;; Author: Ioannis Canellos\n\n;; Version: 0.0.1\n\n;; Package-Requires: ((emacs ",
"end": 708,
"score": 0.9998764991760254,
"start": 692,
"tag": "NAME",
"value": "Ioannis Canellos"
}
] | quickmarks.el | iocanel/quickmarks.el | 0 | ;;; quickmarks.el --- quickmarks -*- lexical-binding: t -*-
;; Copyright (C) 2020 Ioannis Canellos
;;
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Author: Ioannis Canellos
;; Version: 0.0.1
;; Package-Requires: ((emacs "27.1"))
;;; Commentary:
;;; Code:
;;
;; Quickmarks
;;
;;
;; Quickmarks is a convention created on top of org-mode that allows you to easily insert org links and images in org files (and not only) ...
;; The idea is that you create rich bookmarks in org-mode that are tagged with 'quickmark' (customizable) and use quickmark functions and snippets to easily use them as you are typing.
;; These entries may include properties for:
;; - url: QM_URL (customizable)
;; - logo: QM_LOGO (customizable)
;; - avatar: QM_AVATAR (customizable)
;;
(require 'rx)
(defcustom qm-url "QM_URL" "The property key for the quickmark url." :group 'quickmarks)
(defcustom qm-logo "QM_LOGO" "The property key for the quickmark logo." :group 'quickmarks)
(defcustom qm-avatar "QM_AVATAR" "The property key for the quickmark avatar." :group 'quickmarks)
(defcustom qm-tag "quickmark" "The property key for the quickmark entry." :group 'quickmarks)
(defcustom qm-src-dir nil "The path to quickmark sources. If not specified detection will be attempted." :group 'quickmarks)
;; Capturing customization: Only applicable to capturing, querying doesn't require a fixed file or structure.
(defcustom qm-org-capture-template-dir "~/Documents/org/templates/" "The directory the template is going to installed." :group 'quickmarks)
(defcustom qm-org-capture-file "~/Documents/org/roam/quickmarks.org" "The file to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-key-chord "Q" "The key chord to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-heading "Quickmakrs" "The heading under which quickmarks will be captured." :group 'quickmarks)
(defconst qm-org-capture-template-file-name "quickmarks.orgtmpl" "The file name of the quickmarks template.")
(defun qm-all-entries ()
"Find all quickmarks."
(interactive)
(let* ((entries (org-ql-query
:select ,(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo)
(org-entry-get (point) ,qm-avatar))
:from (org-agenda-files)
:where `(tags ,qm-tag))))
entries))
(defun qm-entry-by-name (name)
"Find a quickmark entry by name."
(interactive)
(let* ((entries (org-ql-query
:select `(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo))
:from (org-agenda-files)
:where `(and (regexp ,name) (tags ,qm-tag)))))
(car entries)))
(defun qm-url-by-name (name)
"Find a quickmark url entry by name."
(nth 1 (qm-entry-by-name name)))
(defun qm-logo-by-name (name)
"Find a quickmark logo entry by name."
(nth 2 (qm-entry-by-name name)))
(defun qm-avatar-by-name (name)
"Find a quickmark avatar entry by name."
(nth 3 (qm-entry-by-name name)))
(defun qm--link-to-qm (link)
"Converts an org-mode LINK to a quickmark entry."
(let* ((path (org-element-property :path link))
(type (org-element-property :type link))
(url (concat type ":" path))
(entry (nth 2 link))
(description (if entry (substring-no-properties (nth 2 link)) nil)))
(if description (list description url nil nil) nil)))
(defun qm--collect-quickmarks-from-file (file)
"Collects all links from the SPECIIFED file and returns a list of quickmark entries."
(cond ((string-suffix-p ".org" file) (qm--collect-quickmarks-from-org-file file))
((string-suffix-p ".md" file) (qm--collect-quickmarks-from-markdown-file file))
(:else nil)))
(defun qm--collect-quickmarks-from-org-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(org-mode)
(org-element-map (org-element-parse-buffer) 'link 'qm--link-to-qm)))
(defun qm--collect-quickmarks-from-markdown-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(goto-char (point-min))
(while (re-search-forward
(rx "[" (group (one-or-more (or word space))) "]" "(" (group (or "http://" "https://" (one-or-more (or alnum "." ":" "/")))) ")")
nil t)
(let ((url (match-string 1))
(description (match-string 2)))
(list description url nil nil)))))
(defun qm--collect-quickmarks-from-directory (dir)
(let ((path (file-truename dir)))
(mapcar 'qm--collect-quickmarks-from-file (directory-files-recursively dir (rx (sequence "." (or "org" "md") eol)) t))))
(defun qm-populate-from-dir ()
"Populate quickmarks that are found in the directory."
(interactive)
(let* ((dir (car (find-file-read-args "Serach for quickmarks in directory:" nil)))
(quickmark-list (qm--collect-quickmarks-from-directory dir)))
(mapcar (lambda (f)
(when f (mapcar (lambda (q)
(qm-create (capitalize (nth 0 q)) (nth 1 q) (nth 3 q) (nth 4 q))) f)))
quickmark-list)))
(defun qm-create(heading url logo avatar)
"Create a new quickmark. The quickmark will be an entry the specified HEADING.
Optionally a property will be added for the specified URL LOGO and AVATAR. "
(save-excursion
(with-temp-buffer
(insert-file qm-org-capture-file)
(goto-char (point-max))
(when (not (re-search-backward (rx-to-string `(: bol "**" (one-or-more space) ,heading (one-or-more space) (zero-or-more ":" word) ":quickmark:")) nil t))
(insert (concat "\n" "**" " " heading " " ":quickmark:"))
(when url (org-entry-put (point) qm-url url))
(when logo (org-entry-put (point) qm-logo logo))
(when avatar (org-entry-put (point) qm-avatar avatar))
(goto-char (point-max))
(write-file qm-org-capture-file)))))
;;
;; Initialization & Setup
;;
(defun qm--find-source-dir ()
"Find the source dir of the project."
(if qm-src-dir
qm-src-dir
(progn
(setq qm-src-dir (replace-regexp-in-string (regexp-quote "straight/build/idee") "straight/repos/idee"
(file-name-directory
;; Copied from ‘yasnippet-snippets’ that copied from ‘f-this-file’ from f.el.
(cond (load-in-progress load-file-name) ((and (boundp 'byte-compile-current-file) byte-compile-current-file) byte-compile-current-file)
(:else (buffer-file-name))))))
qm-src-dir)))
(defun qm--install-template ()
"Install the template to the template directory."
(let* ((src (qm--find-source-dir))
(src-template (concat (file-name-as-directory src) qm-org-capture-template-file-name))
(target-template (concat (file-name-as-directory qm-org-capture-template-dir) qm-org-capture-template-file-name)))
(when (not (file-exists-p src)) (make-directory src t))
(copy-file src-template target-template t)))
(defun qm--install-snippets ()
"Install the snippets to the emacs snippet directory."
(let* ((src (qm--find-source-dir))
(src-snippet-dir (file-name-as-directory (concat (file-name-as-directory src) "snippets")))
(src-org-mode-snippet-dir (file-name-as-directory (concat src-snippet-dir "org-mode")))
(target-snippet-dir (concat (file-name-as-directory user-emacs-directory) "snippets"))
(target-org-mode-snippet-dir (file-name-as-directory (concat (file-name-as-directory target-snippet-dir) "org-mode"))))
(when (not (file-exists-p target-org-mode-snippet-dir)) (make-directory target-org-mode-snippet-dir t))
(mapcar (lambda (f) (copy-file f (concat target-org-mode-snippet-dir (file-name-nondirectory f))))
(seq-filter (lambda (f) (not (string-suffix-p "." f))) (directory-files src-org-mode-snippet-dir t)))))
(defun qm--register-template()
"Register the capture template for quickmarks."
(let ((template-file (concat qm-org-capture-template-dir qm-org-capture-template-file-name)))
(setq org-capture-templates (append org-capture-templates `((,qm-org-capture-key-chord "Quickmarks" entry (file+olp ,qm-org-capture-file "Quickmarks") (file ,template-file)))))))
(defun qm-install()
(interactive)
"Install templates and snippets."
(qm--install-snippets)
(qm--install-template))
(defun qm-init()
(interactive)
"Initialize quickmarks."
(qm--register-template))
(provide 'quickmarks)
;;; quickmarks.el ends here
| 49375 | ;;; quickmarks.el --- quickmarks -*- lexical-binding: t -*-
;; Copyright (C) 2020 <NAME>
;;
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Author: <NAME>
;; Version: 0.0.1
;; Package-Requires: ((emacs "27.1"))
;;; Commentary:
;;; Code:
;;
;; Quickmarks
;;
;;
;; Quickmarks is a convention created on top of org-mode that allows you to easily insert org links and images in org files (and not only) ...
;; The idea is that you create rich bookmarks in org-mode that are tagged with 'quickmark' (customizable) and use quickmark functions and snippets to easily use them as you are typing.
;; These entries may include properties for:
;; - url: QM_URL (customizable)
;; - logo: QM_LOGO (customizable)
;; - avatar: QM_AVATAR (customizable)
;;
(require 'rx)
(defcustom qm-url "QM_URL" "The property key for the quickmark url." :group 'quickmarks)
(defcustom qm-logo "QM_LOGO" "The property key for the quickmark logo." :group 'quickmarks)
(defcustom qm-avatar "QM_AVATAR" "The property key for the quickmark avatar." :group 'quickmarks)
(defcustom qm-tag "quickmark" "The property key for the quickmark entry." :group 'quickmarks)
(defcustom qm-src-dir nil "The path to quickmark sources. If not specified detection will be attempted." :group 'quickmarks)
;; Capturing customization: Only applicable to capturing, querying doesn't require a fixed file or structure.
(defcustom qm-org-capture-template-dir "~/Documents/org/templates/" "The directory the template is going to installed." :group 'quickmarks)
(defcustom qm-org-capture-file "~/Documents/org/roam/quickmarks.org" "The file to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-key-chord "Q" "The key chord to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-heading "Quickmakrs" "The heading under which quickmarks will be captured." :group 'quickmarks)
(defconst qm-org-capture-template-file-name "quickmarks.orgtmpl" "The file name of the quickmarks template.")
(defun qm-all-entries ()
"Find all quickmarks."
(interactive)
(let* ((entries (org-ql-query
:select ,(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo)
(org-entry-get (point) ,qm-avatar))
:from (org-agenda-files)
:where `(tags ,qm-tag))))
entries))
(defun qm-entry-by-name (name)
"Find a quickmark entry by name."
(interactive)
(let* ((entries (org-ql-query
:select `(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo))
:from (org-agenda-files)
:where `(and (regexp ,name) (tags ,qm-tag)))))
(car entries)))
(defun qm-url-by-name (name)
"Find a quickmark url entry by name."
(nth 1 (qm-entry-by-name name)))
(defun qm-logo-by-name (name)
"Find a quickmark logo entry by name."
(nth 2 (qm-entry-by-name name)))
(defun qm-avatar-by-name (name)
"Find a quickmark avatar entry by name."
(nth 3 (qm-entry-by-name name)))
(defun qm--link-to-qm (link)
"Converts an org-mode LINK to a quickmark entry."
(let* ((path (org-element-property :path link))
(type (org-element-property :type link))
(url (concat type ":" path))
(entry (nth 2 link))
(description (if entry (substring-no-properties (nth 2 link)) nil)))
(if description (list description url nil nil) nil)))
(defun qm--collect-quickmarks-from-file (file)
"Collects all links from the SPECIIFED file and returns a list of quickmark entries."
(cond ((string-suffix-p ".org" file) (qm--collect-quickmarks-from-org-file file))
((string-suffix-p ".md" file) (qm--collect-quickmarks-from-markdown-file file))
(:else nil)))
(defun qm--collect-quickmarks-from-org-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(org-mode)
(org-element-map (org-element-parse-buffer) 'link 'qm--link-to-qm)))
(defun qm--collect-quickmarks-from-markdown-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(goto-char (point-min))
(while (re-search-forward
(rx "[" (group (one-or-more (or word space))) "]" "(" (group (or "http://" "https://" (one-or-more (or alnum "." ":" "/")))) ")")
nil t)
(let ((url (match-string 1))
(description (match-string 2)))
(list description url nil nil)))))
(defun qm--collect-quickmarks-from-directory (dir)
(let ((path (file-truename dir)))
(mapcar 'qm--collect-quickmarks-from-file (directory-files-recursively dir (rx (sequence "." (or "org" "md") eol)) t))))
(defun qm-populate-from-dir ()
"Populate quickmarks that are found in the directory."
(interactive)
(let* ((dir (car (find-file-read-args "Serach for quickmarks in directory:" nil)))
(quickmark-list (qm--collect-quickmarks-from-directory dir)))
(mapcar (lambda (f)
(when f (mapcar (lambda (q)
(qm-create (capitalize (nth 0 q)) (nth 1 q) (nth 3 q) (nth 4 q))) f)))
quickmark-list)))
(defun qm-create(heading url logo avatar)
"Create a new quickmark. The quickmark will be an entry the specified HEADING.
Optionally a property will be added for the specified URL LOGO and AVATAR. "
(save-excursion
(with-temp-buffer
(insert-file qm-org-capture-file)
(goto-char (point-max))
(when (not (re-search-backward (rx-to-string `(: bol "**" (one-or-more space) ,heading (one-or-more space) (zero-or-more ":" word) ":quickmark:")) nil t))
(insert (concat "\n" "**" " " heading " " ":quickmark:"))
(when url (org-entry-put (point) qm-url url))
(when logo (org-entry-put (point) qm-logo logo))
(when avatar (org-entry-put (point) qm-avatar avatar))
(goto-char (point-max))
(write-file qm-org-capture-file)))))
;;
;; Initialization & Setup
;;
(defun qm--find-source-dir ()
"Find the source dir of the project."
(if qm-src-dir
qm-src-dir
(progn
(setq qm-src-dir (replace-regexp-in-string (regexp-quote "straight/build/idee") "straight/repos/idee"
(file-name-directory
;; Copied from ‘yasnippet-snippets’ that copied from ‘f-this-file’ from f.el.
(cond (load-in-progress load-file-name) ((and (boundp 'byte-compile-current-file) byte-compile-current-file) byte-compile-current-file)
(:else (buffer-file-name))))))
qm-src-dir)))
(defun qm--install-template ()
"Install the template to the template directory."
(let* ((src (qm--find-source-dir))
(src-template (concat (file-name-as-directory src) qm-org-capture-template-file-name))
(target-template (concat (file-name-as-directory qm-org-capture-template-dir) qm-org-capture-template-file-name)))
(when (not (file-exists-p src)) (make-directory src t))
(copy-file src-template target-template t)))
(defun qm--install-snippets ()
"Install the snippets to the emacs snippet directory."
(let* ((src (qm--find-source-dir))
(src-snippet-dir (file-name-as-directory (concat (file-name-as-directory src) "snippets")))
(src-org-mode-snippet-dir (file-name-as-directory (concat src-snippet-dir "org-mode")))
(target-snippet-dir (concat (file-name-as-directory user-emacs-directory) "snippets"))
(target-org-mode-snippet-dir (file-name-as-directory (concat (file-name-as-directory target-snippet-dir) "org-mode"))))
(when (not (file-exists-p target-org-mode-snippet-dir)) (make-directory target-org-mode-snippet-dir t))
(mapcar (lambda (f) (copy-file f (concat target-org-mode-snippet-dir (file-name-nondirectory f))))
(seq-filter (lambda (f) (not (string-suffix-p "." f))) (directory-files src-org-mode-snippet-dir t)))))
(defun qm--register-template()
"Register the capture template for quickmarks."
(let ((template-file (concat qm-org-capture-template-dir qm-org-capture-template-file-name)))
(setq org-capture-templates (append org-capture-templates `((,qm-org-capture-key-chord "Quickmarks" entry (file+olp ,qm-org-capture-file "Quickmarks") (file ,template-file)))))))
(defun qm-install()
(interactive)
"Install templates and snippets."
(qm--install-snippets)
(qm--install-template))
(defun qm-init()
(interactive)
"Initialize quickmarks."
(qm--register-template))
(provide 'quickmarks)
;;; quickmarks.el ends here
| true | ;;; quickmarks.el --- quickmarks -*- lexical-binding: t -*-
;; Copyright (C) 2020 PI:NAME:<NAME>END_PI
;;
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Author: PI:NAME:<NAME>END_PI
;; Version: 0.0.1
;; Package-Requires: ((emacs "27.1"))
;;; Commentary:
;;; Code:
;;
;; Quickmarks
;;
;;
;; Quickmarks is a convention created on top of org-mode that allows you to easily insert org links and images in org files (and not only) ...
;; The idea is that you create rich bookmarks in org-mode that are tagged with 'quickmark' (customizable) and use quickmark functions and snippets to easily use them as you are typing.
;; These entries may include properties for:
;; - url: QM_URL (customizable)
;; - logo: QM_LOGO (customizable)
;; - avatar: QM_AVATAR (customizable)
;;
(require 'rx)
(defcustom qm-url "QM_URL" "The property key for the quickmark url." :group 'quickmarks)
(defcustom qm-logo "QM_LOGO" "The property key for the quickmark logo." :group 'quickmarks)
(defcustom qm-avatar "QM_AVATAR" "The property key for the quickmark avatar." :group 'quickmarks)
(defcustom qm-tag "quickmark" "The property key for the quickmark entry." :group 'quickmarks)
(defcustom qm-src-dir nil "The path to quickmark sources. If not specified detection will be attempted." :group 'quickmarks)
;; Capturing customization: Only applicable to capturing, querying doesn't require a fixed file or structure.
(defcustom qm-org-capture-template-dir "~/Documents/org/templates/" "The directory the template is going to installed." :group 'quickmarks)
(defcustom qm-org-capture-file "~/Documents/org/roam/quickmarks.org" "The file to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-key-chord "Q" "The key chord to use for capturing quickmarks." :group 'quickmarks)
(defcustom qm-org-capture-heading "Quickmakrs" "The heading under which quickmarks will be captured." :group 'quickmarks)
(defconst qm-org-capture-template-file-name "quickmarks.orgtmpl" "The file name of the quickmarks template.")
(defun qm-all-entries ()
"Find all quickmarks."
(interactive)
(let* ((entries (org-ql-query
:select ,(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo)
(org-entry-get (point) ,qm-avatar))
:from (org-agenda-files)
:where `(tags ,qm-tag))))
entries))
(defun qm-entry-by-name (name)
"Find a quickmark entry by name."
(interactive)
(let* ((entries (org-ql-query
:select `(list (substring-no-properties (org-get-heading t t))
(org-entry-get (point) ,qm-url)
(org-entry-get (point) ,qm-logo))
:from (org-agenda-files)
:where `(and (regexp ,name) (tags ,qm-tag)))))
(car entries)))
(defun qm-url-by-name (name)
"Find a quickmark url entry by name."
(nth 1 (qm-entry-by-name name)))
(defun qm-logo-by-name (name)
"Find a quickmark logo entry by name."
(nth 2 (qm-entry-by-name name)))
(defun qm-avatar-by-name (name)
"Find a quickmark avatar entry by name."
(nth 3 (qm-entry-by-name name)))
(defun qm--link-to-qm (link)
"Converts an org-mode LINK to a quickmark entry."
(let* ((path (org-element-property :path link))
(type (org-element-property :type link))
(url (concat type ":" path))
(entry (nth 2 link))
(description (if entry (substring-no-properties (nth 2 link)) nil)))
(if description (list description url nil nil) nil)))
(defun qm--collect-quickmarks-from-file (file)
"Collects all links from the SPECIIFED file and returns a list of quickmark entries."
(cond ((string-suffix-p ".org" file) (qm--collect-quickmarks-from-org-file file))
((string-suffix-p ".md" file) (qm--collect-quickmarks-from-markdown-file file))
(:else nil)))
(defun qm--collect-quickmarks-from-org-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(org-mode)
(org-element-map (org-element-parse-buffer) 'link 'qm--link-to-qm)))
(defun qm--collect-quickmarks-from-markdown-file (file)
"Collects all links from the specified org FILE and returns a list of quickmark entries."
(with-temp-buffer
(insert-file file)
(goto-char (point-min))
(while (re-search-forward
(rx "[" (group (one-or-more (or word space))) "]" "(" (group (or "http://" "https://" (one-or-more (or alnum "." ":" "/")))) ")")
nil t)
(let ((url (match-string 1))
(description (match-string 2)))
(list description url nil nil)))))
(defun qm--collect-quickmarks-from-directory (dir)
(let ((path (file-truename dir)))
(mapcar 'qm--collect-quickmarks-from-file (directory-files-recursively dir (rx (sequence "." (or "org" "md") eol)) t))))
(defun qm-populate-from-dir ()
"Populate quickmarks that are found in the directory."
(interactive)
(let* ((dir (car (find-file-read-args "Serach for quickmarks in directory:" nil)))
(quickmark-list (qm--collect-quickmarks-from-directory dir)))
(mapcar (lambda (f)
(when f (mapcar (lambda (q)
(qm-create (capitalize (nth 0 q)) (nth 1 q) (nth 3 q) (nth 4 q))) f)))
quickmark-list)))
(defun qm-create(heading url logo avatar)
"Create a new quickmark. The quickmark will be an entry the specified HEADING.
Optionally a property will be added for the specified URL LOGO and AVATAR. "
(save-excursion
(with-temp-buffer
(insert-file qm-org-capture-file)
(goto-char (point-max))
(when (not (re-search-backward (rx-to-string `(: bol "**" (one-or-more space) ,heading (one-or-more space) (zero-or-more ":" word) ":quickmark:")) nil t))
(insert (concat "\n" "**" " " heading " " ":quickmark:"))
(when url (org-entry-put (point) qm-url url))
(when logo (org-entry-put (point) qm-logo logo))
(when avatar (org-entry-put (point) qm-avatar avatar))
(goto-char (point-max))
(write-file qm-org-capture-file)))))
;;
;; Initialization & Setup
;;
(defun qm--find-source-dir ()
"Find the source dir of the project."
(if qm-src-dir
qm-src-dir
(progn
(setq qm-src-dir (replace-regexp-in-string (regexp-quote "straight/build/idee") "straight/repos/idee"
(file-name-directory
;; Copied from ‘yasnippet-snippets’ that copied from ‘f-this-file’ from f.el.
(cond (load-in-progress load-file-name) ((and (boundp 'byte-compile-current-file) byte-compile-current-file) byte-compile-current-file)
(:else (buffer-file-name))))))
qm-src-dir)))
(defun qm--install-template ()
"Install the template to the template directory."
(let* ((src (qm--find-source-dir))
(src-template (concat (file-name-as-directory src) qm-org-capture-template-file-name))
(target-template (concat (file-name-as-directory qm-org-capture-template-dir) qm-org-capture-template-file-name)))
(when (not (file-exists-p src)) (make-directory src t))
(copy-file src-template target-template t)))
(defun qm--install-snippets ()
"Install the snippets to the emacs snippet directory."
(let* ((src (qm--find-source-dir))
(src-snippet-dir (file-name-as-directory (concat (file-name-as-directory src) "snippets")))
(src-org-mode-snippet-dir (file-name-as-directory (concat src-snippet-dir "org-mode")))
(target-snippet-dir (concat (file-name-as-directory user-emacs-directory) "snippets"))
(target-org-mode-snippet-dir (file-name-as-directory (concat (file-name-as-directory target-snippet-dir) "org-mode"))))
(when (not (file-exists-p target-org-mode-snippet-dir)) (make-directory target-org-mode-snippet-dir t))
(mapcar (lambda (f) (copy-file f (concat target-org-mode-snippet-dir (file-name-nondirectory f))))
(seq-filter (lambda (f) (not (string-suffix-p "." f))) (directory-files src-org-mode-snippet-dir t)))))
(defun qm--register-template()
"Register the capture template for quickmarks."
(let ((template-file (concat qm-org-capture-template-dir qm-org-capture-template-file-name)))
(setq org-capture-templates (append org-capture-templates `((,qm-org-capture-key-chord "Quickmarks" entry (file+olp ,qm-org-capture-file "Quickmarks") (file ,template-file)))))))
(defun qm-install()
(interactive)
"Install templates and snippets."
(qm--install-snippets)
(qm--install-template))
(defun qm-init()
(interactive)
"Initialize quickmarks."
(qm--register-template))
(provide 'quickmarks)
;;; quickmarks.el ends here
|
[
{
"context": "01-2015 Free Software Foundation, Inc.\n\n;; Author: K. Shane Hartman\n;; Maintainer: emacs-devel@gnu.org\n;; Keywords: c",
"end": 134,
"score": 0.9998385310173035,
"start": 118,
"tag": "NAME",
"value": "K. Shane Hartman"
},
{
"context": ", Inc.\n\n;; Author: K. Shane Hartman\n;; Maintainer: emacs-devel@gnu.org\n;; Keywords: convenience\n\n;; This file is part of",
"end": 169,
"score": 0.9999290704727173,
"start": 150,
"tag": "EMAIL",
"value": "emacs-devel@gnu.org"
}
] | emacs-24.5/lisp/chistory.el | emacslisp/emacs | 0 | ;;; chistory.el --- list command history
;; Copyright (C) 1985, 2001-2015 Free Software Foundation, Inc.
;; Author: K. Shane Hartman
;; Maintainer: emacs-devel@gnu.org
;; Keywords: convenience
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This really has nothing to do with list-command-history per se, but
;; its a nice alternative to C-x ESC ESC (repeat-complex-command) and
;; functions as a lister if given no pattern. It's not important
;; enough to warrant a file of its own.
;;; Code:
(defgroup chistory nil
"List command history."
:group 'keyboard)
;;;###autoload
(defun repeat-matching-complex-command (&optional pattern)
"Edit and re-evaluate complex command with name matching PATTERN.
Matching occurrences are displayed, most recent first, until you select
a form for evaluation. If PATTERN is empty (or nil), every form in the
command history is offered. The form is placed in the minibuffer for
editing and the result is evaluated."
(interactive "sRedo Command (regexp): ")
(if pattern
(if (string-match "[^ \t]" pattern)
(setq pattern (substring pattern (match-beginning 0)))
(setq pattern nil)))
(let ((history command-history)
(temp)
(what))
(while (and history (not what))
(setq temp (car history))
(if (and (or (not pattern) (string-match pattern (symbol-name (car temp))))
(y-or-n-p (format "Redo %S? " temp)))
(setq what (car history))
(setq history (cdr history))))
(if (not what)
(error "Command history exhausted")
;; Try to remove any useless command history element for this command.
(if (eq (car (car command-history)) 'repeat-matching-complex-command)
(setq command-history (cdr command-history)))
(edit-and-eval-command "Redo: " what))))
(defcustom default-command-history-filter-garbage
'(command-history-mode
list-command-history
electric-command-history)
"A list of symbols to be ignored by `default-command-history-filter'.
If that function is given a list whose car is an element of this list,
then it will return non-nil (indicating the list should be discarded from
the history).
Initially, all commands related to the command history are discarded."
:type '(repeat symbol)
:group 'chistory)
(defvar list-command-history-filter 'default-command-history-filter
"Predicate to test which commands should be excluded from the history listing.
If non-nil, should be the name of a function of one argument.
It is passed each element of the command history when
\\[list-command-history] is called. If the filter returns non-nil for
some element, that element is excluded from the history listing. The
default filter removes commands associated with the command-history.")
(defun default-command-history-filter (frob)
"Filter commands matching `default-command-history-filter-garbage' list
from the command history."
(or (not (consp frob))
(memq (car frob) default-command-history-filter-garbage)))
(defcustom list-command-history-max 32
"If non-nil, maximum length of the listing produced by `list-command-history'."
:type '(choice integer (const nil))
:group 'chistory)
;;;###autoload
(defun list-command-history ()
"List history of commands typed to minibuffer.
The number of commands listed is controlled by `list-command-history-max'.
Calls value of `list-command-history-filter' (if non-nil) on each history
element to judge if that element should be excluded from the list.
The buffer is left in Command History mode."
(interactive)
(with-output-to-temp-buffer
"*Command History*"
(let ((history command-history)
(buffer-read-only nil)
(count (or list-command-history-max -1)))
(while (and (/= count 0) history)
(if (and (bound-and-true-p list-command-history-filter)
(funcall list-command-history-filter (car history)))
nil
(setq count (1- count))
(prin1 (car history))
(terpri))
(setq history (cdr history))))
(with-current-buffer "*Command History*"
(goto-char (point-min))
(if (eobp)
(error "No command history")
(command-history-mode)))))
(define-obsolete-variable-alias 'command-history-map
'command-history-mode-map "24.1")
(defvar command-history-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map lisp-mode-shared-map)
(suppress-keymap map)
(define-key map "x" 'command-history-repeat)
(define-key map "\n" 'next-line)
(define-key map "\r" 'next-line)
(define-key map "\177" 'previous-line)
map)
"Keymap for `command-history-mode'.")
(define-derived-mode command-history-mode fundamental-mode "Command History"
"Major mode for listing and repeating recent commands.
Keybindings:
\\{command-history-mode-map}"
(lisp-mode-variables nil)
(set-syntax-table emacs-lisp-mode-syntax-table)
(setq buffer-read-only t))
(defcustom command-history-hook nil
"If non-nil, its value is called on entry to `command-history-mode'."
:type 'hook
:group 'chistory)
(defun command-history-repeat ()
"Repeat the command shown on the current line.
The buffer for that command is the previous current buffer."
(interactive)
(save-excursion
(eval (prog1
(save-excursion
(beginning-of-line)
(read (current-buffer)))
(set-buffer
(car (cdr (buffer-list))))))))
;;;###autoload
(defun command-history ()
"Examine commands from `command-history' in a buffer.
The number of commands listed is controlled by `list-command-history-max'.
The command history is filtered by `list-command-history-filter' if non-nil.
Use \\<command-history-map>\\[command-history-repeat] to repeat the command on the current line.
Otherwise much like Emacs-Lisp Mode except that there is no self-insertion
and digits provide prefix arguments. Tab does not indent.
\\{command-history-map}
This command always recompiles the Command History listing
and runs the normal hook `command-history-hook'."
(interactive)
(list-command-history)
(pop-to-buffer "*Command History*")
(run-hooks 'command-history-hook))
(provide 'chistory)
;;; chistory.el ends here
| 1366 | ;;; chistory.el --- list command history
;; Copyright (C) 1985, 2001-2015 Free Software Foundation, Inc.
;; Author: <NAME>
;; Maintainer: <EMAIL>
;; Keywords: convenience
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This really has nothing to do with list-command-history per se, but
;; its a nice alternative to C-x ESC ESC (repeat-complex-command) and
;; functions as a lister if given no pattern. It's not important
;; enough to warrant a file of its own.
;;; Code:
(defgroup chistory nil
"List command history."
:group 'keyboard)
;;;###autoload
(defun repeat-matching-complex-command (&optional pattern)
"Edit and re-evaluate complex command with name matching PATTERN.
Matching occurrences are displayed, most recent first, until you select
a form for evaluation. If PATTERN is empty (or nil), every form in the
command history is offered. The form is placed in the minibuffer for
editing and the result is evaluated."
(interactive "sRedo Command (regexp): ")
(if pattern
(if (string-match "[^ \t]" pattern)
(setq pattern (substring pattern (match-beginning 0)))
(setq pattern nil)))
(let ((history command-history)
(temp)
(what))
(while (and history (not what))
(setq temp (car history))
(if (and (or (not pattern) (string-match pattern (symbol-name (car temp))))
(y-or-n-p (format "Redo %S? " temp)))
(setq what (car history))
(setq history (cdr history))))
(if (not what)
(error "Command history exhausted")
;; Try to remove any useless command history element for this command.
(if (eq (car (car command-history)) 'repeat-matching-complex-command)
(setq command-history (cdr command-history)))
(edit-and-eval-command "Redo: " what))))
(defcustom default-command-history-filter-garbage
'(command-history-mode
list-command-history
electric-command-history)
"A list of symbols to be ignored by `default-command-history-filter'.
If that function is given a list whose car is an element of this list,
then it will return non-nil (indicating the list should be discarded from
the history).
Initially, all commands related to the command history are discarded."
:type '(repeat symbol)
:group 'chistory)
(defvar list-command-history-filter 'default-command-history-filter
"Predicate to test which commands should be excluded from the history listing.
If non-nil, should be the name of a function of one argument.
It is passed each element of the command history when
\\[list-command-history] is called. If the filter returns non-nil for
some element, that element is excluded from the history listing. The
default filter removes commands associated with the command-history.")
(defun default-command-history-filter (frob)
"Filter commands matching `default-command-history-filter-garbage' list
from the command history."
(or (not (consp frob))
(memq (car frob) default-command-history-filter-garbage)))
(defcustom list-command-history-max 32
"If non-nil, maximum length of the listing produced by `list-command-history'."
:type '(choice integer (const nil))
:group 'chistory)
;;;###autoload
(defun list-command-history ()
"List history of commands typed to minibuffer.
The number of commands listed is controlled by `list-command-history-max'.
Calls value of `list-command-history-filter' (if non-nil) on each history
element to judge if that element should be excluded from the list.
The buffer is left in Command History mode."
(interactive)
(with-output-to-temp-buffer
"*Command History*"
(let ((history command-history)
(buffer-read-only nil)
(count (or list-command-history-max -1)))
(while (and (/= count 0) history)
(if (and (bound-and-true-p list-command-history-filter)
(funcall list-command-history-filter (car history)))
nil
(setq count (1- count))
(prin1 (car history))
(terpri))
(setq history (cdr history))))
(with-current-buffer "*Command History*"
(goto-char (point-min))
(if (eobp)
(error "No command history")
(command-history-mode)))))
(define-obsolete-variable-alias 'command-history-map
'command-history-mode-map "24.1")
(defvar command-history-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map lisp-mode-shared-map)
(suppress-keymap map)
(define-key map "x" 'command-history-repeat)
(define-key map "\n" 'next-line)
(define-key map "\r" 'next-line)
(define-key map "\177" 'previous-line)
map)
"Keymap for `command-history-mode'.")
(define-derived-mode command-history-mode fundamental-mode "Command History"
"Major mode for listing and repeating recent commands.
Keybindings:
\\{command-history-mode-map}"
(lisp-mode-variables nil)
(set-syntax-table emacs-lisp-mode-syntax-table)
(setq buffer-read-only t))
(defcustom command-history-hook nil
"If non-nil, its value is called on entry to `command-history-mode'."
:type 'hook
:group 'chistory)
(defun command-history-repeat ()
"Repeat the command shown on the current line.
The buffer for that command is the previous current buffer."
(interactive)
(save-excursion
(eval (prog1
(save-excursion
(beginning-of-line)
(read (current-buffer)))
(set-buffer
(car (cdr (buffer-list))))))))
;;;###autoload
(defun command-history ()
"Examine commands from `command-history' in a buffer.
The number of commands listed is controlled by `list-command-history-max'.
The command history is filtered by `list-command-history-filter' if non-nil.
Use \\<command-history-map>\\[command-history-repeat] to repeat the command on the current line.
Otherwise much like Emacs-Lisp Mode except that there is no self-insertion
and digits provide prefix arguments. Tab does not indent.
\\{command-history-map}
This command always recompiles the Command History listing
and runs the normal hook `command-history-hook'."
(interactive)
(list-command-history)
(pop-to-buffer "*Command History*")
(run-hooks 'command-history-hook))
(provide 'chistory)
;;; chistory.el ends here
| true | ;;; chistory.el --- list command history
;; Copyright (C) 1985, 2001-2015 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI
;; Maintainer: PI:EMAIL:<EMAIL>END_PI
;; Keywords: convenience
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This really has nothing to do with list-command-history per se, but
;; its a nice alternative to C-x ESC ESC (repeat-complex-command) and
;; functions as a lister if given no pattern. It's not important
;; enough to warrant a file of its own.
;;; Code:
(defgroup chistory nil
"List command history."
:group 'keyboard)
;;;###autoload
(defun repeat-matching-complex-command (&optional pattern)
"Edit and re-evaluate complex command with name matching PATTERN.
Matching occurrences are displayed, most recent first, until you select
a form for evaluation. If PATTERN is empty (or nil), every form in the
command history is offered. The form is placed in the minibuffer for
editing and the result is evaluated."
(interactive "sRedo Command (regexp): ")
(if pattern
(if (string-match "[^ \t]" pattern)
(setq pattern (substring pattern (match-beginning 0)))
(setq pattern nil)))
(let ((history command-history)
(temp)
(what))
(while (and history (not what))
(setq temp (car history))
(if (and (or (not pattern) (string-match pattern (symbol-name (car temp))))
(y-or-n-p (format "Redo %S? " temp)))
(setq what (car history))
(setq history (cdr history))))
(if (not what)
(error "Command history exhausted")
;; Try to remove any useless command history element for this command.
(if (eq (car (car command-history)) 'repeat-matching-complex-command)
(setq command-history (cdr command-history)))
(edit-and-eval-command "Redo: " what))))
(defcustom default-command-history-filter-garbage
'(command-history-mode
list-command-history
electric-command-history)
"A list of symbols to be ignored by `default-command-history-filter'.
If that function is given a list whose car is an element of this list,
then it will return non-nil (indicating the list should be discarded from
the history).
Initially, all commands related to the command history are discarded."
:type '(repeat symbol)
:group 'chistory)
(defvar list-command-history-filter 'default-command-history-filter
"Predicate to test which commands should be excluded from the history listing.
If non-nil, should be the name of a function of one argument.
It is passed each element of the command history when
\\[list-command-history] is called. If the filter returns non-nil for
some element, that element is excluded from the history listing. The
default filter removes commands associated with the command-history.")
(defun default-command-history-filter (frob)
"Filter commands matching `default-command-history-filter-garbage' list
from the command history."
(or (not (consp frob))
(memq (car frob) default-command-history-filter-garbage)))
(defcustom list-command-history-max 32
"If non-nil, maximum length of the listing produced by `list-command-history'."
:type '(choice integer (const nil))
:group 'chistory)
;;;###autoload
(defun list-command-history ()
"List history of commands typed to minibuffer.
The number of commands listed is controlled by `list-command-history-max'.
Calls value of `list-command-history-filter' (if non-nil) on each history
element to judge if that element should be excluded from the list.
The buffer is left in Command History mode."
(interactive)
(with-output-to-temp-buffer
"*Command History*"
(let ((history command-history)
(buffer-read-only nil)
(count (or list-command-history-max -1)))
(while (and (/= count 0) history)
(if (and (bound-and-true-p list-command-history-filter)
(funcall list-command-history-filter (car history)))
nil
(setq count (1- count))
(prin1 (car history))
(terpri))
(setq history (cdr history))))
(with-current-buffer "*Command History*"
(goto-char (point-min))
(if (eobp)
(error "No command history")
(command-history-mode)))))
(define-obsolete-variable-alias 'command-history-map
'command-history-mode-map "24.1")
(defvar command-history-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map lisp-mode-shared-map)
(suppress-keymap map)
(define-key map "x" 'command-history-repeat)
(define-key map "\n" 'next-line)
(define-key map "\r" 'next-line)
(define-key map "\177" 'previous-line)
map)
"Keymap for `command-history-mode'.")
(define-derived-mode command-history-mode fundamental-mode "Command History"
"Major mode for listing and repeating recent commands.
Keybindings:
\\{command-history-mode-map}"
(lisp-mode-variables nil)
(set-syntax-table emacs-lisp-mode-syntax-table)
(setq buffer-read-only t))
(defcustom command-history-hook nil
"If non-nil, its value is called on entry to `command-history-mode'."
:type 'hook
:group 'chistory)
(defun command-history-repeat ()
"Repeat the command shown on the current line.
The buffer for that command is the previous current buffer."
(interactive)
(save-excursion
(eval (prog1
(save-excursion
(beginning-of-line)
(read (current-buffer)))
(set-buffer
(car (cdr (buffer-list))))))))
;;;###autoload
(defun command-history ()
"Examine commands from `command-history' in a buffer.
The number of commands listed is controlled by `list-command-history-max'.
The command history is filtered by `list-command-history-filter' if non-nil.
Use \\<command-history-map>\\[command-history-repeat] to repeat the command on the current line.
Otherwise much like Emacs-Lisp Mode except that there is no self-insertion
and digits provide prefix arguments. Tab does not indent.
\\{command-history-map}
This command always recompiles the Command History listing
and runs the normal hook `command-history-hook'."
(interactive)
(list-command-history)
(pop-to-buffer "*Command History*")
(run-hooks 'command-history-hook))
(provide 'chistory)
;;; chistory.el ends here
|
[
{
"context": "le with big, ascii art text\n\n;; Copyright (C) 2014 Aurelien Aptel <aurelien.aptel@gmail.com>\n;; Copyright (C) 2008 ",
"end": 93,
"score": 0.9998978972434998,
"start": 79,
"tag": "NAME",
"value": "Aurelien Aptel"
},
{
"context": "i art text\n\n;; Copyright (C) 2014 Aurelien Aptel <aurelien.aptel@gmail.com>\n;; Copyright (C) 2008 Philip Jackson\n\n;; Author:",
"end": 119,
"score": 0.9999356865882874,
"start": 95,
"tag": "EMAIL",
"value": "aurelien.aptel@gmail.com"
},
{
"context": "l <aurelien.aptel@gmail.com>\n;; Copyright (C) 2008 Philip Jackson\n\n;; Author: Philip Jackson <phil@shellarchive.co.",
"end": 157,
"score": 0.9998423457145691,
"start": 143,
"tag": "NAME",
"value": "Philip Jackson"
},
{
"context": ">\n;; Copyright (C) 2008 Philip Jackson\n\n;; Author: Philip Jackson <phil@shellarchive.co.uk>\n;; Version: 0.5\n;; Pack",
"end": 184,
"score": 0.999879002571106,
"start": 170,
"tag": "NAME",
"value": "Philip Jackson"
},
{
"context": ") 2008 Philip Jackson\n\n;; Author: Philip Jackson <phil@shellarchive.co.uk>\n;; Version: 0.5\n;; Package-Version: 20160218.143",
"end": 209,
"score": 0.9999358654022217,
"start": 186,
"tag": "EMAIL",
"value": "phil@shellarchive.co.uk"
}
] | .emacs.d/elpa/figlet-20160218.1437/figlet.el | caqg/linux-home | 0 | ;;; figlet.el --- Annoy people with big, ascii art text
;; Copyright (C) 2014 Aurelien Aptel <aurelien.aptel@gmail.com>
;; Copyright (C) 2008 Philip Jackson
;; Author: Philip Jackson <phil@shellarchive.co.uk>
;; Version: 0.5
;; Package-Version: 20160218.1437
;; This file is not currently part of GNU Emacs.
;; 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 ; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; To use this feature simple eval (require 'figlet) type M-x figlet
;; and you will be asked for a string. If you use a prefix (C-u M-x
;; figlet) then you will be asked for a font.
;; Have a look at `figlet-comment', `figlet-figletify-region' and
;; `figlet-figletify-region-comment'.
;; Warning, leaving large ascii art text in your teams codebase might
;; cause an outbreak of physical violence.
(defvar figlet-fonts '())
(defvar figlet-default-font "small"
"Default font to use when none is supplied.")
(defvar figlet-options '()
"List of options for the figlet call.
This is a list of strings, e.g. '(\"-k\").")
(defvar figlet-font-directory nil
"Figlet default font directory")
(defun figlet-get-font-dir ()
"Return default font directory."
(or figlet-font-directory
(setq figlet-font-directory
(let ((s (shell-command-to-string "figlet -I2")))
(substring s 0 (1- (length s)))))))
(defun figlet-get-font-list ()
"Get a list of figlet fonts."
(or figlet-fonts
(setq figlet-fonts
(mapcar (lambda (f)
(replace-regexp-in-string "\\.flf$" "" f))
(directory-files (figlet-get-font-dir) nil "^[^.].+\\.flf$")))))
;;;###autoload
(defun figlet (string)
"Pass a string through figlet and insert the output at
point. Use a prefix arg to be promted for a font."
(interactive "sTo be fug: ")
(let* ((fonts (figlet-get-font-list))
(font (if current-prefix-arg
(if fonts
(completing-read "Font: " fonts nil t)
(read-from-minibuffer "Font: " figlet-default-font))
figlet-default-font)))
(insert
(with-temp-buffer
(apply #'call-process (append '("figlet" nil t t)
figlet-options
`("-f" ,font ,string)))
(goto-char (point-min))
(re-search-forward "^." nil t)
(delete-region (point-min) (point-at-bol))
(re-search-forward "^[[:blank:]]*$" nil t)
(delete-region (point) (point-max))
(delete-trailing-whitespace)
(buffer-substring (point-min) (point-max))))))
;;;###autoload
(defun figlet-comment (string)
"Insert a figlet string just as `figlet' would but comment the
result (using `comment-region')"
(interactive "sTo be fug: ")
(let ((start (point)))
(save-excursion
(figlet string)
(comment-region start (point)))))
;;;###autoload
(defun figlet-figletify-region (start end)
"Convert the region into a figlet string."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet str)))
;;;###autoload
(defun figlet-figletify-region-comment (start end)
"Convert the region into a figlet string as with
`figlet-figletify-region' but comment it out too."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet-comment str)))
;;;###autoload
(defun figlet-preview-fonts (&optional text)
"View an example of each font in a new buffer."
(interactive)
(switch-to-buffer (get-buffer-create "*Figlet Font Examples*"))
(delete-region (point-min) (point-max))
(mapconcat (lambda (x)
(let ((figlet-default-font x))
(insert (concat x ":\n"))
(figlet (or text x))))
(figlet-get-font-list)
"\n"))
(provide 'figlet)
;;; figlet.el ends here
| 8407 | ;;; figlet.el --- Annoy people with big, ascii art text
;; Copyright (C) 2014 <NAME> <<EMAIL>>
;; Copyright (C) 2008 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Version: 0.5
;; Package-Version: 20160218.1437
;; This file is not currently part of GNU Emacs.
;; 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 ; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; To use this feature simple eval (require 'figlet) type M-x figlet
;; and you will be asked for a string. If you use a prefix (C-u M-x
;; figlet) then you will be asked for a font.
;; Have a look at `figlet-comment', `figlet-figletify-region' and
;; `figlet-figletify-region-comment'.
;; Warning, leaving large ascii art text in your teams codebase might
;; cause an outbreak of physical violence.
(defvar figlet-fonts '())
(defvar figlet-default-font "small"
"Default font to use when none is supplied.")
(defvar figlet-options '()
"List of options for the figlet call.
This is a list of strings, e.g. '(\"-k\").")
(defvar figlet-font-directory nil
"Figlet default font directory")
(defun figlet-get-font-dir ()
"Return default font directory."
(or figlet-font-directory
(setq figlet-font-directory
(let ((s (shell-command-to-string "figlet -I2")))
(substring s 0 (1- (length s)))))))
(defun figlet-get-font-list ()
"Get a list of figlet fonts."
(or figlet-fonts
(setq figlet-fonts
(mapcar (lambda (f)
(replace-regexp-in-string "\\.flf$" "" f))
(directory-files (figlet-get-font-dir) nil "^[^.].+\\.flf$")))))
;;;###autoload
(defun figlet (string)
"Pass a string through figlet and insert the output at
point. Use a prefix arg to be promted for a font."
(interactive "sTo be fug: ")
(let* ((fonts (figlet-get-font-list))
(font (if current-prefix-arg
(if fonts
(completing-read "Font: " fonts nil t)
(read-from-minibuffer "Font: " figlet-default-font))
figlet-default-font)))
(insert
(with-temp-buffer
(apply #'call-process (append '("figlet" nil t t)
figlet-options
`("-f" ,font ,string)))
(goto-char (point-min))
(re-search-forward "^." nil t)
(delete-region (point-min) (point-at-bol))
(re-search-forward "^[[:blank:]]*$" nil t)
(delete-region (point) (point-max))
(delete-trailing-whitespace)
(buffer-substring (point-min) (point-max))))))
;;;###autoload
(defun figlet-comment (string)
"Insert a figlet string just as `figlet' would but comment the
result (using `comment-region')"
(interactive "sTo be fug: ")
(let ((start (point)))
(save-excursion
(figlet string)
(comment-region start (point)))))
;;;###autoload
(defun figlet-figletify-region (start end)
"Convert the region into a figlet string."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet str)))
;;;###autoload
(defun figlet-figletify-region-comment (start end)
"Convert the region into a figlet string as with
`figlet-figletify-region' but comment it out too."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet-comment str)))
;;;###autoload
(defun figlet-preview-fonts (&optional text)
"View an example of each font in a new buffer."
(interactive)
(switch-to-buffer (get-buffer-create "*Figlet Font Examples*"))
(delete-region (point-min) (point-max))
(mapconcat (lambda (x)
(let ((figlet-default-font x))
(insert (concat x ":\n"))
(figlet (or text x))))
(figlet-get-font-list)
"\n"))
(provide 'figlet)
;;; figlet.el ends here
| true | ;;; figlet.el --- Annoy people with big, ascii art text
;; Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Copyright (C) 2008 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Version: 0.5
;; Package-Version: 20160218.1437
;; This file is not currently part of GNU Emacs.
;; 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 ; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; To use this feature simple eval (require 'figlet) type M-x figlet
;; and you will be asked for a string. If you use a prefix (C-u M-x
;; figlet) then you will be asked for a font.
;; Have a look at `figlet-comment', `figlet-figletify-region' and
;; `figlet-figletify-region-comment'.
;; Warning, leaving large ascii art text in your teams codebase might
;; cause an outbreak of physical violence.
(defvar figlet-fonts '())
(defvar figlet-default-font "small"
"Default font to use when none is supplied.")
(defvar figlet-options '()
"List of options for the figlet call.
This is a list of strings, e.g. '(\"-k\").")
(defvar figlet-font-directory nil
"Figlet default font directory")
(defun figlet-get-font-dir ()
"Return default font directory."
(or figlet-font-directory
(setq figlet-font-directory
(let ((s (shell-command-to-string "figlet -I2")))
(substring s 0 (1- (length s)))))))
(defun figlet-get-font-list ()
"Get a list of figlet fonts."
(or figlet-fonts
(setq figlet-fonts
(mapcar (lambda (f)
(replace-regexp-in-string "\\.flf$" "" f))
(directory-files (figlet-get-font-dir) nil "^[^.].+\\.flf$")))))
;;;###autoload
(defun figlet (string)
"Pass a string through figlet and insert the output at
point. Use a prefix arg to be promted for a font."
(interactive "sTo be fug: ")
(let* ((fonts (figlet-get-font-list))
(font (if current-prefix-arg
(if fonts
(completing-read "Font: " fonts nil t)
(read-from-minibuffer "Font: " figlet-default-font))
figlet-default-font)))
(insert
(with-temp-buffer
(apply #'call-process (append '("figlet" nil t t)
figlet-options
`("-f" ,font ,string)))
(goto-char (point-min))
(re-search-forward "^." nil t)
(delete-region (point-min) (point-at-bol))
(re-search-forward "^[[:blank:]]*$" nil t)
(delete-region (point) (point-max))
(delete-trailing-whitespace)
(buffer-substring (point-min) (point-max))))))
;;;###autoload
(defun figlet-comment (string)
"Insert a figlet string just as `figlet' would but comment the
result (using `comment-region')"
(interactive "sTo be fug: ")
(let ((start (point)))
(save-excursion
(figlet string)
(comment-region start (point)))))
;;;###autoload
(defun figlet-figletify-region (start end)
"Convert the region into a figlet string."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet str)))
;;;###autoload
(defun figlet-figletify-region-comment (start end)
"Convert the region into a figlet string as with
`figlet-figletify-region' but comment it out too."
(interactive "r")
(let ((str (buffer-substring start end)))
(delete-region start end)
(figlet-comment str)))
;;;###autoload
(defun figlet-preview-fonts (&optional text)
"View an example of each font in a new buffer."
(interactive)
(switch-to-buffer (get-buffer-create "*Figlet Font Examples*"))
(delete-region (point-min) (point-max))
(mapconcat (lambda (x)
(let ((figlet-default-font x))
(insert (concat x ":\n"))
(figlet (or text x))))
(figlet-get-font-list)
"\n"))
(provide 'figlet)
;;; figlet.el ends here
|
[
{
"context": "een t)\n(setq initial-scratch-message \"Welcome back Jacob\")\n\n; for gui, this is all handled in xresourses\n(",
"end": 269,
"score": 0.9922806024551392,
"start": 264,
"tag": "NAME",
"value": "Jacob"
}
] | emacs/j-config/settings.el | jacobrec/dotfiles | 1 | ;this is never loaded anywasy)
(setq custom-file (concat user-emacs-directory "/custom.el"))
(setq vc-follow-symlinks t) ; stop asking me every time
;; remove all those extra ui stuff
(setq inhibit-startup-screen t)
(setq initial-scratch-message "Welcome back Jacob")
; for gui, this is all handled in xresourses
(unless (display-graphic-p)
(menu-bar-mode -1))
; (scroll-bar-mode -1)
; (tooltip-mode -1)
; (tool-bar-mode -1)
; (set-face-attribute 'default nil :height 150))
;; backup files no more
(setq backup-inhibited t
make-backup-files nil
auto-save-default nil
auto-save-list-file-prefix nil)
(global-linum-mode t) ; line numbers
(show-paren-mode 1) ; show matching parenthesis
(setq whitespace-line-column 220); column width before emacs gets mad
(if (display-graphic-p) ;; only in gui mode
(global-whitespace-mode)) ;; show whitespace
(setq-default indent-tabs-mode nil) ;; no tabs
(setq-default tab-width 4)
(setq org-confirm-babel-evaluate nil) ; stop asking if I actually want to run it
(org-babel-do-load-languages
'org-babel-load-languages ; org-babel language list
'((python . t)
(plantuml . t)
(dot . t)))
(add-to-list 'org-src-lang-modes '("plantuml" . plantuml))
(setq org-plantuml-jar-path (expand-file-name "/usr/share/java/plantuml/plantuml.jar"))
(defun my/fix-inline-images ()
(when org-inline-image-overlays
(org-redisplay-inline-images)))
(add-hook 'org-babel-after-execute-hook 'my/fix-inline-images)
(setq create-lockfiles nil) ; no lockfiles. This kills react
(provide 'settings)
| 35765 | ;this is never loaded anywasy)
(setq custom-file (concat user-emacs-directory "/custom.el"))
(setq vc-follow-symlinks t) ; stop asking me every time
;; remove all those extra ui stuff
(setq inhibit-startup-screen t)
(setq initial-scratch-message "Welcome back <NAME>")
; for gui, this is all handled in xresourses
(unless (display-graphic-p)
(menu-bar-mode -1))
; (scroll-bar-mode -1)
; (tooltip-mode -1)
; (tool-bar-mode -1)
; (set-face-attribute 'default nil :height 150))
;; backup files no more
(setq backup-inhibited t
make-backup-files nil
auto-save-default nil
auto-save-list-file-prefix nil)
(global-linum-mode t) ; line numbers
(show-paren-mode 1) ; show matching parenthesis
(setq whitespace-line-column 220); column width before emacs gets mad
(if (display-graphic-p) ;; only in gui mode
(global-whitespace-mode)) ;; show whitespace
(setq-default indent-tabs-mode nil) ;; no tabs
(setq-default tab-width 4)
(setq org-confirm-babel-evaluate nil) ; stop asking if I actually want to run it
(org-babel-do-load-languages
'org-babel-load-languages ; org-babel language list
'((python . t)
(plantuml . t)
(dot . t)))
(add-to-list 'org-src-lang-modes '("plantuml" . plantuml))
(setq org-plantuml-jar-path (expand-file-name "/usr/share/java/plantuml/plantuml.jar"))
(defun my/fix-inline-images ()
(when org-inline-image-overlays
(org-redisplay-inline-images)))
(add-hook 'org-babel-after-execute-hook 'my/fix-inline-images)
(setq create-lockfiles nil) ; no lockfiles. This kills react
(provide 'settings)
| true | ;this is never loaded anywasy)
(setq custom-file (concat user-emacs-directory "/custom.el"))
(setq vc-follow-symlinks t) ; stop asking me every time
;; remove all those extra ui stuff
(setq inhibit-startup-screen t)
(setq initial-scratch-message "Welcome back PI:NAME:<NAME>END_PI")
; for gui, this is all handled in xresourses
(unless (display-graphic-p)
(menu-bar-mode -1))
; (scroll-bar-mode -1)
; (tooltip-mode -1)
; (tool-bar-mode -1)
; (set-face-attribute 'default nil :height 150))
;; backup files no more
(setq backup-inhibited t
make-backup-files nil
auto-save-default nil
auto-save-list-file-prefix nil)
(global-linum-mode t) ; line numbers
(show-paren-mode 1) ; show matching parenthesis
(setq whitespace-line-column 220); column width before emacs gets mad
(if (display-graphic-p) ;; only in gui mode
(global-whitespace-mode)) ;; show whitespace
(setq-default indent-tabs-mode nil) ;; no tabs
(setq-default tab-width 4)
(setq org-confirm-babel-evaluate nil) ; stop asking if I actually want to run it
(org-babel-do-load-languages
'org-babel-load-languages ; org-babel language list
'((python . t)
(plantuml . t)
(dot . t)))
(add-to-list 'org-src-lang-modes '("plantuml" . plantuml))
(setq org-plantuml-jar-path (expand-file-name "/usr/share/java/plantuml/plantuml.jar"))
(defun my/fix-inline-images ()
(when org-inline-image-overlays
(org-redisplay-inline-images)))
(add-hook 'org-babel-after-execute-hook 'my/fix-inline-images)
(setq create-lockfiles nil) ; no lockfiles. This kills react
(provide 'settings)
|
[
{
"context": "*- lexical-binding: t; -*-\n\n;; Copyright (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu",
"end": 128,
"score": 0.999863862991333,
"start": 116,
"tag": "NAME",
"value": "John Kitchin"
},
{
"context": "-\n\n;; Copyright (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu>\n;; Keywords:\n\n;; This p",
"end": 153,
"score": 0.9998719692230225,
"start": 141,
"tag": "NAME",
"value": "John Kitchin"
},
{
"context": " (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu>\n;; Keywords:\n\n;; This program is free software; ",
"end": 178,
"score": 0.9999323487281799,
"start": 155,
"tag": "EMAIL",
"value": "jkitchin@andrew.cmu.edu"
}
] | elpa/org-ref-20210726.1533/org-ref-reftex.el | ik314/.emacs.d | 11 | ;;; org-ref-reftex.el --- org-ref completion setup with reftex -*- lexical-binding: t; -*-
;; Copyright (C) 2016 John Kitchin
;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary: This is a bare-bones completion engine using only org-mode and
;;; vanilla Emacs functions. It is not being further developed.
;;
;;; Code:
(require 'reftex)
(require 'reftex-cite)
(require 'org-ref-utils)
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(defvar org-ref-cite-types)
(defvar org-ref-open-notes-function)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-open-pdf-function)
;;;###autoload
(defun org-ref-reftex-completion ()
"Use reftex and org-mode for completion."
(interactive)
;; Define core functions for org-ref
(setq org-ref-insert-link-function 'org-ref-insert-cite-link
org-ref-insert-cite-function 'org-ref-insert-cite-link
org-ref-insert-label-function 'org-insert-link
org-ref-insert-ref-function 'org-insert-link
org-ref-cite-onclick-function 'org-ref-cite-onclick-minibuffer-menu)
(message "reftex completion in org-ref loaded."))
(org-ref-reftex-completion)
(define-key org-mode-map
(kbd org-ref-insert-cite-key)
org-ref-insert-link-function)
;; Messages in the minbuffer conflict with the minibuffer menu. So we turn them
;; off.
(setq org-ref-show-citation-on-enter nil)
;;* org-mode / reftex setup
(defun org-mode-reftex-setup ()
"Setup `org-mode' and reftex for `org-ref'."
(and (buffer-file-name)
(file-exists-p (buffer-file-name))
(global-auto-revert-mode t))
(make-local-variable 'reftex-cite-format)
(setq reftex-cite-format 'org))
(add-hook 'org-mode-hook 'org-mode-reftex-setup)
(eval-after-load 'reftex-vars
'(progn
(add-to-list 'reftex-cite-format-builtin
'(org "Org-mode citation"
((?\C-m . "cite:%l") ; default
(?d . ",%l") ; for appending
(?a . "autocite:%l")
(?t . "citet:%l")
(?T . "citet*:%l")
(?p . "citep:%l")
(?P . "citep*:%l")
(?h . "citeauthor:%l")
(?H . "citeauthor*:%l")
(?y . "citeyear:%l")
(?x . "citetext:%l")
(?n . "nocite:%l"))))))
(defun org-ref-insert-cite-link (alternative-cite)
"Insert a default citation link using reftex.
If you are on a link, it appends to the end of the link,
otherwise, a new link is inserted. Use a prefix
arg (ALTERNATIVE-CITE) to get a menu of citation types."
(interactive "P")
(org-ref-find-bibliography)
(let* ((object (org-element-context))
(link-string-end (org-element-property :end object)))
(if (not alternative-cite)
(cond
;; case where we are in a link
((and (equal (org-element-type object) 'link)
(-contains? org-ref-cite-types
(org-element-property :type object)))
(goto-char link-string-end)
;; sometimes there are spaces at the end of the link
;; this code moves point pack until no spaces are there
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; We are next to a link, and we want to append
((save-excursion
(backward-char)
(and (equal (org-element-type (org-element-context)) 'link)
(-contains? org-ref-cite-types
(org-element-property
:type (org-element-context)))))
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; insert fresh link
(t
(insert
(concat org-ref-default-citation-link
":"
(mapconcat 'identity (reftex-citation t) ",")))))
;; you pressed a C-u so we run this code
(reftex-citation))))
;;;###autoload
(defun org-ref-open-notes-from-reftex ()
"Call reftex, and open notes for selected entry."
(interactive)
;; now look for entry in the notes file
(if org-ref-bibliography-notes
(find-file-other-window org-ref-bibliography-notes)
(error "org-ref-bibliography-notes is not set to anything"))
(org-open-link-from-string
(format "[[#%s]]" (car (reftex-citation t))))
(funcall org-ref-open-notes-function))
(defalias 'ornr 'org-ref-open-notes-from-reftex)
;;*** Minibuffer menu
;;;###autoload
(defun org-ref-cite-onclick-minibuffer-menu (&optional _link-string)
"Action when a cite link is clicked on.
Provides a menu of context sensitive actions. If the bibtex entry
has a pdf, you get an option to open it. If there is a doi, you
get a lot of options. LINK-STRING is used by the link function."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key))
(bibfile (cdr results))
(url (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(bibtex-autokey-get-field "url"))))
(doi (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(bibtex-autokey-get-field "doi")))))
(when (string= "" doi) (setq doi nil))
(when (string= "" url) (setq url nil))
(setq org-ref-cite-menu-funcs '())
;; open action
(when
bibfile
(add-to-list
'org-ref-cite-menu-funcs
'("o" "pen" org-ref-open-citation-at-point)))
;; pdf
(when (file-exists-p pdf-file)
(add-to-list
'org-ref-cite-menu-funcs
`("p" "df" ,org-ref-open-pdf-function) t))
;; notes
(add-to-list
'org-ref-cite-menu-funcs
'("n" "otes" org-ref-open-notes-at-point) t)
;; url
(when (or url doi)
(add-to-list
'org-ref-cite-menu-funcs
'("u" "rl" org-ref-open-url-at-point) t))
;; doi funcs
(when doi
(add-to-list
'org-ref-cite-menu-funcs
'("w" "os" org-ref-wos-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("c" "iting" org-ref-wos-citing-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("r" "elated" org-ref-wos-related-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("g" "oogle scholar" org-ref-google-scholar-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("P" "ubmed" org-ref-pubmed-at-point) t))
;; add user functions
(dolist (tup org-ref-user-cite-menu-funcs)
(add-to-list
'org-ref-cite-menu-funcs
tup t))
;; finally quit
(add-to-list
'org-ref-cite-menu-funcs
'("q" "uit" (lambda ())) t)
;; now we make a menu
;; construct menu string as a message
(message
(concat
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-bib-citation))))
"\n"
(mapconcat
(lambda (tup)
(concat "[" (elt tup 0) "]"
(elt tup 1) " "))
org-ref-cite-menu-funcs "")))
;; get the input
(let* ((input (read-char-exclusive))
(choice (assoc
(char-to-string input) org-ref-cite-menu-funcs)))
;; now run the function (2nd element in choice)
(when choice
(funcall
(elt
choice
2))))))
(provide 'org-ref-reftex)
;;; org-ref-reftex.el ends here
| 81 | ;;; org-ref-reftex.el --- org-ref completion setup with reftex -*- lexical-binding: t; -*-
;; Copyright (C) 2016 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary: This is a bare-bones completion engine using only org-mode and
;;; vanilla Emacs functions. It is not being further developed.
;;
;;; Code:
(require 'reftex)
(require 'reftex-cite)
(require 'org-ref-utils)
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(defvar org-ref-cite-types)
(defvar org-ref-open-notes-function)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-open-pdf-function)
;;;###autoload
(defun org-ref-reftex-completion ()
"Use reftex and org-mode for completion."
(interactive)
;; Define core functions for org-ref
(setq org-ref-insert-link-function 'org-ref-insert-cite-link
org-ref-insert-cite-function 'org-ref-insert-cite-link
org-ref-insert-label-function 'org-insert-link
org-ref-insert-ref-function 'org-insert-link
org-ref-cite-onclick-function 'org-ref-cite-onclick-minibuffer-menu)
(message "reftex completion in org-ref loaded."))
(org-ref-reftex-completion)
(define-key org-mode-map
(kbd org-ref-insert-cite-key)
org-ref-insert-link-function)
;; Messages in the minbuffer conflict with the minibuffer menu. So we turn them
;; off.
(setq org-ref-show-citation-on-enter nil)
;;* org-mode / reftex setup
(defun org-mode-reftex-setup ()
"Setup `org-mode' and reftex for `org-ref'."
(and (buffer-file-name)
(file-exists-p (buffer-file-name))
(global-auto-revert-mode t))
(make-local-variable 'reftex-cite-format)
(setq reftex-cite-format 'org))
(add-hook 'org-mode-hook 'org-mode-reftex-setup)
(eval-after-load 'reftex-vars
'(progn
(add-to-list 'reftex-cite-format-builtin
'(org "Org-mode citation"
((?\C-m . "cite:%l") ; default
(?d . ",%l") ; for appending
(?a . "autocite:%l")
(?t . "citet:%l")
(?T . "citet*:%l")
(?p . "citep:%l")
(?P . "citep*:%l")
(?h . "citeauthor:%l")
(?H . "citeauthor*:%l")
(?y . "citeyear:%l")
(?x . "citetext:%l")
(?n . "nocite:%l"))))))
(defun org-ref-insert-cite-link (alternative-cite)
"Insert a default citation link using reftex.
If you are on a link, it appends to the end of the link,
otherwise, a new link is inserted. Use a prefix
arg (ALTERNATIVE-CITE) to get a menu of citation types."
(interactive "P")
(org-ref-find-bibliography)
(let* ((object (org-element-context))
(link-string-end (org-element-property :end object)))
(if (not alternative-cite)
(cond
;; case where we are in a link
((and (equal (org-element-type object) 'link)
(-contains? org-ref-cite-types
(org-element-property :type object)))
(goto-char link-string-end)
;; sometimes there are spaces at the end of the link
;; this code moves point pack until no spaces are there
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; We are next to a link, and we want to append
((save-excursion
(backward-char)
(and (equal (org-element-type (org-element-context)) 'link)
(-contains? org-ref-cite-types
(org-element-property
:type (org-element-context)))))
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; insert fresh link
(t
(insert
(concat org-ref-default-citation-link
":"
(mapconcat 'identity (reftex-citation t) ",")))))
;; you pressed a C-u so we run this code
(reftex-citation))))
;;;###autoload
(defun org-ref-open-notes-from-reftex ()
"Call reftex, and open notes for selected entry."
(interactive)
;; now look for entry in the notes file
(if org-ref-bibliography-notes
(find-file-other-window org-ref-bibliography-notes)
(error "org-ref-bibliography-notes is not set to anything"))
(org-open-link-from-string
(format "[[#%s]]" (car (reftex-citation t))))
(funcall org-ref-open-notes-function))
(defalias 'ornr 'org-ref-open-notes-from-reftex)
;;*** Minibuffer menu
;;;###autoload
(defun org-ref-cite-onclick-minibuffer-menu (&optional _link-string)
"Action when a cite link is clicked on.
Provides a menu of context sensitive actions. If the bibtex entry
has a pdf, you get an option to open it. If there is a doi, you
get a lot of options. LINK-STRING is used by the link function."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key))
(bibfile (cdr results))
(url (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(bibtex-autokey-get-field "url"))))
(doi (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(bibtex-autokey-get-field "doi")))))
(when (string= "" doi) (setq doi nil))
(when (string= "" url) (setq url nil))
(setq org-ref-cite-menu-funcs '())
;; open action
(when
bibfile
(add-to-list
'org-ref-cite-menu-funcs
'("o" "pen" org-ref-open-citation-at-point)))
;; pdf
(when (file-exists-p pdf-file)
(add-to-list
'org-ref-cite-menu-funcs
`("p" "df" ,org-ref-open-pdf-function) t))
;; notes
(add-to-list
'org-ref-cite-menu-funcs
'("n" "otes" org-ref-open-notes-at-point) t)
;; url
(when (or url doi)
(add-to-list
'org-ref-cite-menu-funcs
'("u" "rl" org-ref-open-url-at-point) t))
;; doi funcs
(when doi
(add-to-list
'org-ref-cite-menu-funcs
'("w" "os" org-ref-wos-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("c" "iting" org-ref-wos-citing-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("r" "elated" org-ref-wos-related-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("g" "oogle scholar" org-ref-google-scholar-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("P" "ubmed" org-ref-pubmed-at-point) t))
;; add user functions
(dolist (tup org-ref-user-cite-menu-funcs)
(add-to-list
'org-ref-cite-menu-funcs
tup t))
;; finally quit
(add-to-list
'org-ref-cite-menu-funcs
'("q" "uit" (lambda ())) t)
;; now we make a menu
;; construct menu string as a message
(message
(concat
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-bib-citation))))
"\n"
(mapconcat
(lambda (tup)
(concat "[" (elt tup 0) "]"
(elt tup 1) " "))
org-ref-cite-menu-funcs "")))
;; get the input
(let* ((input (read-char-exclusive))
(choice (assoc
(char-to-string input) org-ref-cite-menu-funcs)))
;; now run the function (2nd element in choice)
(when choice
(funcall
(elt
choice
2))))))
(provide 'org-ref-reftex)
;;; org-ref-reftex.el ends here
| true | ;;; org-ref-reftex.el --- org-ref completion setup with reftex -*- lexical-binding: t; -*-
;; Copyright (C) 2016 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary: This is a bare-bones completion engine using only org-mode and
;;; vanilla Emacs functions. It is not being further developed.
;;
;;; Code:
(require 'reftex)
(require 'reftex-cite)
(require 'org-ref-utils)
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(defvar org-ref-cite-types)
(defvar org-ref-open-notes-function)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-open-pdf-function)
;;;###autoload
(defun org-ref-reftex-completion ()
"Use reftex and org-mode for completion."
(interactive)
;; Define core functions for org-ref
(setq org-ref-insert-link-function 'org-ref-insert-cite-link
org-ref-insert-cite-function 'org-ref-insert-cite-link
org-ref-insert-label-function 'org-insert-link
org-ref-insert-ref-function 'org-insert-link
org-ref-cite-onclick-function 'org-ref-cite-onclick-minibuffer-menu)
(message "reftex completion in org-ref loaded."))
(org-ref-reftex-completion)
(define-key org-mode-map
(kbd org-ref-insert-cite-key)
org-ref-insert-link-function)
;; Messages in the minbuffer conflict with the minibuffer menu. So we turn them
;; off.
(setq org-ref-show-citation-on-enter nil)
;;* org-mode / reftex setup
(defun org-mode-reftex-setup ()
"Setup `org-mode' and reftex for `org-ref'."
(and (buffer-file-name)
(file-exists-p (buffer-file-name))
(global-auto-revert-mode t))
(make-local-variable 'reftex-cite-format)
(setq reftex-cite-format 'org))
(add-hook 'org-mode-hook 'org-mode-reftex-setup)
(eval-after-load 'reftex-vars
'(progn
(add-to-list 'reftex-cite-format-builtin
'(org "Org-mode citation"
((?\C-m . "cite:%l") ; default
(?d . ",%l") ; for appending
(?a . "autocite:%l")
(?t . "citet:%l")
(?T . "citet*:%l")
(?p . "citep:%l")
(?P . "citep*:%l")
(?h . "citeauthor:%l")
(?H . "citeauthor*:%l")
(?y . "citeyear:%l")
(?x . "citetext:%l")
(?n . "nocite:%l"))))))
(defun org-ref-insert-cite-link (alternative-cite)
"Insert a default citation link using reftex.
If you are on a link, it appends to the end of the link,
otherwise, a new link is inserted. Use a prefix
arg (ALTERNATIVE-CITE) to get a menu of citation types."
(interactive "P")
(org-ref-find-bibliography)
(let* ((object (org-element-context))
(link-string-end (org-element-property :end object)))
(if (not alternative-cite)
(cond
;; case where we are in a link
((and (equal (org-element-type object) 'link)
(-contains? org-ref-cite-types
(org-element-property :type object)))
(goto-char link-string-end)
;; sometimes there are spaces at the end of the link
;; this code moves point pack until no spaces are there
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; We are next to a link, and we want to append
((save-excursion
(backward-char)
(and (equal (org-element-type (org-element-context)) 'link)
(-contains? org-ref-cite-types
(org-element-property
:type (org-element-context)))))
(skip-chars-backward " ")
(insert (concat "," (mapconcat
'identity
(reftex-citation t ?a) ","))))
;; insert fresh link
(t
(insert
(concat org-ref-default-citation-link
":"
(mapconcat 'identity (reftex-citation t) ",")))))
;; you pressed a C-u so we run this code
(reftex-citation))))
;;;###autoload
(defun org-ref-open-notes-from-reftex ()
"Call reftex, and open notes for selected entry."
(interactive)
;; now look for entry in the notes file
(if org-ref-bibliography-notes
(find-file-other-window org-ref-bibliography-notes)
(error "org-ref-bibliography-notes is not set to anything"))
(org-open-link-from-string
(format "[[#%s]]" (car (reftex-citation t))))
(funcall org-ref-open-notes-function))
(defalias 'ornr 'org-ref-open-notes-from-reftex)
;;*** Minibuffer menu
;;;###autoload
(defun org-ref-cite-onclick-minibuffer-menu (&optional _link-string)
"Action when a cite link is clicked on.
Provides a menu of context sensitive actions. If the bibtex entry
has a pdf, you get an option to open it. If there is a doi, you
get a lot of options. LINK-STRING is used by the link function."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key))
(bibfile (cdr results))
(url (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(bibtex-autokey-get-field "url"))))
(doi (save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(bibtex-autokey-get-field "doi")))))
(when (string= "" doi) (setq doi nil))
(when (string= "" url) (setq url nil))
(setq org-ref-cite-menu-funcs '())
;; open action
(when
bibfile
(add-to-list
'org-ref-cite-menu-funcs
'("o" "pen" org-ref-open-citation-at-point)))
;; pdf
(when (file-exists-p pdf-file)
(add-to-list
'org-ref-cite-menu-funcs
`("p" "df" ,org-ref-open-pdf-function) t))
;; notes
(add-to-list
'org-ref-cite-menu-funcs
'("n" "otes" org-ref-open-notes-at-point) t)
;; url
(when (or url doi)
(add-to-list
'org-ref-cite-menu-funcs
'("u" "rl" org-ref-open-url-at-point) t))
;; doi funcs
(when doi
(add-to-list
'org-ref-cite-menu-funcs
'("w" "os" org-ref-wos-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("c" "iting" org-ref-wos-citing-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("r" "elated" org-ref-wos-related-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("g" "oogle scholar" org-ref-google-scholar-at-point) t)
(add-to-list
'org-ref-cite-menu-funcs
'("P" "ubmed" org-ref-pubmed-at-point) t))
;; add user functions
(dolist (tup org-ref-user-cite-menu-funcs)
(add-to-list
'org-ref-cite-menu-funcs
tup t))
;; finally quit
(add-to-list
'org-ref-cite-menu-funcs
'("q" "uit" (lambda ())) t)
;; now we make a menu
;; construct menu string as a message
(message
(concat
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-bib-citation))))
"\n"
(mapconcat
(lambda (tup)
(concat "[" (elt tup 0) "]"
(elt tup 1) " "))
org-ref-cite-menu-funcs "")))
;; get the input
(let* ((input (read-char-exclusive))
(choice (assoc
(char-to-string input) org-ref-cite-menu-funcs)))
;; now run the function (2nd element in choice)
(when choice
(funcall
(elt
choice
2))))))
(provide 'org-ref-reftex)
;;; org-ref-reftex.el ends here
|
[
{
"context": "e\n\n;;; Commentary:\n;; Base16: (https://github.com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: Khue Nguyen (htt",
"end": 114,
"score": 0.9996827840805054,
"start": 102,
"tag": "USERNAME",
"value": "chriskempson"
},
{
"context": ".com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: Khue Nguyen (https://github.com/Z5483)\n;; Template: Kaleb Elw",
"end": 159,
"score": 0.9997571706771851,
"start": 148,
"tag": "NAME",
"value": "Khue Nguyen"
},
{
"context": "thors:\n;; Scheme: Khue Nguyen (https://github.com/Z5483)\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; ",
"end": 185,
"score": 0.9994932413101196,
"start": 180,
"tag": "USERNAME",
"value": "Z5483"
},
{
"context": "hue Nguyen (https://github.com/Z5483)\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-the",
"end": 212,
"score": 0.9998922348022461,
"start": 200,
"tag": "NAME",
"value": "Kaleb Elwert"
},
{
"context": "ps://github.com/Z5483)\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-theme)\n\n(defvar bas",
"end": 228,
"score": 0.9999306797981262,
"start": 214,
"tag": "EMAIL",
"value": "belak@coded.io"
}
] | themes/emacs/build/base16-ayu-mirage-theme.el | base16-fork/base16-fork | 0 | ;; base16-ayu-mirage-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: Khue Nguyen (https://github.com/Z5483)
;; Template: Kaleb Elwert <belak@coded.io>
;;; Code:
(require 'base16-theme)
(defvar base16-ayu-mirage-colors
'(:base00 "#171B24"
:base01 "#1F2430"
:base02 "#242936"
:base03 "#707A8C"
:base04 "#8A9199"
:base05 "#CCCAC2"
:base06 "#D9D7CE"
:base07 "#F3F4F5"
:base08 "#F28779"
:base09 "#FFAD66"
:base0A "#FFD173"
:base0B "#D5FF80"
:base0C "#95E6CB"
:base0D "#5CCFE6"
:base0E "#D4BFFF"
:base0F "#F29E74")
"All colors for Base16 Ayu Mirage are defined here.")
;; Define the theme
(deftheme base16-ayu-mirage)
;; Add all the faces to the theme
(base16-theme-define 'base16-ayu-mirage base16-ayu-mirage-colors)
;; Mark the theme as provided
(provide-theme 'base16-ayu-mirage)
(provide 'base16-ayu-mirage-theme)
;;; base16-ayu-mirage-theme.el ends here
| 44412 | ;; base16-ayu-mirage-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: <NAME> (https://github.com/Z5483)
;; Template: <NAME> <<EMAIL>>
;;; Code:
(require 'base16-theme)
(defvar base16-ayu-mirage-colors
'(:base00 "#171B24"
:base01 "#1F2430"
:base02 "#242936"
:base03 "#707A8C"
:base04 "#8A9199"
:base05 "#CCCAC2"
:base06 "#D9D7CE"
:base07 "#F3F4F5"
:base08 "#F28779"
:base09 "#FFAD66"
:base0A "#FFD173"
:base0B "#D5FF80"
:base0C "#95E6CB"
:base0D "#5CCFE6"
:base0E "#D4BFFF"
:base0F "#F29E74")
"All colors for Base16 Ayu Mirage are defined here.")
;; Define the theme
(deftheme base16-ayu-mirage)
;; Add all the faces to the theme
(base16-theme-define 'base16-ayu-mirage base16-ayu-mirage-colors)
;; Mark the theme as provided
(provide-theme 'base16-ayu-mirage)
(provide 'base16-ayu-mirage-theme)
;;; base16-ayu-mirage-theme.el ends here
| true | ;; base16-ayu-mirage-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: PI:NAME:<NAME>END_PI (https://github.com/Z5483)
;; Template: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;; Code:
(require 'base16-theme)
(defvar base16-ayu-mirage-colors
'(:base00 "#171B24"
:base01 "#1F2430"
:base02 "#242936"
:base03 "#707A8C"
:base04 "#8A9199"
:base05 "#CCCAC2"
:base06 "#D9D7CE"
:base07 "#F3F4F5"
:base08 "#F28779"
:base09 "#FFAD66"
:base0A "#FFD173"
:base0B "#D5FF80"
:base0C "#95E6CB"
:base0D "#5CCFE6"
:base0E "#D4BFFF"
:base0F "#F29E74")
"All colors for Base16 Ayu Mirage are defined here.")
;; Define the theme
(deftheme base16-ayu-mirage)
;; Add all the faces to the theme
(base16-theme-define 'base16-ayu-mirage base16-ayu-mirage-colors)
;; Mark the theme as provided
(provide-theme 'base16-ayu-mirage)
(provide 'base16-ayu-mirage-theme)
;;; base16-ayu-mirage-theme.el ends here
|
[
{
"context": "de.el --- elnode configure\n\n;; Copyright (C) 2013 zxsu\n\n;; Author: zxsu <suzp1984@gmail.com>\n;; Keywords",
"end": 66,
"score": 0.8957905173301697,
"start": 62,
"tag": "USERNAME",
"value": "zxsu"
},
{
"context": "configure\n\n;; Copyright (C) 2013 zxsu\n\n;; Author: zxsu <suzp1984@gmail.com>\n;; Keywords: \n\n;; This progr",
"end": 83,
"score": 0.9983417391777039,
"start": 79,
"tag": "USERNAME",
"value": "zxsu"
},
{
"context": "re\n\n;; Copyright (C) 2013 zxsu\n\n;; Author: zxsu <suzp1984@gmail.com>\n;; Keywords: \n\n;; This program is free software;",
"end": 103,
"score": 0.9999133944511414,
"start": 85,
"tag": "EMAIL",
"value": "suzp1984@gmail.com"
}
] | config/my-elnode.el | suzp1984/emacs_d | 1 | ;;; my-elnode.el --- elnode configure
;; Copyright (C) 2013 zxsu
;; Author: zxsu <suzp1984@gmail.com>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(require 'elnode)
;(defvar my-org-dir "~/tmp/org")
;; (defun my-elnode-org-handler (httpcon)
;; (elnode-docroot-for my-org-dir
;; with org-file
;; on httpcon
;; do (with-current-buffer (find-file-noselect org-file)
;; (let ((org-html
;; ;; This might throw errors so you could condition-case it
;; (org-export-as-html 3 nil 'string)))
;; (elnode-send-html httpcon org-html)))))
;; (elnode-start 'my-elnode-org-handler :port 8002)
;;(setq elnode-init-port 8702)
(defconst my-elnode-webserver-handler
(elnode-webserver-handler-maker (expand-file-name "~/hack/html/")))
(elnode-start my-elnode-webserver-handler :port 8701 :host "localhost")
(defun my-elnode-hello-world-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/html"))
(elnode-http-return
httpcon
"<html><body><h1>Hello World</h1></body></html>"))
(add-to-list 'elnode-hostpath-default-table '("/helloworld/" . my-elnode-hello-world-handler))
(defvar my-elnode-editor-buffer (get-buffer-create "*my-elnode-editor-buffer*"))
(defun my-elnode-editor-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/plain"))
(elnode-http-return
httpcon
(with-current-buffer my-elnode-editor-buffer
(buffer-substring-no-properties (point-min) (point-max)))))
(add-to-list 'elnode-hostpath-default-table '("/buffer/" . my-elnode-editor-handler))
(defun my-elnode-show-buffer ()
(interactive)
(let ((buffer (get-buffer-create my-elnode-editor-buffer)))
(pop-to-buffer buffer)))
(elnode-init)
(provide 'my-elnode)
;;; my-elnode.el ends here
| 29874 | ;;; my-elnode.el --- elnode configure
;; Copyright (C) 2013 zxsu
;; Author: zxsu <<EMAIL>>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(require 'elnode)
;(defvar my-org-dir "~/tmp/org")
;; (defun my-elnode-org-handler (httpcon)
;; (elnode-docroot-for my-org-dir
;; with org-file
;; on httpcon
;; do (with-current-buffer (find-file-noselect org-file)
;; (let ((org-html
;; ;; This might throw errors so you could condition-case it
;; (org-export-as-html 3 nil 'string)))
;; (elnode-send-html httpcon org-html)))))
;; (elnode-start 'my-elnode-org-handler :port 8002)
;;(setq elnode-init-port 8702)
(defconst my-elnode-webserver-handler
(elnode-webserver-handler-maker (expand-file-name "~/hack/html/")))
(elnode-start my-elnode-webserver-handler :port 8701 :host "localhost")
(defun my-elnode-hello-world-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/html"))
(elnode-http-return
httpcon
"<html><body><h1>Hello World</h1></body></html>"))
(add-to-list 'elnode-hostpath-default-table '("/helloworld/" . my-elnode-hello-world-handler))
(defvar my-elnode-editor-buffer (get-buffer-create "*my-elnode-editor-buffer*"))
(defun my-elnode-editor-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/plain"))
(elnode-http-return
httpcon
(with-current-buffer my-elnode-editor-buffer
(buffer-substring-no-properties (point-min) (point-max)))))
(add-to-list 'elnode-hostpath-default-table '("/buffer/" . my-elnode-editor-handler))
(defun my-elnode-show-buffer ()
(interactive)
(let ((buffer (get-buffer-create my-elnode-editor-buffer)))
(pop-to-buffer buffer)))
(elnode-init)
(provide 'my-elnode)
;;; my-elnode.el ends here
| true | ;;; my-elnode.el --- elnode configure
;; Copyright (C) 2013 zxsu
;; Author: zxsu <PI:EMAIL:<EMAIL>END_PI>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(require 'elnode)
;(defvar my-org-dir "~/tmp/org")
;; (defun my-elnode-org-handler (httpcon)
;; (elnode-docroot-for my-org-dir
;; with org-file
;; on httpcon
;; do (with-current-buffer (find-file-noselect org-file)
;; (let ((org-html
;; ;; This might throw errors so you could condition-case it
;; (org-export-as-html 3 nil 'string)))
;; (elnode-send-html httpcon org-html)))))
;; (elnode-start 'my-elnode-org-handler :port 8002)
;;(setq elnode-init-port 8702)
(defconst my-elnode-webserver-handler
(elnode-webserver-handler-maker (expand-file-name "~/hack/html/")))
(elnode-start my-elnode-webserver-handler :port 8701 :host "localhost")
(defun my-elnode-hello-world-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/html"))
(elnode-http-return
httpcon
"<html><body><h1>Hello World</h1></body></html>"))
(add-to-list 'elnode-hostpath-default-table '("/helloworld/" . my-elnode-hello-world-handler))
(defvar my-elnode-editor-buffer (get-buffer-create "*my-elnode-editor-buffer*"))
(defun my-elnode-editor-handler (httpcon)
(elnode-http-start httpcon 200 '("Content-Type" . "text/plain"))
(elnode-http-return
httpcon
(with-current-buffer my-elnode-editor-buffer
(buffer-substring-no-properties (point-min) (point-max)))))
(add-to-list 'elnode-hostpath-default-table '("/buffer/" . my-elnode-editor-handler))
(defun my-elnode-show-buffer ()
(interactive)
(let ((buffer (get-buffer-create my-elnode-editor-buffer)))
(pop-to-buffer buffer)))
(elnode-init)
(provide 'my-elnode)
;;; my-elnode.el ends here
|
[
{
"context": "ault indent-tabs-mode nil)\n\n(setq user-full-name \"Shadorain\"\n user-mail-address \"shadorain7517@gmail.com",
"end": 638,
"score": 0.9825291037559509,
"start": 629,
"tag": "NAME",
"value": "Shadorain"
},
{
"context": "er-full-name \"Shadorain\"\n user-mail-address \"shadorain7517@gmail.com\")\n\n(setq org-time-stamp-custom-formats '(\"[%a, %m",
"end": 688,
"score": 0.9999138116836548,
"start": 665,
"tag": "EMAIL",
"value": "shadorain7517@gmail.com"
},
{
"context": " :port \"6667\"\n :nick erc-nick\n :password erc-password)))\n\n;; (load \"escreen\")\n;; (escreen-install)\n;; (",
"end": 3745,
"score": 0.9975506067276001,
"start": 3733,
"tag": "PASSWORD",
"value": "erc-password"
}
] | config.el | Shadorain/shadodoom | 2 | ;;; config.el --- -*- lexical-binding: t -*-
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(add-to-list 'package-archives
'("gnu" . "http://elpa.gnu.org/packages/"))
(package-initialize)
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(setq package-check-signature nil)
(eval-when-compile
(require 'use-package))
(setq auto-window-vscroll nil)
(setq scroll-conservatively 101)
;; (add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(setq-default indent-tabs-mode nil)
(setq user-full-name "Shadorain"
user-mail-address "shadorain7517@gmail.com")
(setq org-time-stamp-custom-formats '("[%a, %m/%d/%y]" . "[%a, %m/%d/%y -- %H:%M]"))
(setq
doom-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-variable-pitch-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-theme 'shado
projectile-project-search-path '("~/.xmonad/" "~/Documents/Programming/" "~/dwm/"))
(set-face-foreground 'line-number "#a1a1dd") ; Line number colors
(set-face-foreground 'line-number-current-line "#de286e") ; Current line number color
;; (add-to-list 'default-frame-alist '(background-color . "#0f0f17")) ; Background color
(add-to-list 'default-frame-alist '(background-color . "#08080d")) ; Background color
;; (annotate-mode)
;;; integrate ido with artist-mode
(defun artist-ido-select-operation (type)
"Use ido to select a drawing operation in artist-mode"
(interactive (list (ido-completing-read "Drawing operation: "
(list "Pen" "Pen Line" "line" "straight line" "rectangle"
"square" "poly-line" "straight poly-line" "ellipse"
"circle" "text see-thru" "text-overwrite" "spray-can"
"erase char" "erase rectangle" "vaporize line" "vaporize lines"
"cut rectangle" "cut square" "copy rectangle" "copy square"
"paste" "flood-fill"))))
(artist-select-operation type))
(defun artist-ido-select-settings (type)
"Use ido to select a setting to change in artist-mode"
(interactive (list (ido-completing-read "Setting: "
(list "Set Fill" "Set Line" "Set Erase" "Spray-size" "Spray-chars"
"Rubber-banding" "Trimming" "Borders"))))
(if (equal type "Spray-size")
(artist-select-operation "spray set size")
(call-interactively (artist-fc-get-fn-from-symbol
(cdr (assoc type '(("Set Fill" . set-fill)
("Set Line" . set-line)
("Set Erase" . set-erase)
("Rubber-banding" . rubber-band)
("Trimming" . trimming)
("Borders" . borders)
("Spray-chars" . spray-chars))))))))
;; (avy-setup-default)
(global-set-key (kbd "C-c C-j") 'avy-resume)
(require 'company)
(setq company-idle-delay 0.01
company-minimum-prefix-length 2)
(setq deft-directory "~/org"
deft-exensions '("org")
deft-recursive t)
(setq doom-modeline-height 10)
(set-face-attribute 'mode-line nil :family "Agave" :height 10)
(set-face-attribute 'mode-line-inactive nil :family "Agave" :height 10)
(defun start-erc ()
"Log into freenode with less keystrokes"
(interactive)
(let
((password-cache nil))
(erc
:server "irc.freenode.net"
:port "6667"
:nick erc-nick
:password erc-password)))
;; (load "escreen")
;; (escreen-install)
;; (global-set-key escreen-prefix-char 'escreen-prefix)
;; (require 'eyebrowse)
;; (use-package eyebrowse ; Easy workspaces creation and switching
;; :ensure t
;; :config
;; (validate-setq eyebrowse-mode-line-separator " "
;; eyebrowse-new-workspace t)
(eyebrowse-mode t)
(require 'evil-snipe)
(evil-snipe-mode +1)
(evil-snipe-override-mode +1)
(add-hook 'magit-mode-hook 'turn-off-evil-snipe-override-mode)
(flyspell-mode 0)
(add-to-list 'load-path "~/.emacs.d/lib/gpastel/")
(setq haskell-process-log t)
(add-hook 'haskell-mode-hook 'haskell-indent-mode)
(add-hook 'haskell-mode-hook 'interactive-haskell-mode)
(add-hook 'haskell-mode-hook 'haskell-doc-mode)
(add-hook 'haskell-mode-hook 'hindent-mode)
(require 'lsp)
(require 'lsp-haskell)
(add-hook 'haskell-mode-hook #'lsp)
(require 'hlinum)
(hlinum-activate)
(setq display-line-numbers-type 'relative) ; Relative line numbers with current line shown
(use-package outline
:diminish outline-minor-mode
:config
(use-package outline-minor-faces
:ensure
:hook
(outline-minor-mode-hook . outline-minor-faces-add-font-lock-keywords)))
(global-set-key (kbd "C-`") 'outline-show-entry)
(global-set-key (kbd "C-~") 'outline-hide-entry)
(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu4e")
(require 'mu4e)
;; (require 'ox-latex)
;; (require 'pdf-tools)
;; ;; (setq Tex-auto-save t)
;; ;; (setq Tex-parse-self t)
;; ;; (setq-default Tex-master nil)
;; ;; (add-hook 'LaTeX-mode-hook 'visual-line-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'flyspell-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex)
;; ;; (setq reftex-plug-into-AUCTeX t)
;; ;; (setq TeX-PDF-mode t)
;; ;; (pdf-tools-install)
;; (with-eval-after-load 'pdf-tools
;; (require 'pdf-sync))
;; (use-package pdf-tools
;; :init (pdf-tools-install)
;; :bind (:map pdf-view-mode-map
;; ("T" . pdf-annot-add-text-annotation)
;; ("D" . pdf-annot-delete)
;; ("t" . pdf-annot-add-highlight-markup-annotation)
;; ("j" . image-next-line)
;; ("k" . image-previous-line)
;; ("l" . image-forward-hscroll)
;; ("h" . image-backward-hscroll)
;; ("G" . pdf-view-last-page)
;; ("g" . nil)
;; ("gg" . pdf-view-first-page)
;; ("C-c C-c" . image-toggle-display)
;; ("C-s" . isearch-forward))
;; :config
;; (setq-default pdf-view-display-size 'fit-page)
;; :custom
;; (yas-minor-mode nil)
;; (pdf-cache-image-limit 32)
;; (pdf-view-max-image-width 2048)
;; (pdf-view-resize-factor 1.8)
;; (pdf-isearch-batch-mode t)
;; (pdf-annot-activate-created-annotations t))
;; (setq pdf-sync-backward-display-action t)
;; (setq pdf-sync-forward-display-action t)
(use-package pdf-tools
:ensure t
:config
(pdf-tools-install)
(setq-default pdf-view-display-size 'fit-page)
(setq pdf-annot-activate-created-annotations t)
(define-key pdf-view-mode-map (kbd "C-s") 'isearch-forward)
(define-key pdf-view-mode-map (kbd "C-r") 'isearch-backward)
;; (add-hook 'pdf-view-mode-hook (lambda ()
;; (bms/pdf-midnite-amber))) ; automatically turns on midnight-mode for pdfs
)
;; (use-package auctex-latexmk
;; :ensure t
;; :config
;; (auctex-latexmk-setup)
;; (setq auctex-latexmk-inherit-TeX-PDF-mode t))
;; (use-package reftex
;; :ensure t
;; :defer t
;; :config
;; (setq reftex-cite-prompt-optional-args t)) ;; Prompt for empty optional arguments in cite
;; (use-package auto-dictionary
;; :ensure t
;; :init(add-hook 'flyspell-mode-hook (lambda () (auto-dictionary-mode 1))))
(use-package company-auctex
:ensure t
:init (company-auctex-init))
(use-package tex
:ensure auctex
:mode ("\\.tex\\'" . latex-mode)
:config (progn
(vimish-fold-from-marks)
(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-auto-save t)
(setq TeX-parse-self t)
(pdf-tools-install)
(setq TeX-view-program-selection '((output-pdf "PDF Tools"))
TeX-source-correlate-start-server t)
;; Update PDF buffers after successful LaTeX runs
(add-hook 'TeX-after-compilation-finished-functions
#'TeX-revert-document-buffer)
))
(add-hook 'pdf-view-mode-hook (lambda ()
(pdf-view-midnight-minor-mode))) ; automatically turns on midnight-mode for pdfs
(setq pdf-view-midnight-colors '("#BFAEE3" . "#0a0a12" )) ; #0a0a12 #6f88e8 #e1acff Set custom colors
(defun bms/pdf-no-filter ()
"View pdf without colour filter."
(interactive)
(pdf-view-midnight-minor-mode -1))
; (use-package! rainbow-mode)
(use-package yasnippet
:config
(yas-global-mode 1)
(yas-load-directory "~/.doom.d/snippets/")
(setq yasnippet-snippets-dir "~/.doom.d/snippets/"))
(setq vimish-fold-find-marks-on-open t)
(turn-off-evil-vimish-fold-mode)
(vimish-fold-from-marks)
;; (global-whitespace-mode 1)
;; (progn
;; (setq whitespace-style (quote (face spaces tabs space-mark tab-mark )))
;; (setq whitespace-display-mappings
;; '((space-mark 32 [183] [46]) ; SPACE 32 「 」, 183 MIDDLE DOT 「·」, 46 FULL STOP 「.」; 4347
;; (tab-mark 9 [9655 9] [92 9])))) ; tabs
;; (add-hook 'c-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'emacs-lisp-mode 'rc/set-up-whitespace-handling)
;; (add-hook 'markdown-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'asm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'nasm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'haskell-mode-hook 'rc/set-up-whitespace-handling)
(require 'eglot)
(add-to-list 'eglot-server-programs '((c++-mode c-mode) "clangd"))
(add-hook 'c-mode-hook 'eglot-ensure)
(add-hook 'c++-mode-hook 'eglot-ensure)
(setq
split-width-threshold 0
split-height-threshold nil)
(global-auto-revert-mode t)
(setq TeX-command-force "LaTex")
(defun latex-export-pdf-then-refresh()
(TeX-command-master))
(defun latex-auto-export-on()
(interactive)
(add-hook 'after-save-hook 'latex-export-pdf-then-refresh t t)
(TeX-command-run-all TeX-command-buffer)
(windmove-left))
(defun org-export-pdf-then-refresh()
(org-latex-export-to-pdf))
(defun org-auto-export-on()
(interactive)
(cond
((string-match "LATEX_CMD: latex" (buffer-string))
(add-hook 'after-save-hook 'org-export-pdf-then-refresh t t)
(split-window-right)
(windmove-right)
(org-open-file (org-latex-export-to-pdf))
(windmove-left))))
(after! org
(setq org-highlight-latex-and-related nil)
(setq org-hide-emphasis-markers t) ; Hides ugly markup symbols
(setq org-agenda-skip-scheduled-if-done t
org-ellipsis " ... "
org-fontify-emphasized-text t
;; org-ellipsis "➞"
; org-add-link-type "yt" #'make-yt-link
org-todo-keywords '((sequence "TODO(t)" "TIP(T)" "INPROGRESS(i)" "WAITING(w)" "|" "DONE(d)" "CANCELLED(c)"))
org-todo-keyword-faces
'(("TODO" :foreground "#943d84" :weight bold :underline t)
("TIP" :foreground "#29e3e3")
("WAITING" :foreground "#9f7efe" :weight normal :underline t)
("INPROGRESS" :foreground "#0098dd" :weight normal :underline t)
("DONE" :strike-through t :foreground "#2F2F4A" :background nil :weight light :underline t)
("CANCELLED" :strike-through t :foreground "#de286e" :background nil :weight light :underline t))
org-priority-faces '((?A :foreground "#de286e")
(?B :foreground "#0098dd")
(?C :foreground "#a1a1dd"))
; org-tags-column -80
))
(setq org-directory "~/org/")
;; (defun md-auto-export-on()
;; (interactive)
;; (add-hook 'after-save-hook 'org-md-export-to-markdown)
;; )
;; (eval-after-load 'org-mode
;; '(local-set-key (kbd "C-m") #'md-auto-export-on))
(setq org-startup-folded t)
; (defun make-yt-link (youtube_id)
; (browse-url (concat "https://www.youtube.com/embed/" youtube_id)))
(use-package org-brain :ensure t
:init
(setq org-brain-path "~/org/brain/")
;; For Evil users
(with-eval-after-load 'evil
(evil-set-initial-state 'org-brain-visualize-mode 'emacs))
:config
(bind-key "C-c b" 'org-brain-prefix-map org-mode-map)
(setq org-id-track-globally t)
(setq org-id-locations-file "~/.emacs.d/.org-id-locations")
(add-hook 'before-save-hook #'org-brain-ensure-ids-in-buffer)
(push '("b" "Brain" plain (function org-brain-goto-end)
"* %i%?" :empty-lines 1)
org-capture-templates)
(setq org-brain-visualize-default-choices 'all)
(setq org-brain-title-max-length 12)
(setq org-brain-include-file-entries nil
org-brain-file-entries-use-title nil))
;; Allows you to edit entries directly from org-brain-visualize
(use-package polymode
:config
(add-hook 'org-brain-visualize-mode-hook #'org-brain-polymode))
(use-package! org-fancy-priorities
:hook (org-mode . org-fancy-priorities-mode)
:config
(setq org-fancy-priorities-list '("" "" "")))
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups '((:name "Today"
:time-grid t
:scheduled today)
(:name "Due today"
:deadline today)
(:name "Important"
:priority "A")
(:name "Overdue"
:deadline past)
(:name "Due soon"
:deadline future)
(:name "Big Outcomes"
:tag "bo")))
:config
(org-super-agenda-mode))
;; (require 'org-superstar)
;; (setq org-bullets-face-name (quote org-bullet-face))
;; (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
;; (setq
;; org-superstar-headline-bullets-list '("⁖" "✲" "✱" "✻" "✼" "✥" "✿" "❀" "❁" "❂" "❃" "❄" "❅" "❆" "❇")
;; org-superstar-cycle-headline-bullets t
;; org-superstar-item-bullet-alist t
;; org-superstar-prettify-item-bullets t)
(load! "binds")
(load "~/.erc-auth")
;; (load! "agenda-files")
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(package-selected-packages
(quote
(vimish-fold rainbow-mode ivy-avy forge evil-snipe evil-multiedit evil-avy))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
| 21865 | ;;; config.el --- -*- lexical-binding: t -*-
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(add-to-list 'package-archives
'("gnu" . "http://elpa.gnu.org/packages/"))
(package-initialize)
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(setq package-check-signature nil)
(eval-when-compile
(require 'use-package))
(setq auto-window-vscroll nil)
(setq scroll-conservatively 101)
;; (add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(setq-default indent-tabs-mode nil)
(setq user-full-name "<NAME>"
user-mail-address "<EMAIL>")
(setq org-time-stamp-custom-formats '("[%a, %m/%d/%y]" . "[%a, %m/%d/%y -- %H:%M]"))
(setq
doom-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-variable-pitch-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-theme 'shado
projectile-project-search-path '("~/.xmonad/" "~/Documents/Programming/" "~/dwm/"))
(set-face-foreground 'line-number "#a1a1dd") ; Line number colors
(set-face-foreground 'line-number-current-line "#de286e") ; Current line number color
;; (add-to-list 'default-frame-alist '(background-color . "#0f0f17")) ; Background color
(add-to-list 'default-frame-alist '(background-color . "#08080d")) ; Background color
;; (annotate-mode)
;;; integrate ido with artist-mode
(defun artist-ido-select-operation (type)
"Use ido to select a drawing operation in artist-mode"
(interactive (list (ido-completing-read "Drawing operation: "
(list "Pen" "Pen Line" "line" "straight line" "rectangle"
"square" "poly-line" "straight poly-line" "ellipse"
"circle" "text see-thru" "text-overwrite" "spray-can"
"erase char" "erase rectangle" "vaporize line" "vaporize lines"
"cut rectangle" "cut square" "copy rectangle" "copy square"
"paste" "flood-fill"))))
(artist-select-operation type))
(defun artist-ido-select-settings (type)
"Use ido to select a setting to change in artist-mode"
(interactive (list (ido-completing-read "Setting: "
(list "Set Fill" "Set Line" "Set Erase" "Spray-size" "Spray-chars"
"Rubber-banding" "Trimming" "Borders"))))
(if (equal type "Spray-size")
(artist-select-operation "spray set size")
(call-interactively (artist-fc-get-fn-from-symbol
(cdr (assoc type '(("Set Fill" . set-fill)
("Set Line" . set-line)
("Set Erase" . set-erase)
("Rubber-banding" . rubber-band)
("Trimming" . trimming)
("Borders" . borders)
("Spray-chars" . spray-chars))))))))
;; (avy-setup-default)
(global-set-key (kbd "C-c C-j") 'avy-resume)
(require 'company)
(setq company-idle-delay 0.01
company-minimum-prefix-length 2)
(setq deft-directory "~/org"
deft-exensions '("org")
deft-recursive t)
(setq doom-modeline-height 10)
(set-face-attribute 'mode-line nil :family "Agave" :height 10)
(set-face-attribute 'mode-line-inactive nil :family "Agave" :height 10)
(defun start-erc ()
"Log into freenode with less keystrokes"
(interactive)
(let
((password-cache nil))
(erc
:server "irc.freenode.net"
:port "6667"
:nick erc-nick
:password <PASSWORD>)))
;; (load "escreen")
;; (escreen-install)
;; (global-set-key escreen-prefix-char 'escreen-prefix)
;; (require 'eyebrowse)
;; (use-package eyebrowse ; Easy workspaces creation and switching
;; :ensure t
;; :config
;; (validate-setq eyebrowse-mode-line-separator " "
;; eyebrowse-new-workspace t)
(eyebrowse-mode t)
(require 'evil-snipe)
(evil-snipe-mode +1)
(evil-snipe-override-mode +1)
(add-hook 'magit-mode-hook 'turn-off-evil-snipe-override-mode)
(flyspell-mode 0)
(add-to-list 'load-path "~/.emacs.d/lib/gpastel/")
(setq haskell-process-log t)
(add-hook 'haskell-mode-hook 'haskell-indent-mode)
(add-hook 'haskell-mode-hook 'interactive-haskell-mode)
(add-hook 'haskell-mode-hook 'haskell-doc-mode)
(add-hook 'haskell-mode-hook 'hindent-mode)
(require 'lsp)
(require 'lsp-haskell)
(add-hook 'haskell-mode-hook #'lsp)
(require 'hlinum)
(hlinum-activate)
(setq display-line-numbers-type 'relative) ; Relative line numbers with current line shown
(use-package outline
:diminish outline-minor-mode
:config
(use-package outline-minor-faces
:ensure
:hook
(outline-minor-mode-hook . outline-minor-faces-add-font-lock-keywords)))
(global-set-key (kbd "C-`") 'outline-show-entry)
(global-set-key (kbd "C-~") 'outline-hide-entry)
(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu4e")
(require 'mu4e)
;; (require 'ox-latex)
;; (require 'pdf-tools)
;; ;; (setq Tex-auto-save t)
;; ;; (setq Tex-parse-self t)
;; ;; (setq-default Tex-master nil)
;; ;; (add-hook 'LaTeX-mode-hook 'visual-line-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'flyspell-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex)
;; ;; (setq reftex-plug-into-AUCTeX t)
;; ;; (setq TeX-PDF-mode t)
;; ;; (pdf-tools-install)
;; (with-eval-after-load 'pdf-tools
;; (require 'pdf-sync))
;; (use-package pdf-tools
;; :init (pdf-tools-install)
;; :bind (:map pdf-view-mode-map
;; ("T" . pdf-annot-add-text-annotation)
;; ("D" . pdf-annot-delete)
;; ("t" . pdf-annot-add-highlight-markup-annotation)
;; ("j" . image-next-line)
;; ("k" . image-previous-line)
;; ("l" . image-forward-hscroll)
;; ("h" . image-backward-hscroll)
;; ("G" . pdf-view-last-page)
;; ("g" . nil)
;; ("gg" . pdf-view-first-page)
;; ("C-c C-c" . image-toggle-display)
;; ("C-s" . isearch-forward))
;; :config
;; (setq-default pdf-view-display-size 'fit-page)
;; :custom
;; (yas-minor-mode nil)
;; (pdf-cache-image-limit 32)
;; (pdf-view-max-image-width 2048)
;; (pdf-view-resize-factor 1.8)
;; (pdf-isearch-batch-mode t)
;; (pdf-annot-activate-created-annotations t))
;; (setq pdf-sync-backward-display-action t)
;; (setq pdf-sync-forward-display-action t)
(use-package pdf-tools
:ensure t
:config
(pdf-tools-install)
(setq-default pdf-view-display-size 'fit-page)
(setq pdf-annot-activate-created-annotations t)
(define-key pdf-view-mode-map (kbd "C-s") 'isearch-forward)
(define-key pdf-view-mode-map (kbd "C-r") 'isearch-backward)
;; (add-hook 'pdf-view-mode-hook (lambda ()
;; (bms/pdf-midnite-amber))) ; automatically turns on midnight-mode for pdfs
)
;; (use-package auctex-latexmk
;; :ensure t
;; :config
;; (auctex-latexmk-setup)
;; (setq auctex-latexmk-inherit-TeX-PDF-mode t))
;; (use-package reftex
;; :ensure t
;; :defer t
;; :config
;; (setq reftex-cite-prompt-optional-args t)) ;; Prompt for empty optional arguments in cite
;; (use-package auto-dictionary
;; :ensure t
;; :init(add-hook 'flyspell-mode-hook (lambda () (auto-dictionary-mode 1))))
(use-package company-auctex
:ensure t
:init (company-auctex-init))
(use-package tex
:ensure auctex
:mode ("\\.tex\\'" . latex-mode)
:config (progn
(vimish-fold-from-marks)
(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-auto-save t)
(setq TeX-parse-self t)
(pdf-tools-install)
(setq TeX-view-program-selection '((output-pdf "PDF Tools"))
TeX-source-correlate-start-server t)
;; Update PDF buffers after successful LaTeX runs
(add-hook 'TeX-after-compilation-finished-functions
#'TeX-revert-document-buffer)
))
(add-hook 'pdf-view-mode-hook (lambda ()
(pdf-view-midnight-minor-mode))) ; automatically turns on midnight-mode for pdfs
(setq pdf-view-midnight-colors '("#BFAEE3" . "#0a0a12" )) ; #0a0a12 #6f88e8 #e1acff Set custom colors
(defun bms/pdf-no-filter ()
"View pdf without colour filter."
(interactive)
(pdf-view-midnight-minor-mode -1))
; (use-package! rainbow-mode)
(use-package yasnippet
:config
(yas-global-mode 1)
(yas-load-directory "~/.doom.d/snippets/")
(setq yasnippet-snippets-dir "~/.doom.d/snippets/"))
(setq vimish-fold-find-marks-on-open t)
(turn-off-evil-vimish-fold-mode)
(vimish-fold-from-marks)
;; (global-whitespace-mode 1)
;; (progn
;; (setq whitespace-style (quote (face spaces tabs space-mark tab-mark )))
;; (setq whitespace-display-mappings
;; '((space-mark 32 [183] [46]) ; SPACE 32 「 」, 183 MIDDLE DOT 「·」, 46 FULL STOP 「.」; 4347
;; (tab-mark 9 [9655 9] [92 9])))) ; tabs
;; (add-hook 'c-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'emacs-lisp-mode 'rc/set-up-whitespace-handling)
;; (add-hook 'markdown-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'asm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'nasm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'haskell-mode-hook 'rc/set-up-whitespace-handling)
(require 'eglot)
(add-to-list 'eglot-server-programs '((c++-mode c-mode) "clangd"))
(add-hook 'c-mode-hook 'eglot-ensure)
(add-hook 'c++-mode-hook 'eglot-ensure)
(setq
split-width-threshold 0
split-height-threshold nil)
(global-auto-revert-mode t)
(setq TeX-command-force "LaTex")
(defun latex-export-pdf-then-refresh()
(TeX-command-master))
(defun latex-auto-export-on()
(interactive)
(add-hook 'after-save-hook 'latex-export-pdf-then-refresh t t)
(TeX-command-run-all TeX-command-buffer)
(windmove-left))
(defun org-export-pdf-then-refresh()
(org-latex-export-to-pdf))
(defun org-auto-export-on()
(interactive)
(cond
((string-match "LATEX_CMD: latex" (buffer-string))
(add-hook 'after-save-hook 'org-export-pdf-then-refresh t t)
(split-window-right)
(windmove-right)
(org-open-file (org-latex-export-to-pdf))
(windmove-left))))
(after! org
(setq org-highlight-latex-and-related nil)
(setq org-hide-emphasis-markers t) ; Hides ugly markup symbols
(setq org-agenda-skip-scheduled-if-done t
org-ellipsis " ... "
org-fontify-emphasized-text t
;; org-ellipsis "➞"
; org-add-link-type "yt" #'make-yt-link
org-todo-keywords '((sequence "TODO(t)" "TIP(T)" "INPROGRESS(i)" "WAITING(w)" "|" "DONE(d)" "CANCELLED(c)"))
org-todo-keyword-faces
'(("TODO" :foreground "#943d84" :weight bold :underline t)
("TIP" :foreground "#29e3e3")
("WAITING" :foreground "#9f7efe" :weight normal :underline t)
("INPROGRESS" :foreground "#0098dd" :weight normal :underline t)
("DONE" :strike-through t :foreground "#2F2F4A" :background nil :weight light :underline t)
("CANCELLED" :strike-through t :foreground "#de286e" :background nil :weight light :underline t))
org-priority-faces '((?A :foreground "#de286e")
(?B :foreground "#0098dd")
(?C :foreground "#a1a1dd"))
; org-tags-column -80
))
(setq org-directory "~/org/")
;; (defun md-auto-export-on()
;; (interactive)
;; (add-hook 'after-save-hook 'org-md-export-to-markdown)
;; )
;; (eval-after-load 'org-mode
;; '(local-set-key (kbd "C-m") #'md-auto-export-on))
(setq org-startup-folded t)
; (defun make-yt-link (youtube_id)
; (browse-url (concat "https://www.youtube.com/embed/" youtube_id)))
(use-package org-brain :ensure t
:init
(setq org-brain-path "~/org/brain/")
;; For Evil users
(with-eval-after-load 'evil
(evil-set-initial-state 'org-brain-visualize-mode 'emacs))
:config
(bind-key "C-c b" 'org-brain-prefix-map org-mode-map)
(setq org-id-track-globally t)
(setq org-id-locations-file "~/.emacs.d/.org-id-locations")
(add-hook 'before-save-hook #'org-brain-ensure-ids-in-buffer)
(push '("b" "Brain" plain (function org-brain-goto-end)
"* %i%?" :empty-lines 1)
org-capture-templates)
(setq org-brain-visualize-default-choices 'all)
(setq org-brain-title-max-length 12)
(setq org-brain-include-file-entries nil
org-brain-file-entries-use-title nil))
;; Allows you to edit entries directly from org-brain-visualize
(use-package polymode
:config
(add-hook 'org-brain-visualize-mode-hook #'org-brain-polymode))
(use-package! org-fancy-priorities
:hook (org-mode . org-fancy-priorities-mode)
:config
(setq org-fancy-priorities-list '("" "" "")))
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups '((:name "Today"
:time-grid t
:scheduled today)
(:name "Due today"
:deadline today)
(:name "Important"
:priority "A")
(:name "Overdue"
:deadline past)
(:name "Due soon"
:deadline future)
(:name "Big Outcomes"
:tag "bo")))
:config
(org-super-agenda-mode))
;; (require 'org-superstar)
;; (setq org-bullets-face-name (quote org-bullet-face))
;; (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
;; (setq
;; org-superstar-headline-bullets-list '("⁖" "✲" "✱" "✻" "✼" "✥" "✿" "❀" "❁" "❂" "❃" "❄" "❅" "❆" "❇")
;; org-superstar-cycle-headline-bullets t
;; org-superstar-item-bullet-alist t
;; org-superstar-prettify-item-bullets t)
(load! "binds")
(load "~/.erc-auth")
;; (load! "agenda-files")
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(package-selected-packages
(quote
(vimish-fold rainbow-mode ivy-avy forge evil-snipe evil-multiedit evil-avy))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
| true | ;;; config.el --- -*- lexical-binding: t -*-
(require 'package)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(add-to-list 'package-archives
'("gnu" . "http://elpa.gnu.org/packages/"))
(package-initialize)
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(setq package-check-signature nil)
(eval-when-compile
(require 'use-package))
(setq auto-window-vscroll nil)
(setq scroll-conservatively 101)
;; (add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(setq-default indent-tabs-mode nil)
(setq user-full-name "PI:NAME:<NAME>END_PI"
user-mail-address "PI:EMAIL:<EMAIL>END_PI")
(setq org-time-stamp-custom-formats '("[%a, %m/%d/%y]" . "[%a, %m/%d/%y -- %H:%M]"))
(setq
doom-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-variable-pitch-font (font-spec :family "Mononoki Nerd Font" :size 16)
doom-theme 'shado
projectile-project-search-path '("~/.xmonad/" "~/Documents/Programming/" "~/dwm/"))
(set-face-foreground 'line-number "#a1a1dd") ; Line number colors
(set-face-foreground 'line-number-current-line "#de286e") ; Current line number color
;; (add-to-list 'default-frame-alist '(background-color . "#0f0f17")) ; Background color
(add-to-list 'default-frame-alist '(background-color . "#08080d")) ; Background color
;; (annotate-mode)
;;; integrate ido with artist-mode
(defun artist-ido-select-operation (type)
"Use ido to select a drawing operation in artist-mode"
(interactive (list (ido-completing-read "Drawing operation: "
(list "Pen" "Pen Line" "line" "straight line" "rectangle"
"square" "poly-line" "straight poly-line" "ellipse"
"circle" "text see-thru" "text-overwrite" "spray-can"
"erase char" "erase rectangle" "vaporize line" "vaporize lines"
"cut rectangle" "cut square" "copy rectangle" "copy square"
"paste" "flood-fill"))))
(artist-select-operation type))
(defun artist-ido-select-settings (type)
"Use ido to select a setting to change in artist-mode"
(interactive (list (ido-completing-read "Setting: "
(list "Set Fill" "Set Line" "Set Erase" "Spray-size" "Spray-chars"
"Rubber-banding" "Trimming" "Borders"))))
(if (equal type "Spray-size")
(artist-select-operation "spray set size")
(call-interactively (artist-fc-get-fn-from-symbol
(cdr (assoc type '(("Set Fill" . set-fill)
("Set Line" . set-line)
("Set Erase" . set-erase)
("Rubber-banding" . rubber-band)
("Trimming" . trimming)
("Borders" . borders)
("Spray-chars" . spray-chars))))))))
;; (avy-setup-default)
(global-set-key (kbd "C-c C-j") 'avy-resume)
(require 'company)
(setq company-idle-delay 0.01
company-minimum-prefix-length 2)
(setq deft-directory "~/org"
deft-exensions '("org")
deft-recursive t)
(setq doom-modeline-height 10)
(set-face-attribute 'mode-line nil :family "Agave" :height 10)
(set-face-attribute 'mode-line-inactive nil :family "Agave" :height 10)
(defun start-erc ()
"Log into freenode with less keystrokes"
(interactive)
(let
((password-cache nil))
(erc
:server "irc.freenode.net"
:port "6667"
:nick erc-nick
:password PI:PASSWORD:<PASSWORD>END_PI)))
;; (load "escreen")
;; (escreen-install)
;; (global-set-key escreen-prefix-char 'escreen-prefix)
;; (require 'eyebrowse)
;; (use-package eyebrowse ; Easy workspaces creation and switching
;; :ensure t
;; :config
;; (validate-setq eyebrowse-mode-line-separator " "
;; eyebrowse-new-workspace t)
(eyebrowse-mode t)
(require 'evil-snipe)
(evil-snipe-mode +1)
(evil-snipe-override-mode +1)
(add-hook 'magit-mode-hook 'turn-off-evil-snipe-override-mode)
(flyspell-mode 0)
(add-to-list 'load-path "~/.emacs.d/lib/gpastel/")
(setq haskell-process-log t)
(add-hook 'haskell-mode-hook 'haskell-indent-mode)
(add-hook 'haskell-mode-hook 'interactive-haskell-mode)
(add-hook 'haskell-mode-hook 'haskell-doc-mode)
(add-hook 'haskell-mode-hook 'hindent-mode)
(require 'lsp)
(require 'lsp-haskell)
(add-hook 'haskell-mode-hook #'lsp)
(require 'hlinum)
(hlinum-activate)
(setq display-line-numbers-type 'relative) ; Relative line numbers with current line shown
(use-package outline
:diminish outline-minor-mode
:config
(use-package outline-minor-faces
:ensure
:hook
(outline-minor-mode-hook . outline-minor-faces-add-font-lock-keywords)))
(global-set-key (kbd "C-`") 'outline-show-entry)
(global-set-key (kbd "C-~") 'outline-hide-entry)
(add-to-list 'load-path "/usr/local/share/emacs/site-lisp/mu4e")
(require 'mu4e)
;; (require 'ox-latex)
;; (require 'pdf-tools)
;; ;; (setq Tex-auto-save t)
;; ;; (setq Tex-parse-self t)
;; ;; (setq-default Tex-master nil)
;; ;; (add-hook 'LaTeX-mode-hook 'visual-line-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'flyspell-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)
;; ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex)
;; ;; (setq reftex-plug-into-AUCTeX t)
;; ;; (setq TeX-PDF-mode t)
;; ;; (pdf-tools-install)
;; (with-eval-after-load 'pdf-tools
;; (require 'pdf-sync))
;; (use-package pdf-tools
;; :init (pdf-tools-install)
;; :bind (:map pdf-view-mode-map
;; ("T" . pdf-annot-add-text-annotation)
;; ("D" . pdf-annot-delete)
;; ("t" . pdf-annot-add-highlight-markup-annotation)
;; ("j" . image-next-line)
;; ("k" . image-previous-line)
;; ("l" . image-forward-hscroll)
;; ("h" . image-backward-hscroll)
;; ("G" . pdf-view-last-page)
;; ("g" . nil)
;; ("gg" . pdf-view-first-page)
;; ("C-c C-c" . image-toggle-display)
;; ("C-s" . isearch-forward))
;; :config
;; (setq-default pdf-view-display-size 'fit-page)
;; :custom
;; (yas-minor-mode nil)
;; (pdf-cache-image-limit 32)
;; (pdf-view-max-image-width 2048)
;; (pdf-view-resize-factor 1.8)
;; (pdf-isearch-batch-mode t)
;; (pdf-annot-activate-created-annotations t))
;; (setq pdf-sync-backward-display-action t)
;; (setq pdf-sync-forward-display-action t)
(use-package pdf-tools
:ensure t
:config
(pdf-tools-install)
(setq-default pdf-view-display-size 'fit-page)
(setq pdf-annot-activate-created-annotations t)
(define-key pdf-view-mode-map (kbd "C-s") 'isearch-forward)
(define-key pdf-view-mode-map (kbd "C-r") 'isearch-backward)
;; (add-hook 'pdf-view-mode-hook (lambda ()
;; (bms/pdf-midnite-amber))) ; automatically turns on midnight-mode for pdfs
)
;; (use-package auctex-latexmk
;; :ensure t
;; :config
;; (auctex-latexmk-setup)
;; (setq auctex-latexmk-inherit-TeX-PDF-mode t))
;; (use-package reftex
;; :ensure t
;; :defer t
;; :config
;; (setq reftex-cite-prompt-optional-args t)) ;; Prompt for empty optional arguments in cite
;; (use-package auto-dictionary
;; :ensure t
;; :init(add-hook 'flyspell-mode-hook (lambda () (auto-dictionary-mode 1))))
(use-package company-auctex
:ensure t
:init (company-auctex-init))
(use-package tex
:ensure auctex
:mode ("\\.tex\\'" . latex-mode)
:config (progn
(vimish-fold-from-marks)
(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-auto-save t)
(setq TeX-parse-self t)
(pdf-tools-install)
(setq TeX-view-program-selection '((output-pdf "PDF Tools"))
TeX-source-correlate-start-server t)
;; Update PDF buffers after successful LaTeX runs
(add-hook 'TeX-after-compilation-finished-functions
#'TeX-revert-document-buffer)
))
(add-hook 'pdf-view-mode-hook (lambda ()
(pdf-view-midnight-minor-mode))) ; automatically turns on midnight-mode for pdfs
(setq pdf-view-midnight-colors '("#BFAEE3" . "#0a0a12" )) ; #0a0a12 #6f88e8 #e1acff Set custom colors
(defun bms/pdf-no-filter ()
"View pdf without colour filter."
(interactive)
(pdf-view-midnight-minor-mode -1))
; (use-package! rainbow-mode)
(use-package yasnippet
:config
(yas-global-mode 1)
(yas-load-directory "~/.doom.d/snippets/")
(setq yasnippet-snippets-dir "~/.doom.d/snippets/"))
(setq vimish-fold-find-marks-on-open t)
(turn-off-evil-vimish-fold-mode)
(vimish-fold-from-marks)
;; (global-whitespace-mode 1)
;; (progn
;; (setq whitespace-style (quote (face spaces tabs space-mark tab-mark )))
;; (setq whitespace-display-mappings
;; '((space-mark 32 [183] [46]) ; SPACE 32 「 」, 183 MIDDLE DOT 「·」, 46 FULL STOP 「.」; 4347
;; (tab-mark 9 [9655 9] [92 9])))) ; tabs
;; (add-hook 'c-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'emacs-lisp-mode 'rc/set-up-whitespace-handling)
;; (add-hook 'markdown-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'asm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'nasm-mode-hook 'rc/set-up-whitespace-handling)
;; (add-hook 'haskell-mode-hook 'rc/set-up-whitespace-handling)
(require 'eglot)
(add-to-list 'eglot-server-programs '((c++-mode c-mode) "clangd"))
(add-hook 'c-mode-hook 'eglot-ensure)
(add-hook 'c++-mode-hook 'eglot-ensure)
(setq
split-width-threshold 0
split-height-threshold nil)
(global-auto-revert-mode t)
(setq TeX-command-force "LaTex")
(defun latex-export-pdf-then-refresh()
(TeX-command-master))
(defun latex-auto-export-on()
(interactive)
(add-hook 'after-save-hook 'latex-export-pdf-then-refresh t t)
(TeX-command-run-all TeX-command-buffer)
(windmove-left))
(defun org-export-pdf-then-refresh()
(org-latex-export-to-pdf))
(defun org-auto-export-on()
(interactive)
(cond
((string-match "LATEX_CMD: latex" (buffer-string))
(add-hook 'after-save-hook 'org-export-pdf-then-refresh t t)
(split-window-right)
(windmove-right)
(org-open-file (org-latex-export-to-pdf))
(windmove-left))))
(after! org
(setq org-highlight-latex-and-related nil)
(setq org-hide-emphasis-markers t) ; Hides ugly markup symbols
(setq org-agenda-skip-scheduled-if-done t
org-ellipsis " ... "
org-fontify-emphasized-text t
;; org-ellipsis "➞"
; org-add-link-type "yt" #'make-yt-link
org-todo-keywords '((sequence "TODO(t)" "TIP(T)" "INPROGRESS(i)" "WAITING(w)" "|" "DONE(d)" "CANCELLED(c)"))
org-todo-keyword-faces
'(("TODO" :foreground "#943d84" :weight bold :underline t)
("TIP" :foreground "#29e3e3")
("WAITING" :foreground "#9f7efe" :weight normal :underline t)
("INPROGRESS" :foreground "#0098dd" :weight normal :underline t)
("DONE" :strike-through t :foreground "#2F2F4A" :background nil :weight light :underline t)
("CANCELLED" :strike-through t :foreground "#de286e" :background nil :weight light :underline t))
org-priority-faces '((?A :foreground "#de286e")
(?B :foreground "#0098dd")
(?C :foreground "#a1a1dd"))
; org-tags-column -80
))
(setq org-directory "~/org/")
;; (defun md-auto-export-on()
;; (interactive)
;; (add-hook 'after-save-hook 'org-md-export-to-markdown)
;; )
;; (eval-after-load 'org-mode
;; '(local-set-key (kbd "C-m") #'md-auto-export-on))
(setq org-startup-folded t)
; (defun make-yt-link (youtube_id)
; (browse-url (concat "https://www.youtube.com/embed/" youtube_id)))
(use-package org-brain :ensure t
:init
(setq org-brain-path "~/org/brain/")
;; For Evil users
(with-eval-after-load 'evil
(evil-set-initial-state 'org-brain-visualize-mode 'emacs))
:config
(bind-key "C-c b" 'org-brain-prefix-map org-mode-map)
(setq org-id-track-globally t)
(setq org-id-locations-file "~/.emacs.d/.org-id-locations")
(add-hook 'before-save-hook #'org-brain-ensure-ids-in-buffer)
(push '("b" "Brain" plain (function org-brain-goto-end)
"* %i%?" :empty-lines 1)
org-capture-templates)
(setq org-brain-visualize-default-choices 'all)
(setq org-brain-title-max-length 12)
(setq org-brain-include-file-entries nil
org-brain-file-entries-use-title nil))
;; Allows you to edit entries directly from org-brain-visualize
(use-package polymode
:config
(add-hook 'org-brain-visualize-mode-hook #'org-brain-polymode))
(use-package! org-fancy-priorities
:hook (org-mode . org-fancy-priorities-mode)
:config
(setq org-fancy-priorities-list '("" "" "")))
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups '((:name "Today"
:time-grid t
:scheduled today)
(:name "Due today"
:deadline today)
(:name "Important"
:priority "A")
(:name "Overdue"
:deadline past)
(:name "Due soon"
:deadline future)
(:name "Big Outcomes"
:tag "bo")))
:config
(org-super-agenda-mode))
;; (require 'org-superstar)
;; (setq org-bullets-face-name (quote org-bullet-face))
;; (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1)))
;; (setq
;; org-superstar-headline-bullets-list '("⁖" "✲" "✱" "✻" "✼" "✥" "✿" "❀" "❁" "❂" "❃" "❄" "❅" "❆" "❇")
;; org-superstar-cycle-headline-bullets t
;; org-superstar-item-bullet-alist t
;; org-superstar-prettify-item-bullets t)
(load! "binds")
(load "~/.erc-auth")
;; (load! "agenda-files")
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(package-selected-packages
(quote
(vimish-fold rainbow-mode ivy-avy forge evil-snipe evil-multiedit evil-avy))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
|
[
{
"context": "exical-binding: t; -*-\n\n;; Copyright (C) 2003-2016 John Wiegley (johnw AT gnu DOT org)\n\n;; This file is not part ",
"end": 149,
"score": 0.9998655319213867,
"start": 137,
"tag": "NAME",
"value": "John Wiegley"
}
] | emacs.d/elpa/ledger-mode-20210329.2024/ledger-state.el | farynaio/dot-env | 0 | ;;; ledger-state.el --- Helper code for use with the "ledger" command-line tool -*- lexical-binding: t; -*-
;; Copyright (C) 2003-2016 John Wiegley (johnw AT gnu DOT org)
;; This file is not part of GNU Emacs.
;; This 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 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:
;; Utilities for dealing with transaction and posting status.
;;; Code:
(require 'ledger-navigate)
(require 'ledger-context)
(defcustom ledger-clear-whole-transactions nil
"If non-nil, clear whole transactions, not individual postings."
:type 'boolean
:group 'ledger)
(defun ledger-transaction-state ()
"Return the state of the transaction at point."
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t nil)))))
(defun ledger-posting-state ()
"Return the state of the posting."
(save-excursion
(goto-char (line-beginning-position))
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t (ledger-transaction-state)))))
(defun ledger-char-from-state (state)
"Return the char representation of STATE."
(if state
(if (eq state 'pending)
"!"
"*")
""))
(defun ledger-state-from-char (state-char)
"Get state from STATE-CHAR."
(cond ((eql state-char ?\!) 'pending)
((eql state-char ?\*) 'cleared)
((eql state-char ?\;) 'comment)
(t nil)))
(defun ledger-state-from-string (state-string)
"Get state from STATE-STRING."
(when state-string
(cond
((string-match "!" state-string) 'pending)
((string-match "\\*" state-string) 'cleared)
((string-match ";" state-string) 'comment)
(t nil))))
(defun ledger-toggle-current-posting (&optional style)
"Toggle the cleared status of the transaction under point.
Optional argument STYLE may be `pending' or `cleared', depending
on which type of status the caller wishes to indicate (default is
`cleared'). Returns the new status as 'pending 'cleared or nil.
This function is rather complicated because it must preserve both
the overall formatting of the ledger xact, as well as ensuring
that the most minimal display format is used. This could be
achieved more certainly by passing the xact to ledger for
formatting, but doing so causes inline math expressions to be
dropped."
(interactive)
(let ((bounds (ledger-navigate-find-xact-extents (point)))
new-status cur-status)
;; Uncompact the xact, to make it easier to toggle the
;; transaction
(save-excursion ;; this excursion checks state of entire
;; transaction and unclears if marked
(goto-char (car bounds)) ;; beginning of xact
(skip-chars-forward "0-9./=\\-") ;; skip the date
(skip-chars-forward " \t") ;; skip the white space after the date
(setq cur-status (and (member (char-after) '(?\* ?\!))
(ledger-state-from-char (char-after))))
;;if cur-status if !, or * then delete the marker
(when cur-status
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(forward-line)
;; Shift the cleared/pending status to the postings
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(when (not (eq (ledger-state-from-char (char-after)) 'comment))
(insert (ledger-char-from-state cur-status) " ")
(if (and (search-forward " " (line-end-position) t)
(looking-at " "))
(delete-char 2)))
(forward-line))
(setq new-status nil)))
;;this excursion toggles the posting status
(save-excursion
(setq inhibit-modification-hooks t)
(goto-char (line-beginning-position))
(when (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point))
(cur-status (ledger-state-from-char (char-after))))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(save-excursion
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(let (inserted)
(if cur-status
(if (and style (eq style 'cleared))
(progn
(insert "* ")
(setq inserted 'cleared)))
(if (and style (eq style 'pending))
(progn
(insert "! ")
(setq inserted 'pending))
(progn
(insert "* ")
(setq inserted 'cleared))))
(if (and inserted
(re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t))
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1))))
(setq new-status inserted))))
(setq inhibit-modification-hooks nil))
;; This excursion cleans up the xact so that it displays
;; minimally. This means that if all posts are cleared, remove
;; the marks and clear the entire transaction.
(save-excursion
(goto-char (car bounds))
(forward-line)
(let ((first t)
(state nil)
(hetero nil))
(while (and (not hetero) (looking-at "[ \t]"))
(skip-chars-forward " \t")
(let ((cur-status (ledger-state-from-char (char-after))))
(if (not (eq cur-status 'comment))
(if first
(setq state cur-status
first nil)
(if (not (eq state cur-status))
(setq hetero t)))))
(forward-line))
(when (and (not hetero) (not (eq state nil)))
(goto-char (car bounds))
(forward-line)
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(insert (make-string width ? ))))))
(forward-line))
(goto-char (car bounds))
(skip-chars-forward "0-9./=\\-") ;; Skip the date
(skip-chars-forward " \t") ;; Skip the white space
(insert (ledger-char-from-state state) " ")
(setq new-status state)
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1)))))))
new-status))
(defun ledger-toggle-current (&optional style)
"Toggle the current thing at point with optional STYLE."
(interactive)
(if (or ledger-clear-whole-transactions
(eq 'transaction (ledger-thing-at-point)))
(progn
(save-excursion
(forward-line)
(goto-char (line-beginning-position))
(while (and (not (eolp))
(save-excursion
(not (eq 'transaction (ledger-thing-at-point)))))
(if (looking-at "\\s-+[*!]")
(ledger-toggle-current-posting style))
(forward-line)
(goto-char (line-beginning-position))))
(ledger-toggle-current-transaction style))
(ledger-toggle-current-posting style)))
(defun ledger-toggle-current-transaction (&optional style)
"Toggle the transaction at point using optional STYLE."
(interactive)
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(delete-horizontal-space)
(if (or (eq (ledger-state-from-char (char-after)) 'pending)
(eq (ledger-state-from-char (char-after)) 'cleared))
(progn
(delete-char 1)
(when (and style (eq style 'cleared))
(insert " *")
'cleared))
(if (and style (eq style 'pending))
(progn
(insert " ! ")
'pending)
(progn
(insert " * ")
'cleared))))))
(provide 'ledger-state)
;;; ledger-state.el ends here
| 29123 | ;;; ledger-state.el --- Helper code for use with the "ledger" command-line tool -*- lexical-binding: t; -*-
;; Copyright (C) 2003-2016 <NAME> (johnw AT gnu DOT org)
;; This file is not part of GNU Emacs.
;; This 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 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:
;; Utilities for dealing with transaction and posting status.
;;; Code:
(require 'ledger-navigate)
(require 'ledger-context)
(defcustom ledger-clear-whole-transactions nil
"If non-nil, clear whole transactions, not individual postings."
:type 'boolean
:group 'ledger)
(defun ledger-transaction-state ()
"Return the state of the transaction at point."
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t nil)))))
(defun ledger-posting-state ()
"Return the state of the posting."
(save-excursion
(goto-char (line-beginning-position))
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t (ledger-transaction-state)))))
(defun ledger-char-from-state (state)
"Return the char representation of STATE."
(if state
(if (eq state 'pending)
"!"
"*")
""))
(defun ledger-state-from-char (state-char)
"Get state from STATE-CHAR."
(cond ((eql state-char ?\!) 'pending)
((eql state-char ?\*) 'cleared)
((eql state-char ?\;) 'comment)
(t nil)))
(defun ledger-state-from-string (state-string)
"Get state from STATE-STRING."
(when state-string
(cond
((string-match "!" state-string) 'pending)
((string-match "\\*" state-string) 'cleared)
((string-match ";" state-string) 'comment)
(t nil))))
(defun ledger-toggle-current-posting (&optional style)
"Toggle the cleared status of the transaction under point.
Optional argument STYLE may be `pending' or `cleared', depending
on which type of status the caller wishes to indicate (default is
`cleared'). Returns the new status as 'pending 'cleared or nil.
This function is rather complicated because it must preserve both
the overall formatting of the ledger xact, as well as ensuring
that the most minimal display format is used. This could be
achieved more certainly by passing the xact to ledger for
formatting, but doing so causes inline math expressions to be
dropped."
(interactive)
(let ((bounds (ledger-navigate-find-xact-extents (point)))
new-status cur-status)
;; Uncompact the xact, to make it easier to toggle the
;; transaction
(save-excursion ;; this excursion checks state of entire
;; transaction and unclears if marked
(goto-char (car bounds)) ;; beginning of xact
(skip-chars-forward "0-9./=\\-") ;; skip the date
(skip-chars-forward " \t") ;; skip the white space after the date
(setq cur-status (and (member (char-after) '(?\* ?\!))
(ledger-state-from-char (char-after))))
;;if cur-status if !, or * then delete the marker
(when cur-status
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(forward-line)
;; Shift the cleared/pending status to the postings
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(when (not (eq (ledger-state-from-char (char-after)) 'comment))
(insert (ledger-char-from-state cur-status) " ")
(if (and (search-forward " " (line-end-position) t)
(looking-at " "))
(delete-char 2)))
(forward-line))
(setq new-status nil)))
;;this excursion toggles the posting status
(save-excursion
(setq inhibit-modification-hooks t)
(goto-char (line-beginning-position))
(when (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point))
(cur-status (ledger-state-from-char (char-after))))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(save-excursion
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(let (inserted)
(if cur-status
(if (and style (eq style 'cleared))
(progn
(insert "* ")
(setq inserted 'cleared)))
(if (and style (eq style 'pending))
(progn
(insert "! ")
(setq inserted 'pending))
(progn
(insert "* ")
(setq inserted 'cleared))))
(if (and inserted
(re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t))
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1))))
(setq new-status inserted))))
(setq inhibit-modification-hooks nil))
;; This excursion cleans up the xact so that it displays
;; minimally. This means that if all posts are cleared, remove
;; the marks and clear the entire transaction.
(save-excursion
(goto-char (car bounds))
(forward-line)
(let ((first t)
(state nil)
(hetero nil))
(while (and (not hetero) (looking-at "[ \t]"))
(skip-chars-forward " \t")
(let ((cur-status (ledger-state-from-char (char-after))))
(if (not (eq cur-status 'comment))
(if first
(setq state cur-status
first nil)
(if (not (eq state cur-status))
(setq hetero t)))))
(forward-line))
(when (and (not hetero) (not (eq state nil)))
(goto-char (car bounds))
(forward-line)
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(insert (make-string width ? ))))))
(forward-line))
(goto-char (car bounds))
(skip-chars-forward "0-9./=\\-") ;; Skip the date
(skip-chars-forward " \t") ;; Skip the white space
(insert (ledger-char-from-state state) " ")
(setq new-status state)
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1)))))))
new-status))
(defun ledger-toggle-current (&optional style)
"Toggle the current thing at point with optional STYLE."
(interactive)
(if (or ledger-clear-whole-transactions
(eq 'transaction (ledger-thing-at-point)))
(progn
(save-excursion
(forward-line)
(goto-char (line-beginning-position))
(while (and (not (eolp))
(save-excursion
(not (eq 'transaction (ledger-thing-at-point)))))
(if (looking-at "\\s-+[*!]")
(ledger-toggle-current-posting style))
(forward-line)
(goto-char (line-beginning-position))))
(ledger-toggle-current-transaction style))
(ledger-toggle-current-posting style)))
(defun ledger-toggle-current-transaction (&optional style)
"Toggle the transaction at point using optional STYLE."
(interactive)
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(delete-horizontal-space)
(if (or (eq (ledger-state-from-char (char-after)) 'pending)
(eq (ledger-state-from-char (char-after)) 'cleared))
(progn
(delete-char 1)
(when (and style (eq style 'cleared))
(insert " *")
'cleared))
(if (and style (eq style 'pending))
(progn
(insert " ! ")
'pending)
(progn
(insert " * ")
'cleared))))))
(provide 'ledger-state)
;;; ledger-state.el ends here
| true | ;;; ledger-state.el --- Helper code for use with the "ledger" command-line tool -*- lexical-binding: t; -*-
;; Copyright (C) 2003-2016 PI:NAME:<NAME>END_PI (johnw AT gnu DOT org)
;; This file is not part of GNU Emacs.
;; This 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 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:
;; Utilities for dealing with transaction and posting status.
;;; Code:
(require 'ledger-navigate)
(require 'ledger-context)
(defcustom ledger-clear-whole-transactions nil
"If non-nil, clear whole transactions, not individual postings."
:type 'boolean
:group 'ledger)
(defun ledger-transaction-state ()
"Return the state of the transaction at point."
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t nil)))))
(defun ledger-posting-state ()
"Return the state of the posting."
(save-excursion
(goto-char (line-beginning-position))
(skip-syntax-forward " ")
(cond ((looking-at "!\\s-*") 'pending)
((looking-at "\\*\\s-*") 'cleared)
(t (ledger-transaction-state)))))
(defun ledger-char-from-state (state)
"Return the char representation of STATE."
(if state
(if (eq state 'pending)
"!"
"*")
""))
(defun ledger-state-from-char (state-char)
"Get state from STATE-CHAR."
(cond ((eql state-char ?\!) 'pending)
((eql state-char ?\*) 'cleared)
((eql state-char ?\;) 'comment)
(t nil)))
(defun ledger-state-from-string (state-string)
"Get state from STATE-STRING."
(when state-string
(cond
((string-match "!" state-string) 'pending)
((string-match "\\*" state-string) 'cleared)
((string-match ";" state-string) 'comment)
(t nil))))
(defun ledger-toggle-current-posting (&optional style)
"Toggle the cleared status of the transaction under point.
Optional argument STYLE may be `pending' or `cleared', depending
on which type of status the caller wishes to indicate (default is
`cleared'). Returns the new status as 'pending 'cleared or nil.
This function is rather complicated because it must preserve both
the overall formatting of the ledger xact, as well as ensuring
that the most minimal display format is used. This could be
achieved more certainly by passing the xact to ledger for
formatting, but doing so causes inline math expressions to be
dropped."
(interactive)
(let ((bounds (ledger-navigate-find-xact-extents (point)))
new-status cur-status)
;; Uncompact the xact, to make it easier to toggle the
;; transaction
(save-excursion ;; this excursion checks state of entire
;; transaction and unclears if marked
(goto-char (car bounds)) ;; beginning of xact
(skip-chars-forward "0-9./=\\-") ;; skip the date
(skip-chars-forward " \t") ;; skip the white space after the date
(setq cur-status (and (member (char-after) '(?\* ?\!))
(ledger-state-from-char (char-after))))
;;if cur-status if !, or * then delete the marker
(when cur-status
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(forward-line)
;; Shift the cleared/pending status to the postings
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(when (not (eq (ledger-state-from-char (char-after)) 'comment))
(insert (ledger-char-from-state cur-status) " ")
(if (and (search-forward " " (line-end-position) t)
(looking-at " "))
(delete-char 2)))
(forward-line))
(setq new-status nil)))
;;this excursion toggles the posting status
(save-excursion
(setq inhibit-modification-hooks t)
(goto-char (line-beginning-position))
(when (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point))
(cur-status (ledger-state-from-char (char-after))))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(save-excursion
(if (search-forward " " (line-end-position) t)
(insert (make-string width ? ))))))
(let (inserted)
(if cur-status
(if (and style (eq style 'cleared))
(progn
(insert "* ")
(setq inserted 'cleared)))
(if (and style (eq style 'pending))
(progn
(insert "! ")
(setq inserted 'pending))
(progn
(insert "* ")
(setq inserted 'cleared))))
(if (and inserted
(re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t))
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1))))
(setq new-status inserted))))
(setq inhibit-modification-hooks nil))
;; This excursion cleans up the xact so that it displays
;; minimally. This means that if all posts are cleared, remove
;; the marks and clear the entire transaction.
(save-excursion
(goto-char (car bounds))
(forward-line)
(let ((first t)
(state nil)
(hetero nil))
(while (and (not hetero) (looking-at "[ \t]"))
(skip-chars-forward " \t")
(let ((cur-status (ledger-state-from-char (char-after))))
(if (not (eq cur-status 'comment))
(if first
(setq state cur-status
first nil)
(if (not (eq state cur-status))
(setq hetero t)))))
(forward-line))
(when (and (not hetero) (not (eq state nil)))
(goto-char (car bounds))
(forward-line)
(while (looking-at "[ \t]")
(skip-chars-forward " \t")
(let ((here (point)))
(skip-chars-forward "*! ")
(let ((width (- (point) here)))
(when (> width 0)
(delete-region here (point))
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(insert (make-string width ? ))))))
(forward-line))
(goto-char (car bounds))
(skip-chars-forward "0-9./=\\-") ;; Skip the date
(skip-chars-forward " \t") ;; Skip the white space
(insert (ledger-char-from-state state) " ")
(setq new-status state)
(if (re-search-forward "\\(\t\\| [ \t]\\)"
(line-end-position) t)
(cond
((looking-at "\t")
(delete-char 1))
((looking-at " [ \t]")
(delete-char 2))
((looking-at " ")
(delete-char 1)))))))
new-status))
(defun ledger-toggle-current (&optional style)
"Toggle the current thing at point with optional STYLE."
(interactive)
(if (or ledger-clear-whole-transactions
(eq 'transaction (ledger-thing-at-point)))
(progn
(save-excursion
(forward-line)
(goto-char (line-beginning-position))
(while (and (not (eolp))
(save-excursion
(not (eq 'transaction (ledger-thing-at-point)))))
(if (looking-at "\\s-+[*!]")
(ledger-toggle-current-posting style))
(forward-line)
(goto-char (line-beginning-position))))
(ledger-toggle-current-transaction style))
(ledger-toggle-current-posting style)))
(defun ledger-toggle-current-transaction (&optional style)
"Toggle the transaction at point using optional STYLE."
(interactive)
(save-excursion
(when (or (looking-at "^[0-9]")
(re-search-backward "^[0-9]" nil t))
(skip-chars-forward "0-9./=\\-")
(delete-horizontal-space)
(if (or (eq (ledger-state-from-char (char-after)) 'pending)
(eq (ledger-state-from-char (char-after)) 'cleared))
(progn
(delete-char 1)
(when (and style (eq style 'cleared))
(insert " *")
'cleared))
(if (and style (eq style 'pending))
(progn
(insert " ! ")
'pending)
(progn
(insert " * ")
'cleared))))))
(provide 'ledger-state)
;;; ledger-state.el ends here
|
[
{
"context": "tions file for Spacemacs.\n;;\n;; Copyright (c) 2017 Balakrishnan Chandrasekaran\n;;\n;; Author: Balakrishnan Chandrasekaran <balakr",
"end": 121,
"score": 0.9998736381530762,
"start": 94,
"tag": "NAME",
"value": "Balakrishnan Chandrasekaran"
},
{
"context": "(c) 2017 Balakrishnan Chandrasekaran\n;;\n;; Author: Balakrishnan Chandrasekaran <balakrishnan.c@gmail.com>\n;; URL: https://github",
"end": 163,
"score": 0.9998776316642761,
"start": 136,
"tag": "NAME",
"value": "Balakrishnan Chandrasekaran"
},
{
"context": "ekaran\n;;\n;; Author: Balakrishnan Chandrasekaran <balakrishnan.c@gmail.com>\n;; URL: https://github.com/balakrishnanc/emacs-p",
"end": 189,
"score": 0.999934196472168,
"start": 165,
"tag": "EMAIL",
"value": "balakrishnan.c@gmail.com"
},
{
"context": "akrishnan.c@gmail.com>\n;; URL: https://github.com/balakrishnanc/emacs-personalization\n;;\n;;; License: MIT\n\n;;; Co",
"end": 231,
"score": 0.9942780137062073,
"start": 218,
"tag": "USERNAME",
"value": "balakrishnanc"
}
] | funcs.el | balakrishnanc/emacs-personalization | 0 | ;;; funcs.el --- personalization layer functions file for Spacemacs.
;;
;; Copyright (c) 2017 Balakrishnan Chandrasekaran
;;
;; Author: Balakrishnan Chandrasekaran <balakrishnan.c@gmail.com>
;; URL: https://github.com/balakrishnanc/emacs-personalization
;;
;;; License: MIT
;;; Commentary:
;;; Code:
;; --- Boilerplates. ---
;; --------------------------------------------------
(defun insert-timestamp ()
"Insert timestamp at point."
(interactive)
(insert (format-time-string timestamp-fmt)))
(defun update-file-headers ()
"Updates the variables in the header."
(let ((buf-file-name (file-name-nondirectory buffer-file-name))
(file-mod-ts (format-time-string timestamp-fmt)))
(save-excursion
(while (re-search-forward file-name-placeholder nil t)
(replace-match buf-file-name t nil))
(goto-char (point-min))
(while (re-search-forward timestamp-placeholder nil t)
(replace-match file-mod-ts t nil)))))
(defun update-project-name ()
"Updates the project name in the header."
(interactive)
(let ((proj-name (read-from-minibuffer "Project Name? ")))
(save-excursion
(while (re-search-forward proj-name-placeholder nil t)
(replace-match proj-name t nil)))))
(defun code-template (file-ext)
"Given file extension provide the template to use."
(let ((rule (lambda (lang ext)
(cons (concat "\\." file-ext "$")
(vector
(concat lang "-template." ext)
#'update-file-headers)))))
(cond ((string= "c" file-ext) (funcall rule "c" "c"))
((string= "cc" file-ext) (funcall rule "c" "c"))
((string= "clj" file-ext) (funcall rule "clojure" "clj"))
((string= "cpp" file-ext) (funcall rule "c" "c"))
((string= "erl" file-ext) (funcall rule "erlang" "erl"))
((string= "go" file-ext) (funcall rule "go" "go"))
((string= "gpi" file-ext) (funcall rule "gnuplot" "plot"))
((string= "h" file-ext) (funcall rule "c" "c"))
((string= "hs" file-ext) (funcall rule "haskell" "hs"))
((string= "java" file-ext) (funcall rule "java" "java"))
((string= "jl" file-ext) (funcall rule "julia" "jl"))
((string= "lisp" file-ext) (funcall rule "lisp" "lisp"))
((string= "pl" file-ext) (funcall rule "perl" "pl"))
((string= "plot" file-ext) (funcall rule "gnuplot" "plot"))
((string= "py" file-ext) (funcall rule "python" "py"))
((string= "scala" file-ext) (funcall rule "scala" "scala"))
((string= "scm" file-ext) (funcall rule "scheme" "scm"))
((string= "sh" file-ext) (funcall rule "bash" "sh"))
((string= "sql" file-ext) (funcall rule "sql" "sql")))))
(defun setup-file-boilerplates ()
"Setup boilerplates for various files based on extensions."
(setq-default auto-insert-directory code-templates-dir)
(setq-default auto-insert-alist
(cl-loop for i in '("c" "cc" "clj" "cpp" "erl"
"go" "gpi" "h" "hs" "java"
"jl" "lisp" "pl" "plot" "py"
"scala" "scm" "sh" "sql")
collecting (code-template i)))
;; Automatically insert boilerplates.
(add-hook 'find-file-hooks 'auto-insert))
;; --- Enable easy editing. ---
;; --------------------------------------------------
(defun indent-on-paste ()
"Indent text on paste."
(dolist (command '(yank yank-pop))
(eval `(defadvice ,command (after indent-region activate)
(and (not current-prefix-arg)
(member major-mode
'(emacs-lisp-mode
lisp-mode
clojure-mode
go-mode
ruby-mode
latex-mode
c-mode
c++-mode
;; indent-on-paste sucks in the following modes.
;; python-mode
;; haskell-mode
))
(let ((mark-even-if-inactive transient-mark-mode))
(indent-region (region-beginning) (region-end) nil)))))))
(defun kill-and-join-forward (&optional arg)
"If at end of line, join with following; otherwise kill line.
Deletes whitespace at join."
(interactive "P")
(if (and (eolp) (not (bolp)))
(delete-indentation t)
(kill-line arg)))
;; --- Auto saves and backups. ---
;; --------------------------------------------------
(defun make-auto-save-file-name ()
(if buffer-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(file-name-nondirectory buffer-file-name)
"-"
system-name)
(expand-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(buffer-name)
"-"
system-name))))
(defun make-dir (dir-path)
"Create directory, if it does not exist."
(if (not (file-exists-p dir-path))
(make-directory dir-path t)))
(defadvice auto-save-mode (around auto-saves-dir)
"Use a standard location for auto-save files for non-file buffers."
(if (not buffer-file-name)
(let ((default-directory auto-saves-dir))
ad-do-it)
ad-do-it))
(defun setup-auto-saves-and-bkups ()
"Setup auto-saves and auto-backups."
(make-dir auto-saves-dir)
(setq-default auto-save-list-file-prefix auto-saves-dir)
(setq-default auto-save-file-name-transforms
`((".*" ,auto-saves-dir t)))
(make-dir auto-bkups-dir)
(setq-default backup-directory-alist
`((".*" . ,auto-bkups-dir)))
(ad-activate 'auto-save-mode)
(setq auto-save-interval 30)
;; Save when focus is lost.
(add-hook 'focus-out-hook
(defun save-all-unsaved-buffers ()
(interactive)
(save-some-buffers t))))
(defun recover-this-buffer ()
"Recover current buffer from auto-save file, if any."
(interactive)
(if (buffer-file-name)
(recover-this-file)
(recover-file (buffer-name))))
;; --- Distraction free writing. ---
;; --------------------------------------------------
(defun disable-distraction-free-writing ()
"Disable distraction-free-writing mode."
(progn
(olivetti-mode -1)
;; Disable visual line mode.
(visual-line-mode -1)
;; NOTE: `visual-line-mode' affects `truncate-lines' and `word-wrap'.
;; Enable `truncate-lines' feature.
(toggle-truncate-lines 1)
;; Disable centered cursor mode.
(centered-cursor-mode -1)
;; Show mode line.
(hidden-mode-line-mode -1)
(message "distraction-free-writing mode disabled.")
(put 'toggle-distraction-free-writing 'state nil)))
(defun enable-distraction-free-writing ()
"Enable distraction-free-writing mode."
(progn
(olivetti-set-width 81)
(olivetti-mode 1)
(spacemacs/toggle-vi-tilde-fringe-off)
;; Enable visual line mode.
(visual-line-mode 1)
;; Disable `truncate-lines' feature.
(toggle-truncate-lines -1)
;; Keep text being edited in the center of the screen.
(centered-cursor-mode 1)
;; Hide mode line.
(hidden-mode-line-mode 1)
(message "distraction-free-writing mode enabled.")
(put 'toggle-distraction-free-writing 'state t)))
(defun toggle-distraction-free-writing (&optional arg)
"Toggle distraction-free writing."
(interactive "p")
(if (get 'toggle-distraction-free-writing 'state)
(disable-distraction-free-writing)
(enable-distraction-free-writing)))
;; --- Customize look and feel. ---
;; --------------------------------------------------
(defun customize-look-and-feel ()
"Customize how the editor frame or window looks and feels."
;; Increase space between text and the border or fringe.
(add-to-list 'default-frame-alist '(internal-border-width . 20))
(global-prettify-symbols-mode t)
;; Highlight current line.
(global-hl-line-mode -1))
;; --- Customize modes.
;; --------------------------------------------------
(defun setup-lisp-mode ()
"Customize `lisp-mode'."
(add-hook 'lisp-mode-hook
(lambda ()
(progn
(let ((slime-config (concat (file-name-as-directory ext-config-dir)
(file-name-as-directory "quicklisp")
"slime-helper.el")))
(when (file-exists-p slime-config)
(load slime-config)))
(let ((sbcl-bin "/usr/local/bin/sbcl"))
(when (and (file-exists-p sbcl-bin)
(file-executable-p sbcl-bin))
(setq inferior-lisp-program sbcl-bin)))
;; ;; Minor mode to keep S-expressions safely balanced.
;; (spacemacs/toggle-evil-safe-lisp-structural-editing-on-register-hook-common-lisp-mode)
(pretty-mode)))))
(defun setup-programming-mode ()
"Add customizations to setup a development environment."
;; Turn on support for boilerplates.
(setup-file-boilerplates)
;; Tack on customizations to the `prog-mode-hook'.
(add-hook 'prog-mode-hook
(lambda ()
;; Turn off line-truncation; wrap lines around.
(toggle-truncate-lines -1)
(pretty-mode)))
;; Set execute permissions automatically when saving scripts.
(add-hook 'after-save-hook
'executable-make-buffer-file-executable-if-script-p)
(setup-lisp-mode))
(defun can-use-font? (font-name)
"Returns 't' only if emacs can recognize the font face."
(if (x-list-fonts font-name)
t
nil))
(defun fmt-org-bullets ()
"Customize bullets in `org-mode'"
(font-lock-add-keywords 'org-mode
'(("^ *\\([+]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"•"))))
("^ *\\([-]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"⋯")))))))
(defun fmt-org-mode-style ()
"Customize `org-mode' look and feel."
(let* ((base-font-color (face-foreground 'default nil 'default))
(heading-font `(:font ,serif-font-face))
(heading-attrs `(:inherit default
:weight bold)))
(custom-theme-set-faces
'user
`(org-block ((t (:inherit fixed-pitch))))
`(org-block-begin-line ((t (:inherit fixed-pitch))))
`(org-block-end-line ((t (:inherit org-block-begin-line))))
`(org-code ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info ((t (:foreground "#fb5607"))))
`(org-document-info-keyword ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info-title ((t (:inherit (shadow fixed-pitch)
:weight bold :underline nil))))
`(org-indent ((t (:inherit (org-hide fixed-pitch)))))
`(org-link ((t (:foreground "#3a86ff" :underline t))))
`(org-list-dt ((t (:inherit variable-pitch :height 0.7))))
`(org-meta-line ((t (:inherit (font-lock-comment-face fixed-pitch)))))
`(org-property-value ((t (:inherit fixed-pitch))) t)
`(org-special-keyword ((t (:inherit (font-lock-comment-face
fixed-pitch)))))
`(org-table ((t (:inherit fixed-pitch :foreground "#83a598"))))
`(org-tag ((t (:inherit (shadow fixed-pitch) :weight bold :height 0.8))))
`(org-verbatim ((t (:inherit (shadow fixed-pitch)))))
`(org-level-8 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-7 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-6 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-5 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-4 ((t (,@heading-attrs ,@heading-font :height 1.1))))
`(org-level-3 ((t (,@heading-attrs ,@heading-font :height 1.2))))
`(org-level-2 ((t (,@heading-attrs ,@heading-font :height 1.3))))
`(org-level-1 ((t (,@heading-attrs ,@heading-font :height 1.4)))))))
(defun setup-org-mode ()
"Customize `org-mode'."
(with-eval-after-load 'org
(progn
(setq
org-fontify-whole-heading-line t
org-fontify-done-headline t
org-fontify-emphasized-text t
org-fontify-quote-and-verse-blocks t
org-src-fontify-natively t
org-hide-emphasis-markers t
org-hide-leading-stars t
org-indent-mode t
org-pretty-entities t
org-use-sub-superscripts "{}"
org-startup-indented t
spaceline-org-clock-p t)
(fmt-org-bullets)
(fmt-org-mode-style)
(evil-leader/set-key "t ;" 'org-toggle-narrow-to-subtree)))
(add-hook 'org-mode-hook
(lambda ()
(progn
;; For `org-mode' to _safely_ store notes.
(auto-save-mode 1)
;; For customizing look and feel.
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-latex-mode ()
"Customize `latex-mode'."
(with-eval-after-load 'latex
(progn
(setq-default TeX-master nil)
(custom-theme-set-faces
'user
`(font-latex-math-face ((t (:inherit (shadow fixed-pitch) :height 0.9))))
`(font-lock-function-name-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-lock-constant-face ((t (:inherit fixed-pitch :height 1.0 :weight bold))))
`(font-latex-sedate-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-latex-sectioning-2-face ((t (:inherit variable-pitch :height 1.0 :weight bold)))))))
(add-hook 'LaTeX-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing))))
;; Perform full-document previews.
(add-hook 'doc-view-mode-hook 'auto-revert-mode))
(defun setup-text-mode ()
"Customize `text-mode'."
(add-hook 'text-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-markdown-mode ()
"Customize `markdown-mode'."
(with-eval-after-load 'markdown
(progn
(custom-theme-set-faces
'user
`(markdown-inline-code-face ((t (:inherit
(markdown-code-face
markdown-pre-face
shadow
fixed-pitch) :height 1.0)))))))
(add-hook 'markdown-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(typo-mode -1)
(enable-distraction-free-writing)))))
(defun customize-modes ()
"Customize different modes."
(custom-theme-set-faces
'user
;; `(default ((t (:family ,base-font-face
;; :slant normal
;; :height 120))))
`(variable-pitch ((t (:family ,serif-font-face
:height 1.6
:weight normal))))
`(fixed-pitch ((t (:family ,monospace-font-face
:slant normal
:height 0.8)))))
(setup-programming-mode)
(setup-org-mode)
(setup-latex-mode)
(setup-text-mode)
(setup-markdown-mode))
;; --- Common editor preferences. ---
;; --------------------------------------------------
(defun handle-delete-frame-without-kill-emacs (event)
"Handle delete-frame events from the X server."
(interactive "e")
(let ((frame (posn-window (event-start event)))
(i 0)
(tail (frame-list)))
(while tail
(and (frame-visible-p (car tail))
(not (eq (car tail) frame))
(setq i (1+ i)))
(setq tail (cdr tail)))
(if (> i 0)
(delete-frame frame t)
;; Not (save-buffers-kill-emacs) but instead:
(ns-do-hide-emacs))))
(defun use-utf-8-everywhere ()
"Use utf-8 everywhere."
(set-language-environment 'utf-8)
(set-default-coding-systems 'utf-8))
(defun customize-editor-behavior ()
"Customize common editor behavior."
;; Start server.
(setq-default dotspacemacs-enable-server t)
(use-utf-8-everywhere)
(setup-auto-saves-and-bkups)
;; Use '4' spaces instead of a 'tab' character.
(setq-default tab-width 4)
(setq-default indent-tabs-mode nil)
;; By default, set column width to '80' characters.
(setq-default fill-column 80)
;; Ensure files always end with a new line.
(setq-default require-final-newline t)
;; Stop emacs from arbitrarily adding lines to the end of a file,
;; when cursor is moved past the end of it.
(setq-default next-line-add-newlines nil)
;; Show recently opened files in helm.
(setq-default helm-ff-file-name-history-use-recentf t)
;; Configure projectile to use `.projectile' files, if any, in the project directory.
(setq projectile-indexing-method 'hybrid)
(when (eq system-type 'darwin)
(advice-add 'handle-delete-frame :override
#'handle-delete-frame-without-kill-emacs)))
;;; funcs.el ends here
| 5731 | ;;; funcs.el --- personalization layer functions file for Spacemacs.
;;
;; Copyright (c) 2017 <NAME>
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/balakrishnanc/emacs-personalization
;;
;;; License: MIT
;;; Commentary:
;;; Code:
;; --- Boilerplates. ---
;; --------------------------------------------------
(defun insert-timestamp ()
"Insert timestamp at point."
(interactive)
(insert (format-time-string timestamp-fmt)))
(defun update-file-headers ()
"Updates the variables in the header."
(let ((buf-file-name (file-name-nondirectory buffer-file-name))
(file-mod-ts (format-time-string timestamp-fmt)))
(save-excursion
(while (re-search-forward file-name-placeholder nil t)
(replace-match buf-file-name t nil))
(goto-char (point-min))
(while (re-search-forward timestamp-placeholder nil t)
(replace-match file-mod-ts t nil)))))
(defun update-project-name ()
"Updates the project name in the header."
(interactive)
(let ((proj-name (read-from-minibuffer "Project Name? ")))
(save-excursion
(while (re-search-forward proj-name-placeholder nil t)
(replace-match proj-name t nil)))))
(defun code-template (file-ext)
"Given file extension provide the template to use."
(let ((rule (lambda (lang ext)
(cons (concat "\\." file-ext "$")
(vector
(concat lang "-template." ext)
#'update-file-headers)))))
(cond ((string= "c" file-ext) (funcall rule "c" "c"))
((string= "cc" file-ext) (funcall rule "c" "c"))
((string= "clj" file-ext) (funcall rule "clojure" "clj"))
((string= "cpp" file-ext) (funcall rule "c" "c"))
((string= "erl" file-ext) (funcall rule "erlang" "erl"))
((string= "go" file-ext) (funcall rule "go" "go"))
((string= "gpi" file-ext) (funcall rule "gnuplot" "plot"))
((string= "h" file-ext) (funcall rule "c" "c"))
((string= "hs" file-ext) (funcall rule "haskell" "hs"))
((string= "java" file-ext) (funcall rule "java" "java"))
((string= "jl" file-ext) (funcall rule "julia" "jl"))
((string= "lisp" file-ext) (funcall rule "lisp" "lisp"))
((string= "pl" file-ext) (funcall rule "perl" "pl"))
((string= "plot" file-ext) (funcall rule "gnuplot" "plot"))
((string= "py" file-ext) (funcall rule "python" "py"))
((string= "scala" file-ext) (funcall rule "scala" "scala"))
((string= "scm" file-ext) (funcall rule "scheme" "scm"))
((string= "sh" file-ext) (funcall rule "bash" "sh"))
((string= "sql" file-ext) (funcall rule "sql" "sql")))))
(defun setup-file-boilerplates ()
"Setup boilerplates for various files based on extensions."
(setq-default auto-insert-directory code-templates-dir)
(setq-default auto-insert-alist
(cl-loop for i in '("c" "cc" "clj" "cpp" "erl"
"go" "gpi" "h" "hs" "java"
"jl" "lisp" "pl" "plot" "py"
"scala" "scm" "sh" "sql")
collecting (code-template i)))
;; Automatically insert boilerplates.
(add-hook 'find-file-hooks 'auto-insert))
;; --- Enable easy editing. ---
;; --------------------------------------------------
(defun indent-on-paste ()
"Indent text on paste."
(dolist (command '(yank yank-pop))
(eval `(defadvice ,command (after indent-region activate)
(and (not current-prefix-arg)
(member major-mode
'(emacs-lisp-mode
lisp-mode
clojure-mode
go-mode
ruby-mode
latex-mode
c-mode
c++-mode
;; indent-on-paste sucks in the following modes.
;; python-mode
;; haskell-mode
))
(let ((mark-even-if-inactive transient-mark-mode))
(indent-region (region-beginning) (region-end) nil)))))))
(defun kill-and-join-forward (&optional arg)
"If at end of line, join with following; otherwise kill line.
Deletes whitespace at join."
(interactive "P")
(if (and (eolp) (not (bolp)))
(delete-indentation t)
(kill-line arg)))
;; --- Auto saves and backups. ---
;; --------------------------------------------------
(defun make-auto-save-file-name ()
(if buffer-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(file-name-nondirectory buffer-file-name)
"-"
system-name)
(expand-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(buffer-name)
"-"
system-name))))
(defun make-dir (dir-path)
"Create directory, if it does not exist."
(if (not (file-exists-p dir-path))
(make-directory dir-path t)))
(defadvice auto-save-mode (around auto-saves-dir)
"Use a standard location for auto-save files for non-file buffers."
(if (not buffer-file-name)
(let ((default-directory auto-saves-dir))
ad-do-it)
ad-do-it))
(defun setup-auto-saves-and-bkups ()
"Setup auto-saves and auto-backups."
(make-dir auto-saves-dir)
(setq-default auto-save-list-file-prefix auto-saves-dir)
(setq-default auto-save-file-name-transforms
`((".*" ,auto-saves-dir t)))
(make-dir auto-bkups-dir)
(setq-default backup-directory-alist
`((".*" . ,auto-bkups-dir)))
(ad-activate 'auto-save-mode)
(setq auto-save-interval 30)
;; Save when focus is lost.
(add-hook 'focus-out-hook
(defun save-all-unsaved-buffers ()
(interactive)
(save-some-buffers t))))
(defun recover-this-buffer ()
"Recover current buffer from auto-save file, if any."
(interactive)
(if (buffer-file-name)
(recover-this-file)
(recover-file (buffer-name))))
;; --- Distraction free writing. ---
;; --------------------------------------------------
(defun disable-distraction-free-writing ()
"Disable distraction-free-writing mode."
(progn
(olivetti-mode -1)
;; Disable visual line mode.
(visual-line-mode -1)
;; NOTE: `visual-line-mode' affects `truncate-lines' and `word-wrap'.
;; Enable `truncate-lines' feature.
(toggle-truncate-lines 1)
;; Disable centered cursor mode.
(centered-cursor-mode -1)
;; Show mode line.
(hidden-mode-line-mode -1)
(message "distraction-free-writing mode disabled.")
(put 'toggle-distraction-free-writing 'state nil)))
(defun enable-distraction-free-writing ()
"Enable distraction-free-writing mode."
(progn
(olivetti-set-width 81)
(olivetti-mode 1)
(spacemacs/toggle-vi-tilde-fringe-off)
;; Enable visual line mode.
(visual-line-mode 1)
;; Disable `truncate-lines' feature.
(toggle-truncate-lines -1)
;; Keep text being edited in the center of the screen.
(centered-cursor-mode 1)
;; Hide mode line.
(hidden-mode-line-mode 1)
(message "distraction-free-writing mode enabled.")
(put 'toggle-distraction-free-writing 'state t)))
(defun toggle-distraction-free-writing (&optional arg)
"Toggle distraction-free writing."
(interactive "p")
(if (get 'toggle-distraction-free-writing 'state)
(disable-distraction-free-writing)
(enable-distraction-free-writing)))
;; --- Customize look and feel. ---
;; --------------------------------------------------
(defun customize-look-and-feel ()
"Customize how the editor frame or window looks and feels."
;; Increase space between text and the border or fringe.
(add-to-list 'default-frame-alist '(internal-border-width . 20))
(global-prettify-symbols-mode t)
;; Highlight current line.
(global-hl-line-mode -1))
;; --- Customize modes.
;; --------------------------------------------------
(defun setup-lisp-mode ()
"Customize `lisp-mode'."
(add-hook 'lisp-mode-hook
(lambda ()
(progn
(let ((slime-config (concat (file-name-as-directory ext-config-dir)
(file-name-as-directory "quicklisp")
"slime-helper.el")))
(when (file-exists-p slime-config)
(load slime-config)))
(let ((sbcl-bin "/usr/local/bin/sbcl"))
(when (and (file-exists-p sbcl-bin)
(file-executable-p sbcl-bin))
(setq inferior-lisp-program sbcl-bin)))
;; ;; Minor mode to keep S-expressions safely balanced.
;; (spacemacs/toggle-evil-safe-lisp-structural-editing-on-register-hook-common-lisp-mode)
(pretty-mode)))))
(defun setup-programming-mode ()
"Add customizations to setup a development environment."
;; Turn on support for boilerplates.
(setup-file-boilerplates)
;; Tack on customizations to the `prog-mode-hook'.
(add-hook 'prog-mode-hook
(lambda ()
;; Turn off line-truncation; wrap lines around.
(toggle-truncate-lines -1)
(pretty-mode)))
;; Set execute permissions automatically when saving scripts.
(add-hook 'after-save-hook
'executable-make-buffer-file-executable-if-script-p)
(setup-lisp-mode))
(defun can-use-font? (font-name)
"Returns 't' only if emacs can recognize the font face."
(if (x-list-fonts font-name)
t
nil))
(defun fmt-org-bullets ()
"Customize bullets in `org-mode'"
(font-lock-add-keywords 'org-mode
'(("^ *\\([+]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"•"))))
("^ *\\([-]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"⋯")))))))
(defun fmt-org-mode-style ()
"Customize `org-mode' look and feel."
(let* ((base-font-color (face-foreground 'default nil 'default))
(heading-font `(:font ,serif-font-face))
(heading-attrs `(:inherit default
:weight bold)))
(custom-theme-set-faces
'user
`(org-block ((t (:inherit fixed-pitch))))
`(org-block-begin-line ((t (:inherit fixed-pitch))))
`(org-block-end-line ((t (:inherit org-block-begin-line))))
`(org-code ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info ((t (:foreground "#fb5607"))))
`(org-document-info-keyword ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info-title ((t (:inherit (shadow fixed-pitch)
:weight bold :underline nil))))
`(org-indent ((t (:inherit (org-hide fixed-pitch)))))
`(org-link ((t (:foreground "#3a86ff" :underline t))))
`(org-list-dt ((t (:inherit variable-pitch :height 0.7))))
`(org-meta-line ((t (:inherit (font-lock-comment-face fixed-pitch)))))
`(org-property-value ((t (:inherit fixed-pitch))) t)
`(org-special-keyword ((t (:inherit (font-lock-comment-face
fixed-pitch)))))
`(org-table ((t (:inherit fixed-pitch :foreground "#83a598"))))
`(org-tag ((t (:inherit (shadow fixed-pitch) :weight bold :height 0.8))))
`(org-verbatim ((t (:inherit (shadow fixed-pitch)))))
`(org-level-8 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-7 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-6 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-5 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-4 ((t (,@heading-attrs ,@heading-font :height 1.1))))
`(org-level-3 ((t (,@heading-attrs ,@heading-font :height 1.2))))
`(org-level-2 ((t (,@heading-attrs ,@heading-font :height 1.3))))
`(org-level-1 ((t (,@heading-attrs ,@heading-font :height 1.4)))))))
(defun setup-org-mode ()
"Customize `org-mode'."
(with-eval-after-load 'org
(progn
(setq
org-fontify-whole-heading-line t
org-fontify-done-headline t
org-fontify-emphasized-text t
org-fontify-quote-and-verse-blocks t
org-src-fontify-natively t
org-hide-emphasis-markers t
org-hide-leading-stars t
org-indent-mode t
org-pretty-entities t
org-use-sub-superscripts "{}"
org-startup-indented t
spaceline-org-clock-p t)
(fmt-org-bullets)
(fmt-org-mode-style)
(evil-leader/set-key "t ;" 'org-toggle-narrow-to-subtree)))
(add-hook 'org-mode-hook
(lambda ()
(progn
;; For `org-mode' to _safely_ store notes.
(auto-save-mode 1)
;; For customizing look and feel.
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-latex-mode ()
"Customize `latex-mode'."
(with-eval-after-load 'latex
(progn
(setq-default TeX-master nil)
(custom-theme-set-faces
'user
`(font-latex-math-face ((t (:inherit (shadow fixed-pitch) :height 0.9))))
`(font-lock-function-name-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-lock-constant-face ((t (:inherit fixed-pitch :height 1.0 :weight bold))))
`(font-latex-sedate-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-latex-sectioning-2-face ((t (:inherit variable-pitch :height 1.0 :weight bold)))))))
(add-hook 'LaTeX-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing))))
;; Perform full-document previews.
(add-hook 'doc-view-mode-hook 'auto-revert-mode))
(defun setup-text-mode ()
"Customize `text-mode'."
(add-hook 'text-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-markdown-mode ()
"Customize `markdown-mode'."
(with-eval-after-load 'markdown
(progn
(custom-theme-set-faces
'user
`(markdown-inline-code-face ((t (:inherit
(markdown-code-face
markdown-pre-face
shadow
fixed-pitch) :height 1.0)))))))
(add-hook 'markdown-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(typo-mode -1)
(enable-distraction-free-writing)))))
(defun customize-modes ()
"Customize different modes."
(custom-theme-set-faces
'user
;; `(default ((t (:family ,base-font-face
;; :slant normal
;; :height 120))))
`(variable-pitch ((t (:family ,serif-font-face
:height 1.6
:weight normal))))
`(fixed-pitch ((t (:family ,monospace-font-face
:slant normal
:height 0.8)))))
(setup-programming-mode)
(setup-org-mode)
(setup-latex-mode)
(setup-text-mode)
(setup-markdown-mode))
;; --- Common editor preferences. ---
;; --------------------------------------------------
(defun handle-delete-frame-without-kill-emacs (event)
"Handle delete-frame events from the X server."
(interactive "e")
(let ((frame (posn-window (event-start event)))
(i 0)
(tail (frame-list)))
(while tail
(and (frame-visible-p (car tail))
(not (eq (car tail) frame))
(setq i (1+ i)))
(setq tail (cdr tail)))
(if (> i 0)
(delete-frame frame t)
;; Not (save-buffers-kill-emacs) but instead:
(ns-do-hide-emacs))))
(defun use-utf-8-everywhere ()
"Use utf-8 everywhere."
(set-language-environment 'utf-8)
(set-default-coding-systems 'utf-8))
(defun customize-editor-behavior ()
"Customize common editor behavior."
;; Start server.
(setq-default dotspacemacs-enable-server t)
(use-utf-8-everywhere)
(setup-auto-saves-and-bkups)
;; Use '4' spaces instead of a 'tab' character.
(setq-default tab-width 4)
(setq-default indent-tabs-mode nil)
;; By default, set column width to '80' characters.
(setq-default fill-column 80)
;; Ensure files always end with a new line.
(setq-default require-final-newline t)
;; Stop emacs from arbitrarily adding lines to the end of a file,
;; when cursor is moved past the end of it.
(setq-default next-line-add-newlines nil)
;; Show recently opened files in helm.
(setq-default helm-ff-file-name-history-use-recentf t)
;; Configure projectile to use `.projectile' files, if any, in the project directory.
(setq projectile-indexing-method 'hybrid)
(when (eq system-type 'darwin)
(advice-add 'handle-delete-frame :override
#'handle-delete-frame-without-kill-emacs)))
;;; funcs.el ends here
| true | ;;; funcs.el --- personalization layer functions file for Spacemacs.
;;
;; Copyright (c) 2017 PI:NAME:<NAME>END_PI
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/balakrishnanc/emacs-personalization
;;
;;; License: MIT
;;; Commentary:
;;; Code:
;; --- Boilerplates. ---
;; --------------------------------------------------
(defun insert-timestamp ()
"Insert timestamp at point."
(interactive)
(insert (format-time-string timestamp-fmt)))
(defun update-file-headers ()
"Updates the variables in the header."
(let ((buf-file-name (file-name-nondirectory buffer-file-name))
(file-mod-ts (format-time-string timestamp-fmt)))
(save-excursion
(while (re-search-forward file-name-placeholder nil t)
(replace-match buf-file-name t nil))
(goto-char (point-min))
(while (re-search-forward timestamp-placeholder nil t)
(replace-match file-mod-ts t nil)))))
(defun update-project-name ()
"Updates the project name in the header."
(interactive)
(let ((proj-name (read-from-minibuffer "Project Name? ")))
(save-excursion
(while (re-search-forward proj-name-placeholder nil t)
(replace-match proj-name t nil)))))
(defun code-template (file-ext)
"Given file extension provide the template to use."
(let ((rule (lambda (lang ext)
(cons (concat "\\." file-ext "$")
(vector
(concat lang "-template." ext)
#'update-file-headers)))))
(cond ((string= "c" file-ext) (funcall rule "c" "c"))
((string= "cc" file-ext) (funcall rule "c" "c"))
((string= "clj" file-ext) (funcall rule "clojure" "clj"))
((string= "cpp" file-ext) (funcall rule "c" "c"))
((string= "erl" file-ext) (funcall rule "erlang" "erl"))
((string= "go" file-ext) (funcall rule "go" "go"))
((string= "gpi" file-ext) (funcall rule "gnuplot" "plot"))
((string= "h" file-ext) (funcall rule "c" "c"))
((string= "hs" file-ext) (funcall rule "haskell" "hs"))
((string= "java" file-ext) (funcall rule "java" "java"))
((string= "jl" file-ext) (funcall rule "julia" "jl"))
((string= "lisp" file-ext) (funcall rule "lisp" "lisp"))
((string= "pl" file-ext) (funcall rule "perl" "pl"))
((string= "plot" file-ext) (funcall rule "gnuplot" "plot"))
((string= "py" file-ext) (funcall rule "python" "py"))
((string= "scala" file-ext) (funcall rule "scala" "scala"))
((string= "scm" file-ext) (funcall rule "scheme" "scm"))
((string= "sh" file-ext) (funcall rule "bash" "sh"))
((string= "sql" file-ext) (funcall rule "sql" "sql")))))
(defun setup-file-boilerplates ()
"Setup boilerplates for various files based on extensions."
(setq-default auto-insert-directory code-templates-dir)
(setq-default auto-insert-alist
(cl-loop for i in '("c" "cc" "clj" "cpp" "erl"
"go" "gpi" "h" "hs" "java"
"jl" "lisp" "pl" "plot" "py"
"scala" "scm" "sh" "sql")
collecting (code-template i)))
;; Automatically insert boilerplates.
(add-hook 'find-file-hooks 'auto-insert))
;; --- Enable easy editing. ---
;; --------------------------------------------------
(defun indent-on-paste ()
"Indent text on paste."
(dolist (command '(yank yank-pop))
(eval `(defadvice ,command (after indent-region activate)
(and (not current-prefix-arg)
(member major-mode
'(emacs-lisp-mode
lisp-mode
clojure-mode
go-mode
ruby-mode
latex-mode
c-mode
c++-mode
;; indent-on-paste sucks in the following modes.
;; python-mode
;; haskell-mode
))
(let ((mark-even-if-inactive transient-mark-mode))
(indent-region (region-beginning) (region-end) nil)))))))
(defun kill-and-join-forward (&optional arg)
"If at end of line, join with following; otherwise kill line.
Deletes whitespace at join."
(interactive "P")
(if (and (eolp) (not (bolp)))
(delete-indentation t)
(kill-line arg)))
;; --- Auto saves and backups. ---
;; --------------------------------------------------
(defun make-auto-save-file-name ()
(if buffer-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(file-name-nondirectory buffer-file-name)
"-"
system-name)
(expand-file-name
(concat auto-saves-dir
auto-save-file-name-prefix
(buffer-name)
"-"
system-name))))
(defun make-dir (dir-path)
"Create directory, if it does not exist."
(if (not (file-exists-p dir-path))
(make-directory dir-path t)))
(defadvice auto-save-mode (around auto-saves-dir)
"Use a standard location for auto-save files for non-file buffers."
(if (not buffer-file-name)
(let ((default-directory auto-saves-dir))
ad-do-it)
ad-do-it))
(defun setup-auto-saves-and-bkups ()
"Setup auto-saves and auto-backups."
(make-dir auto-saves-dir)
(setq-default auto-save-list-file-prefix auto-saves-dir)
(setq-default auto-save-file-name-transforms
`((".*" ,auto-saves-dir t)))
(make-dir auto-bkups-dir)
(setq-default backup-directory-alist
`((".*" . ,auto-bkups-dir)))
(ad-activate 'auto-save-mode)
(setq auto-save-interval 30)
;; Save when focus is lost.
(add-hook 'focus-out-hook
(defun save-all-unsaved-buffers ()
(interactive)
(save-some-buffers t))))
(defun recover-this-buffer ()
"Recover current buffer from auto-save file, if any."
(interactive)
(if (buffer-file-name)
(recover-this-file)
(recover-file (buffer-name))))
;; --- Distraction free writing. ---
;; --------------------------------------------------
(defun disable-distraction-free-writing ()
"Disable distraction-free-writing mode."
(progn
(olivetti-mode -1)
;; Disable visual line mode.
(visual-line-mode -1)
;; NOTE: `visual-line-mode' affects `truncate-lines' and `word-wrap'.
;; Enable `truncate-lines' feature.
(toggle-truncate-lines 1)
;; Disable centered cursor mode.
(centered-cursor-mode -1)
;; Show mode line.
(hidden-mode-line-mode -1)
(message "distraction-free-writing mode disabled.")
(put 'toggle-distraction-free-writing 'state nil)))
(defun enable-distraction-free-writing ()
"Enable distraction-free-writing mode."
(progn
(olivetti-set-width 81)
(olivetti-mode 1)
(spacemacs/toggle-vi-tilde-fringe-off)
;; Enable visual line mode.
(visual-line-mode 1)
;; Disable `truncate-lines' feature.
(toggle-truncate-lines -1)
;; Keep text being edited in the center of the screen.
(centered-cursor-mode 1)
;; Hide mode line.
(hidden-mode-line-mode 1)
(message "distraction-free-writing mode enabled.")
(put 'toggle-distraction-free-writing 'state t)))
(defun toggle-distraction-free-writing (&optional arg)
"Toggle distraction-free writing."
(interactive "p")
(if (get 'toggle-distraction-free-writing 'state)
(disable-distraction-free-writing)
(enable-distraction-free-writing)))
;; --- Customize look and feel. ---
;; --------------------------------------------------
(defun customize-look-and-feel ()
"Customize how the editor frame or window looks and feels."
;; Increase space between text and the border or fringe.
(add-to-list 'default-frame-alist '(internal-border-width . 20))
(global-prettify-symbols-mode t)
;; Highlight current line.
(global-hl-line-mode -1))
;; --- Customize modes.
;; --------------------------------------------------
(defun setup-lisp-mode ()
"Customize `lisp-mode'."
(add-hook 'lisp-mode-hook
(lambda ()
(progn
(let ((slime-config (concat (file-name-as-directory ext-config-dir)
(file-name-as-directory "quicklisp")
"slime-helper.el")))
(when (file-exists-p slime-config)
(load slime-config)))
(let ((sbcl-bin "/usr/local/bin/sbcl"))
(when (and (file-exists-p sbcl-bin)
(file-executable-p sbcl-bin))
(setq inferior-lisp-program sbcl-bin)))
;; ;; Minor mode to keep S-expressions safely balanced.
;; (spacemacs/toggle-evil-safe-lisp-structural-editing-on-register-hook-common-lisp-mode)
(pretty-mode)))))
(defun setup-programming-mode ()
"Add customizations to setup a development environment."
;; Turn on support for boilerplates.
(setup-file-boilerplates)
;; Tack on customizations to the `prog-mode-hook'.
(add-hook 'prog-mode-hook
(lambda ()
;; Turn off line-truncation; wrap lines around.
(toggle-truncate-lines -1)
(pretty-mode)))
;; Set execute permissions automatically when saving scripts.
(add-hook 'after-save-hook
'executable-make-buffer-file-executable-if-script-p)
(setup-lisp-mode))
(defun can-use-font? (font-name)
"Returns 't' only if emacs can recognize the font face."
(if (x-list-fonts font-name)
t
nil))
(defun fmt-org-bullets ()
"Customize bullets in `org-mode'"
(font-lock-add-keywords 'org-mode
'(("^ *\\([+]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"•"))))
("^ *\\([-]\\) "
(0 (prog1 ()
(compose-region (match-beginning 1)
(match-end 1)
"⋯")))))))
(defun fmt-org-mode-style ()
"Customize `org-mode' look and feel."
(let* ((base-font-color (face-foreground 'default nil 'default))
(heading-font `(:font ,serif-font-face))
(heading-attrs `(:inherit default
:weight bold)))
(custom-theme-set-faces
'user
`(org-block ((t (:inherit fixed-pitch))))
`(org-block-begin-line ((t (:inherit fixed-pitch))))
`(org-block-end-line ((t (:inherit org-block-begin-line))))
`(org-code ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info ((t (:foreground "#fb5607"))))
`(org-document-info-keyword ((t (:inherit (shadow fixed-pitch)))))
`(org-document-info-title ((t (:inherit (shadow fixed-pitch)
:weight bold :underline nil))))
`(org-indent ((t (:inherit (org-hide fixed-pitch)))))
`(org-link ((t (:foreground "#3a86ff" :underline t))))
`(org-list-dt ((t (:inherit variable-pitch :height 0.7))))
`(org-meta-line ((t (:inherit (font-lock-comment-face fixed-pitch)))))
`(org-property-value ((t (:inherit fixed-pitch))) t)
`(org-special-keyword ((t (:inherit (font-lock-comment-face
fixed-pitch)))))
`(org-table ((t (:inherit fixed-pitch :foreground "#83a598"))))
`(org-tag ((t (:inherit (shadow fixed-pitch) :weight bold :height 0.8))))
`(org-verbatim ((t (:inherit (shadow fixed-pitch)))))
`(org-level-8 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-7 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-6 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-5 ((t (,@heading-attrs ,@heading-font :height 1.0))))
`(org-level-4 ((t (,@heading-attrs ,@heading-font :height 1.1))))
`(org-level-3 ((t (,@heading-attrs ,@heading-font :height 1.2))))
`(org-level-2 ((t (,@heading-attrs ,@heading-font :height 1.3))))
`(org-level-1 ((t (,@heading-attrs ,@heading-font :height 1.4)))))))
(defun setup-org-mode ()
"Customize `org-mode'."
(with-eval-after-load 'org
(progn
(setq
org-fontify-whole-heading-line t
org-fontify-done-headline t
org-fontify-emphasized-text t
org-fontify-quote-and-verse-blocks t
org-src-fontify-natively t
org-hide-emphasis-markers t
org-hide-leading-stars t
org-indent-mode t
org-pretty-entities t
org-use-sub-superscripts "{}"
org-startup-indented t
spaceline-org-clock-p t)
(fmt-org-bullets)
(fmt-org-mode-style)
(evil-leader/set-key "t ;" 'org-toggle-narrow-to-subtree)))
(add-hook 'org-mode-hook
(lambda ()
(progn
;; For `org-mode' to _safely_ store notes.
(auto-save-mode 1)
;; For customizing look and feel.
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-latex-mode ()
"Customize `latex-mode'."
(with-eval-after-load 'latex
(progn
(setq-default TeX-master nil)
(custom-theme-set-faces
'user
`(font-latex-math-face ((t (:inherit (shadow fixed-pitch) :height 0.9))))
`(font-lock-function-name-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-lock-constant-face ((t (:inherit fixed-pitch :height 1.0 :weight bold))))
`(font-latex-sedate-face ((t (:inherit fixed-pitch :height 1.0))))
`(font-latex-sectioning-2-face ((t (:inherit variable-pitch :height 1.0 :weight bold)))))))
(add-hook 'LaTeX-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing))))
;; Perform full-document previews.
(add-hook 'doc-view-mode-hook 'auto-revert-mode))
(defun setup-text-mode ()
"Customize `text-mode'."
(add-hook 'text-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(enable-distraction-free-writing)))))
(defun setup-markdown-mode ()
"Customize `markdown-mode'."
(with-eval-after-load 'markdown
(progn
(custom-theme-set-faces
'user
`(markdown-inline-code-face ((t (:inherit
(markdown-code-face
markdown-pre-face
shadow
fixed-pitch) :height 1.0)))))))
(add-hook 'markdown-mode-hook
(lambda ()
(progn
(variable-pitch-mode 1)
(typo-mode -1)
(enable-distraction-free-writing)))))
(defun customize-modes ()
"Customize different modes."
(custom-theme-set-faces
'user
;; `(default ((t (:family ,base-font-face
;; :slant normal
;; :height 120))))
`(variable-pitch ((t (:family ,serif-font-face
:height 1.6
:weight normal))))
`(fixed-pitch ((t (:family ,monospace-font-face
:slant normal
:height 0.8)))))
(setup-programming-mode)
(setup-org-mode)
(setup-latex-mode)
(setup-text-mode)
(setup-markdown-mode))
;; --- Common editor preferences. ---
;; --------------------------------------------------
(defun handle-delete-frame-without-kill-emacs (event)
"Handle delete-frame events from the X server."
(interactive "e")
(let ((frame (posn-window (event-start event)))
(i 0)
(tail (frame-list)))
(while tail
(and (frame-visible-p (car tail))
(not (eq (car tail) frame))
(setq i (1+ i)))
(setq tail (cdr tail)))
(if (> i 0)
(delete-frame frame t)
;; Not (save-buffers-kill-emacs) but instead:
(ns-do-hide-emacs))))
(defun use-utf-8-everywhere ()
"Use utf-8 everywhere."
(set-language-environment 'utf-8)
(set-default-coding-systems 'utf-8))
(defun customize-editor-behavior ()
"Customize common editor behavior."
;; Start server.
(setq-default dotspacemacs-enable-server t)
(use-utf-8-everywhere)
(setup-auto-saves-and-bkups)
;; Use '4' spaces instead of a 'tab' character.
(setq-default tab-width 4)
(setq-default indent-tabs-mode nil)
;; By default, set column width to '80' characters.
(setq-default fill-column 80)
;; Ensure files always end with a new line.
(setq-default require-final-newline t)
;; Stop emacs from arbitrarily adding lines to the end of a file,
;; when cursor is moved past the end of it.
(setq-default next-line-add-newlines nil)
;; Show recently opened files in helm.
(setq-default helm-ff-file-name-history-use-recentf t)
;; Configure projectile to use `.projectile' files, if any, in the project directory.
(setq projectile-indexing-method 'hybrid)
(when (eq system-type 'darwin)
(advice-add 'handle-delete-frame :override
#'handle-delete-frame-without-kill-emacs)))
;;; funcs.el ends here
|
[
{
"context": "ting for multiple-languages\n\n;; Copyright (C) 2012 Takafumi Arakaki\n\n;; Author: Takafumi Arakaki <aka.tkf at gmail.co",
"end": 115,
"score": 0.9998456835746765,
"start": 99,
"tag": "NAME",
"value": "Takafumi Arakaki"
},
{
"context": ";; Copyright (C) 2012 Takafumi Arakaki\n\n;; Author: Takafumi Arakaki <aka.tkf at gmail.com>\n\n;; This file is NOT part ",
"end": 144,
"score": 0.9998589754104614,
"start": 128,
"tag": "NAME",
"value": "Takafumi Arakaki"
},
{
"context": "12 Takafumi Arakaki\n\n;; Author: Takafumi Arakaki <aka.tkf at gmail.com>\n\n;; This file is NOT part of GN",
"end": 149,
"score": 0.920820415019989,
"start": 146,
"tag": "USERNAME",
"value": "aka"
}
] | elpa/ein-20150812.1947/ein-multilang-fontify.el | pramukta/emacs.d | 1 | ;;; ein-multilang-fontify.el --- Syntax highlighting for multiple-languages
;; Copyright (C) 2012 Takafumi Arakaki
;; Author: Takafumi Arakaki <aka.tkf at gmail.com>
;; This file is NOT part of GNU Emacs.
;; ein-multilang-fontify.el is free software: you can redistribute it
;; and/or modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;; ein-multilang-fontify.el 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 ein-multilang-fontify.el.
;; If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
;; It would be nice if org-src is available, but this module should
;; work without org-src. Data on `org-src-lang-modes' is used
;; if this variable is bound.
(require 'org-src nil t)
(defun ein:mlf-get-lang-mode (lang)
"Return major mode for LANG.
Modified version of `org-src-get-lang-mode'."
(when (symbolp lang)
(setq lang (symbol-name lang)))
(intern
(format "%s-mode"
(or (and (bound-and-true-p org-src-lang-modes)
(cdr (assoc lang org-src-lang-modes)))
lang))))
(defun ein:mlf-font-lock-fontify-block (lang start end)
"Patched version of `org-src-font-lock-fontify-block'."
(let ((lang-mode (ein:mlf-get-lang-mode lang)))
(if (fboundp lang-mode)
(let ((string (buffer-substring-no-properties start end))
(modified (buffer-modified-p))
(orig-buffer (current-buffer))
pos
next)
(remove-text-properties start end '(face nil))
(with-current-buffer
(get-buffer-create
(concat " ein:mlf-fontification:" (symbol-name lang-mode)))
(delete-region (point-min) (point-max))
(insert (concat string " ")) ;; so there's a final property change
(unless (eq major-mode lang-mode) (funcall lang-mode))
(font-lock-fontify-buffer)
(setq pos (point-min))
(while (setq next (next-single-property-change pos 'face))
(put-text-property
;; `font-lock-face' property is used instead of `font'.
;; This is the only difference from org-src.
(+ start (1- pos)) (+ start next) 'font-lock-face
(get-text-property pos 'face) orig-buffer)
(setq pos next)))
(add-text-properties
start end
'(font-lock-fontified t fontified t font-lock-multiline t))
(set-buffer-modified-p modified)))))
(provide 'ein-multilang-fontify)
;;; ein-multilang-fontify.el ends here
| 17216 | ;;; ein-multilang-fontify.el --- Syntax highlighting for multiple-languages
;; Copyright (C) 2012 <NAME>
;; Author: <NAME> <aka.tkf at gmail.com>
;; This file is NOT part of GNU Emacs.
;; ein-multilang-fontify.el is free software: you can redistribute it
;; and/or modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;; ein-multilang-fontify.el 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 ein-multilang-fontify.el.
;; If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
;; It would be nice if org-src is available, but this module should
;; work without org-src. Data on `org-src-lang-modes' is used
;; if this variable is bound.
(require 'org-src nil t)
(defun ein:mlf-get-lang-mode (lang)
"Return major mode for LANG.
Modified version of `org-src-get-lang-mode'."
(when (symbolp lang)
(setq lang (symbol-name lang)))
(intern
(format "%s-mode"
(or (and (bound-and-true-p org-src-lang-modes)
(cdr (assoc lang org-src-lang-modes)))
lang))))
(defun ein:mlf-font-lock-fontify-block (lang start end)
"Patched version of `org-src-font-lock-fontify-block'."
(let ((lang-mode (ein:mlf-get-lang-mode lang)))
(if (fboundp lang-mode)
(let ((string (buffer-substring-no-properties start end))
(modified (buffer-modified-p))
(orig-buffer (current-buffer))
pos
next)
(remove-text-properties start end '(face nil))
(with-current-buffer
(get-buffer-create
(concat " ein:mlf-fontification:" (symbol-name lang-mode)))
(delete-region (point-min) (point-max))
(insert (concat string " ")) ;; so there's a final property change
(unless (eq major-mode lang-mode) (funcall lang-mode))
(font-lock-fontify-buffer)
(setq pos (point-min))
(while (setq next (next-single-property-change pos 'face))
(put-text-property
;; `font-lock-face' property is used instead of `font'.
;; This is the only difference from org-src.
(+ start (1- pos)) (+ start next) 'font-lock-face
(get-text-property pos 'face) orig-buffer)
(setq pos next)))
(add-text-properties
start end
'(font-lock-fontified t fontified t font-lock-multiline t))
(set-buffer-modified-p modified)))))
(provide 'ein-multilang-fontify)
;;; ein-multilang-fontify.el ends here
| true | ;;; ein-multilang-fontify.el --- Syntax highlighting for multiple-languages
;; Copyright (C) 2012 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <aka.tkf at gmail.com>
;; This file is NOT part of GNU Emacs.
;; ein-multilang-fontify.el is free software: you can redistribute it
;; and/or modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;; ein-multilang-fontify.el 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 ein-multilang-fontify.el.
;; If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
;; It would be nice if org-src is available, but this module should
;; work without org-src. Data on `org-src-lang-modes' is used
;; if this variable is bound.
(require 'org-src nil t)
(defun ein:mlf-get-lang-mode (lang)
"Return major mode for LANG.
Modified version of `org-src-get-lang-mode'."
(when (symbolp lang)
(setq lang (symbol-name lang)))
(intern
(format "%s-mode"
(or (and (bound-and-true-p org-src-lang-modes)
(cdr (assoc lang org-src-lang-modes)))
lang))))
(defun ein:mlf-font-lock-fontify-block (lang start end)
"Patched version of `org-src-font-lock-fontify-block'."
(let ((lang-mode (ein:mlf-get-lang-mode lang)))
(if (fboundp lang-mode)
(let ((string (buffer-substring-no-properties start end))
(modified (buffer-modified-p))
(orig-buffer (current-buffer))
pos
next)
(remove-text-properties start end '(face nil))
(with-current-buffer
(get-buffer-create
(concat " ein:mlf-fontification:" (symbol-name lang-mode)))
(delete-region (point-min) (point-max))
(insert (concat string " ")) ;; so there's a final property change
(unless (eq major-mode lang-mode) (funcall lang-mode))
(font-lock-fontify-buffer)
(setq pos (point-min))
(while (setq next (next-single-property-change pos 'face))
(put-text-property
;; `font-lock-face' property is used instead of `font'.
;; This is the only difference from org-src.
(+ start (1- pos)) (+ start next) 'font-lock-face
(get-text-property pos 'face) orig-buffer)
(setq pos next)))
(add-text-properties
start end
'(font-lock-fontified t fontified t font-lock-multiline t))
(set-buffer-modified-p modified)))))
(provide 'ein-multilang-fontify)
;;; ein-multilang-fontify.el ends here
|
[
{
"context": ";;; racket-edit.el\n\n;; Copyright (c) 2013-2014 by Greg Hendershott.\n;; Portions Copyright (C) 1985-1986, 1999-2013 F",
"end": 66,
"score": 0.9998855590820312,
"start": 50,
"tag": "NAME",
"value": "Greg Hendershott"
},
{
"context": "99-2013 Free Software Foundation, Inc.\n\n;; Author: Greg Hendershott\n;; URL: https://github.com/greghendershott/racket",
"end": 174,
"score": 0.9998939037322998,
"start": 158,
"tag": "NAME",
"value": "Greg Hendershott"
},
{
"context": "thor: Greg Hendershott\n;; URL: https://github.com/greghendershott/racket-mode\n\n;; License:\n;; This is free software",
"end": 217,
"score": 0.9672656059265137,
"start": 202,
"tag": "USERNAME",
"value": "greghendershott"
}
] | elpa/racket-mode/racket-edit.el | ahmadseleem/ViMacs | 6 | ;;; racket-edit.el
;; Copyright (c) 2013-2014 by Greg Hendershott.
;; Portions Copyright (C) 1985-1986, 1999-2013 Free Software Foundation, Inc.
;; Author: Greg Hendershott
;; URL: https://github.com/greghendershott/racket-mode
;; License:
;; This 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 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. See
;; http://www.gnu.org/licenses/ for details.
;; racket-mode per se, i.e. the .rkt file buffers
(require 'cl-lib)
(require 'racket-common)
(require 'racket-complete)
(require 'racket-eval)
(require 'hideshow)
(defcustom racket-memory-limit 2048
"Terminate the Racket process if memory use exceeds this value in MB.
Changes to this value take effect upon the next `racket-run'.
Caveat: This uses Racket's custodian-limit-memory, which doesn't
enforce the limit exactly. Instead, the program will be
terminated upon the first garbage collection where memory exceeds
the limit (maybe by a significant amount)."
:tag "Memory limit"
:type 'integer
:group 'racket)
(defun racket-run ()
"Save and evaluate the buffer in REPL, like DrRacket's Run."
(interactive)
(save-buffer)
(racket--invalidate-completion-cache)
(racket--invalidate-type-cache)
(racket--eval (format ",run %s %s\n"
(racket--quoted-buffer-file-name)
racket-memory-limit)))
(defun racket-racket ()
"Do `racket <file>` in *shell* buffer."
(interactive)
(racket--shell (concat racket-program
" "
(racket--quoted-buffer-file-name))))
(defun racket-test ()
"Do (require (submod \".\" test)) in *racket* buffer."
(interactive)
(racket-run) ;start fresh, so (require) will have an effect
(racket--eval
(format "%S\n"
`(begin
(displayln "Running tests...")
(require (submod "." test))
(flush-output (current-output-port))))))
(defun racket-raco-test ()
"Do `raco test -x <file>` in *shell* buffer.
To run <file>'s `test` submodule."
(interactive)
(racket--shell (concat raco-program
" test -x "
(racket--quoted-buffer-file-name))))
(defun racket-visit-definition (&optional prefix)
"Visit definition of symbol at point.
Note: Only works if you've `racket-run' the buffer so that its
namespace is active.
Note: Only visits the definition of module level identifiers (i.e.
things for which Racket's `identifier-binding` function returns a
list, as opposed to 'lexical)."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Visit definition of: ")))
(when sym
(racket--do-visit-def-or-mod "def" sym))))
(defun racket--do-visit-def-or-mod (cmd sym)
"CMD must be \"def\" or \"mod\". SYM must be `symbolp`."
(let ((result (racket--eval/sexpr (format ",%s %s\n\n" cmd sym))))
(cond ((and (listp result) (= (length result) 3))
(racket--push-loc)
(cl-destructuring-bind (path line col) result
(find-file path)
(goto-char (point-min))
(forward-line (1- line))
(forward-char col))
(message "Type M-, to return"))
((eq result 'kernel)
(message "`%s' defined in #%%kernel -- source not available." sym))
((y-or-n-p "Not found. Run current buffer and try again? ")
(racket--eval/buffer (format ",run %s\n"
(racket--quoted-buffer-file-name)))
(racket--do-visit-def-or-mod cmd sym)))))
(defun racket--get-def-file+line (sym)
"For use by company-mode 'location option."
(let ((result (racket--eval/sexpr (format ",def %s\n\n" sym))))
(cond ((and (listp result) (= (length result) 3))
(cl-destructuring-bind (path line col) result
(cons path line)))
(t nil))))
(defun racket-visit-module (&optional prefix)
"Visit definition of module at point, e.g. net/url or \"file.rkt\".
Only works if you've `racket-run' the buffer so that its
namespace is active."
(interactive "P")
(let* ((v (thing-at-point 'filename)) ;matches both net/url and "file.rkt"
(v (and v (substring-no-properties v)))
(v (if (or prefix (not v))
(read-from-minibuffer "Visit module: " (or v ""))
v)))
(racket--do-visit-def-or-mod "mod" v)))
(defun racket-doc (&optional prefix)
"View documentation of the identifier or string at point.
If point is an identifier required in the current namespace that
has help, opens the web browser directly at that help
topic. (i.e. Uses the identifier variant of racket/help.)
Otherwise, opens the 'search for a term' page, where you can
choose among multiple possibilities. (i.e. Uses the string
variant of racket/help.)
With a C-u prefix, prompts for the identifier or quoted string,
instead of looking at point."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Racket help for: ")))
(when sym
(unless (string-match-p "^Sending to web browser..."
(racket--eval/string (format ",doc %s" sym)))
(racket--eval/buffer (format ",doc \"%s\"" sym)))))) ;quoted
(defun racket--symbol-at-point-or-prompt (prefix prompt)
"Helper for functions that want symbol-at-point, or, to prompt
when there is no symbol-at-point or prefix is true."
(let ((sap (symbol-at-point)))
(if (or prefix (not sap))
(read-from-minibuffer prompt (if sap (symbol-name sap) ""))
sap)))
(defvar racket--loc-stack '())
(defun racket--push-loc ()
(push (cons (current-buffer) (point))
racket--loc-stack))
(defun racket-unvisit ()
"Return from previous `racket-visit-definition' or `racket-visit-module'."
(interactive)
(if racket--loc-stack
(cl-destructuring-bind (buffer . pt) (pop racket--loc-stack)
(racket-pop-to-buffer-same-window buffer)
(goto-char pt))
(message "Stack empty.")))
;;; racket-describe-mode
(defun racket-describe (&optional prefix)
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Describe: ")))
(when sym
(racket--do-describe sym t))))
(defun racket--do-describe (sym pop-to)
"A helper for `racket-describe' and `racket-company-backend'.
POP-TO should be t for the former (in which case some buttons are
added) and nil for the latter.
Returns the buffer in which the description was written."
(with-current-buffer (get-buffer-create "*Racket Describe*")
(racket-describe-mode)
(read-only-mode -1)
(erase-buffer)
(let ((file (racket--eval/sexpr (format ",describe %s" sym)))
(spc (string #x2020))) ;unlikely character (hopefully)
;; Emacs shr renderer removes leading from <td> elements
;; -- which messes up the indentation of s-expressions including
;; contracts. So replace   with `spc' in the source HTML,
;; and replace `spc' with " " after shr-insert-document outputs.
(shr-insert-document
(with-temp-buffer
(insert-file-contents file)
(goto-char (point-min))
(while (re-search-forward " " nil t)
(replace-match spc t t))
(libxml-parse-html-region (point-min) (point-max))))
(goto-char (point-min))
(while (re-search-forward spc nil t)
(replace-match " " t t)))
(goto-char (point-max))
(when pop-to
(insert-text-button
"Definition"
'action
`(lambda (btn)
(racket--do-visit-def-or-mod
"def"
,(substring-no-properties (format "%s" sym)))))
(insert " ")
(insert-text-button
"Documentation in Browser"
'action
`(lambda (btn)
(racket--eval/buffer
,(substring-no-properties (format ",doc %s\n" sym)))))
(insert " [q]uit"))
(read-only-mode 1)
(goto-char (point-min))
(display-buffer (current-buffer) t)
(when pop-to
(pop-to-buffer (current-buffer))
(message "Type TAB to move to links, 'q' to restore previous window"))
(current-buffer)))
(defvar racket-describe-mode-map
(let ((m (make-sparse-keymap)))
(set-keymap-parent m nil)
(mapc (lambda (x)
(define-key m (kbd (car x)) (cadr x)))
'(("q" quit-window)
("<tab>" racket-describe--next-button)
("S-<tab>" racket-describe--prev-button)))
m)
"Keymap for Racket Describe mode.")
;;;###autoload
(define-derived-mode racket-describe-mode fundamental-mode
"RacketDescribe"
"Major mode for describing Racket functions.
\\{racket-describe-mode-map}")
(defun racket-describe--next-button ()
(interactive)
(forward-button 1 t t))
(defun racket-describe--prev-button ()
(interactive)
(forward-button -1 t t))
;;; code folding
;;;###autoload
(add-to-list 'hs-special-modes-alist
'(racket-mode "(" ")" ";" nil nil))
(defun racket--for-all-tests (verb f)
(save-excursion
(goto-char (point-min))
(let ((n 0))
(while (re-search-forward "^(module[+*]? test" (point-max) t)
(funcall f)
(cl-incf n)
(goto-char (match-end 0)))
(message "%s %d test submodules" verb n))))
(defun racket-fold-all-tests ()
"Fold (hide) all test submodules."
(interactive)
(racket--for-all-tests "Folded" 'hs-hide-block))
(defun racket-unfold-all-tests ()
"Unfold (show) all test submodules."
(interactive)
(racket--for-all-tests "Unfolded" 'hs-show-block))
;;; macro expansion
(defun racket-expand-region (start end &optional prefix)
"Like `racket-send-region', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "rP")
(if (region-active-p)
(progn
(racket--repl-send-expand-command prefix)
(racket--send-region-to-repl start end))
(beep)
(message "No region.")))
(defun racket-expand-definition (&optional prefix)
"Like `racket-send-definition', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-definition))
(defun racket-expand-last-sexp (&optional prefix)
"Like `racket-send-last-sexp', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-last-sexp))
(defun racket--repl-send-expand-command (prefix)
(comint-send-string (racket--get-repl-buffer-process)
(if prefix ",exp!" ",exp ")))
(defun racket-expand-again ()
"Macro expand again the previous expansion done by one of:
- `racket-expand-region'
- `racket-expand-definition'
- `racket-expand-last-sexp'
- `racket-expand-again'"
(interactive)
(comint-send-string (racket--get-repl-buffer-process) ",exp+\n"))
(defun racket-gui-macro-stepper ()
"Run the DrRacket GUI macro stepper.
Runs on the active region, if any, else the entire buffer.
EXPERIMENTAL: May be changed or removed.
BUGGY: The first-ever invocation might not display a GUI window.
If so, try again."
(interactive)
(save-buffer)
(racket--eval
(format "%S\n"
`(begin
(require macro-debugger/stepper racket/port)
,(if (region-active-p)
`(expand/step
(with-input-from-string ,(buffer-substring-no-properties
(region-beginning)
(region-end))
read-syntax))
`(expand-module/step
(string->path
,(substring-no-properties (buffer-file-name)))))))))
;;; requires
(defun racket-tidy-requires ()
"Make a single top-level `require`, modules sorted, one per line.
All top-level `require` forms are combined into a single form.
Within that form:
- A single subform is used for each phase level, sorted in this
order: for-syntax, for-template, for-label, for-meta, and
plain (phase 0).
- Within each level subform, the modules are sorted:
- Collection path modules -- sorted alphabetically.
- Subforms such as `only-in`.
- Quoted relative requires -- sorted alphabetically.
At most one module is listed per line.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-trim-requires' and `racket-base-requires'."
(interactive)
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/tidy %S" reqs)))))
(when new
(goto-char beg)
(insert (concat (read new) "\n")))))
(defun racket-trim-requires ()
"Like `racket-tidy-requires' but also deletes unused modules.
Note: This only works when the source file can be evaluated with
no errors.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-base-requires'."
(interactive)
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/trim \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs))))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))))
(defun racket-base-requires ()
"Change from `#lang racket` to `#lang racket/base`.
Adds explicit requires for modules that are provided by `racket`
but not by `racket/base`.
This is a recommended optimization for Racket applications.
Avoiding loading all of `racket` can reduce load time and memory
footprint.
Also, as does `racket-trim-requires', this removes unneeded
modules and tidies everything into a single, sorted require form.
Note: This only works when the source file can be evaluated with
no errors.
Note: Currently this only helps change `#lang racket` to
`#lang racket/base`. It does *not* help with other similar conversions,
such as changing `#lang typed/racket` to `#lang typed/racket/base`."
(interactive)
(when (racket--buffer-start-re "^#lang.*? racket/base$")
(error "Already using #lang racket/base. Nothing to change."))
(unless (racket--buffer-start-re "^#lang.*? racket$")
(error "File does not use use #lang racket. Cannot change."))
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (or (nth 0 result)
(save-excursion
(goto-char 0) (forward-line 1) (insert "\n") (point))))
(reqs (nth 1 result))
(new (racket--eval/string
(format ",requires/base \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs)))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))
(goto-char (point-min))
(re-search-forward "^#lang.*? racket$")
(insert "/base")))
(defun racket--buffer-start-re (re)
(save-excursion
(condition-case ()
(progn
(goto-char (point-min))
(re-search-forward re)
t)
(error nil))))
(defun racket--kill-top-level-requires ()
"Delete all top-level `require`s. Return list with two results:
The first element is point where the first require was found, or
nil.
The second element is a list of require s-expressions found.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
Note: It might work better to shift this work into Racket code,
and have it return a list of file offsets and replacements. Doing
so would make it easier to match require forms syntactically
instead of textually, and handle module and submodule forms."
(save-excursion
(goto-char (point-min))
(let ((first-beg nil)
(requires nil))
(while (condition-case ()
(progn
(re-search-forward "^(require")
(let* ((beg (progn (backward-up-list) (point)))
(end (progn (forward-sexp) (point)))
(str (buffer-substring-no-properties beg end))
(sexpr (read str)))
(unless first-beg (setq first-beg beg))
(setq requires (cons sexpr requires))
(kill-sexp -1)
(delete-blank-lines))
t)
(error nil)))
(list first-beg requires))))
(provide 'racket-edit)
;;; misc
(defun racket--quoted-buffer-file-name ()
"`shell-quote-argument' ∘ `buffer-file-name'
Generally this should be used instead of plain
`buffer-file-name'. For example this will handle path names
containing spaces by escaping them."
(shell-quote-argument (buffer-file-name)))
;; racket-edit.el ends here
| 51046 | ;;; racket-edit.el
;; Copyright (c) 2013-2014 by <NAME>.
;; Portions Copyright (C) 1985-1986, 1999-2013 Free Software Foundation, Inc.
;; Author: <NAME>
;; URL: https://github.com/greghendershott/racket-mode
;; License:
;; This 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 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. See
;; http://www.gnu.org/licenses/ for details.
;; racket-mode per se, i.e. the .rkt file buffers
(require 'cl-lib)
(require 'racket-common)
(require 'racket-complete)
(require 'racket-eval)
(require 'hideshow)
(defcustom racket-memory-limit 2048
"Terminate the Racket process if memory use exceeds this value in MB.
Changes to this value take effect upon the next `racket-run'.
Caveat: This uses Racket's custodian-limit-memory, which doesn't
enforce the limit exactly. Instead, the program will be
terminated upon the first garbage collection where memory exceeds
the limit (maybe by a significant amount)."
:tag "Memory limit"
:type 'integer
:group 'racket)
(defun racket-run ()
"Save and evaluate the buffer in REPL, like DrRacket's Run."
(interactive)
(save-buffer)
(racket--invalidate-completion-cache)
(racket--invalidate-type-cache)
(racket--eval (format ",run %s %s\n"
(racket--quoted-buffer-file-name)
racket-memory-limit)))
(defun racket-racket ()
"Do `racket <file>` in *shell* buffer."
(interactive)
(racket--shell (concat racket-program
" "
(racket--quoted-buffer-file-name))))
(defun racket-test ()
"Do (require (submod \".\" test)) in *racket* buffer."
(interactive)
(racket-run) ;start fresh, so (require) will have an effect
(racket--eval
(format "%S\n"
`(begin
(displayln "Running tests...")
(require (submod "." test))
(flush-output (current-output-port))))))
(defun racket-raco-test ()
"Do `raco test -x <file>` in *shell* buffer.
To run <file>'s `test` submodule."
(interactive)
(racket--shell (concat raco-program
" test -x "
(racket--quoted-buffer-file-name))))
(defun racket-visit-definition (&optional prefix)
"Visit definition of symbol at point.
Note: Only works if you've `racket-run' the buffer so that its
namespace is active.
Note: Only visits the definition of module level identifiers (i.e.
things for which Racket's `identifier-binding` function returns a
list, as opposed to 'lexical)."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Visit definition of: ")))
(when sym
(racket--do-visit-def-or-mod "def" sym))))
(defun racket--do-visit-def-or-mod (cmd sym)
"CMD must be \"def\" or \"mod\". SYM must be `symbolp`."
(let ((result (racket--eval/sexpr (format ",%s %s\n\n" cmd sym))))
(cond ((and (listp result) (= (length result) 3))
(racket--push-loc)
(cl-destructuring-bind (path line col) result
(find-file path)
(goto-char (point-min))
(forward-line (1- line))
(forward-char col))
(message "Type M-, to return"))
((eq result 'kernel)
(message "`%s' defined in #%%kernel -- source not available." sym))
((y-or-n-p "Not found. Run current buffer and try again? ")
(racket--eval/buffer (format ",run %s\n"
(racket--quoted-buffer-file-name)))
(racket--do-visit-def-or-mod cmd sym)))))
(defun racket--get-def-file+line (sym)
"For use by company-mode 'location option."
(let ((result (racket--eval/sexpr (format ",def %s\n\n" sym))))
(cond ((and (listp result) (= (length result) 3))
(cl-destructuring-bind (path line col) result
(cons path line)))
(t nil))))
(defun racket-visit-module (&optional prefix)
"Visit definition of module at point, e.g. net/url or \"file.rkt\".
Only works if you've `racket-run' the buffer so that its
namespace is active."
(interactive "P")
(let* ((v (thing-at-point 'filename)) ;matches both net/url and "file.rkt"
(v (and v (substring-no-properties v)))
(v (if (or prefix (not v))
(read-from-minibuffer "Visit module: " (or v ""))
v)))
(racket--do-visit-def-or-mod "mod" v)))
(defun racket-doc (&optional prefix)
"View documentation of the identifier or string at point.
If point is an identifier required in the current namespace that
has help, opens the web browser directly at that help
topic. (i.e. Uses the identifier variant of racket/help.)
Otherwise, opens the 'search for a term' page, where you can
choose among multiple possibilities. (i.e. Uses the string
variant of racket/help.)
With a C-u prefix, prompts for the identifier or quoted string,
instead of looking at point."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Racket help for: ")))
(when sym
(unless (string-match-p "^Sending to web browser..."
(racket--eval/string (format ",doc %s" sym)))
(racket--eval/buffer (format ",doc \"%s\"" sym)))))) ;quoted
(defun racket--symbol-at-point-or-prompt (prefix prompt)
"Helper for functions that want symbol-at-point, or, to prompt
when there is no symbol-at-point or prefix is true."
(let ((sap (symbol-at-point)))
(if (or prefix (not sap))
(read-from-minibuffer prompt (if sap (symbol-name sap) ""))
sap)))
(defvar racket--loc-stack '())
(defun racket--push-loc ()
(push (cons (current-buffer) (point))
racket--loc-stack))
(defun racket-unvisit ()
"Return from previous `racket-visit-definition' or `racket-visit-module'."
(interactive)
(if racket--loc-stack
(cl-destructuring-bind (buffer . pt) (pop racket--loc-stack)
(racket-pop-to-buffer-same-window buffer)
(goto-char pt))
(message "Stack empty.")))
;;; racket-describe-mode
(defun racket-describe (&optional prefix)
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Describe: ")))
(when sym
(racket--do-describe sym t))))
(defun racket--do-describe (sym pop-to)
"A helper for `racket-describe' and `racket-company-backend'.
POP-TO should be t for the former (in which case some buttons are
added) and nil for the latter.
Returns the buffer in which the description was written."
(with-current-buffer (get-buffer-create "*Racket Describe*")
(racket-describe-mode)
(read-only-mode -1)
(erase-buffer)
(let ((file (racket--eval/sexpr (format ",describe %s" sym)))
(spc (string #x2020))) ;unlikely character (hopefully)
;; Emacs shr renderer removes leading from <td> elements
;; -- which messes up the indentation of s-expressions including
;; contracts. So replace   with `spc' in the source HTML,
;; and replace `spc' with " " after shr-insert-document outputs.
(shr-insert-document
(with-temp-buffer
(insert-file-contents file)
(goto-char (point-min))
(while (re-search-forward " " nil t)
(replace-match spc t t))
(libxml-parse-html-region (point-min) (point-max))))
(goto-char (point-min))
(while (re-search-forward spc nil t)
(replace-match " " t t)))
(goto-char (point-max))
(when pop-to
(insert-text-button
"Definition"
'action
`(lambda (btn)
(racket--do-visit-def-or-mod
"def"
,(substring-no-properties (format "%s" sym)))))
(insert " ")
(insert-text-button
"Documentation in Browser"
'action
`(lambda (btn)
(racket--eval/buffer
,(substring-no-properties (format ",doc %s\n" sym)))))
(insert " [q]uit"))
(read-only-mode 1)
(goto-char (point-min))
(display-buffer (current-buffer) t)
(when pop-to
(pop-to-buffer (current-buffer))
(message "Type TAB to move to links, 'q' to restore previous window"))
(current-buffer)))
(defvar racket-describe-mode-map
(let ((m (make-sparse-keymap)))
(set-keymap-parent m nil)
(mapc (lambda (x)
(define-key m (kbd (car x)) (cadr x)))
'(("q" quit-window)
("<tab>" racket-describe--next-button)
("S-<tab>" racket-describe--prev-button)))
m)
"Keymap for Racket Describe mode.")
;;;###autoload
(define-derived-mode racket-describe-mode fundamental-mode
"RacketDescribe"
"Major mode for describing Racket functions.
\\{racket-describe-mode-map}")
(defun racket-describe--next-button ()
(interactive)
(forward-button 1 t t))
(defun racket-describe--prev-button ()
(interactive)
(forward-button -1 t t))
;;; code folding
;;;###autoload
(add-to-list 'hs-special-modes-alist
'(racket-mode "(" ")" ";" nil nil))
(defun racket--for-all-tests (verb f)
(save-excursion
(goto-char (point-min))
(let ((n 0))
(while (re-search-forward "^(module[+*]? test" (point-max) t)
(funcall f)
(cl-incf n)
(goto-char (match-end 0)))
(message "%s %d test submodules" verb n))))
(defun racket-fold-all-tests ()
"Fold (hide) all test submodules."
(interactive)
(racket--for-all-tests "Folded" 'hs-hide-block))
(defun racket-unfold-all-tests ()
"Unfold (show) all test submodules."
(interactive)
(racket--for-all-tests "Unfolded" 'hs-show-block))
;;; macro expansion
(defun racket-expand-region (start end &optional prefix)
"Like `racket-send-region', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "rP")
(if (region-active-p)
(progn
(racket--repl-send-expand-command prefix)
(racket--send-region-to-repl start end))
(beep)
(message "No region.")))
(defun racket-expand-definition (&optional prefix)
"Like `racket-send-definition', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-definition))
(defun racket-expand-last-sexp (&optional prefix)
"Like `racket-send-last-sexp', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-last-sexp))
(defun racket--repl-send-expand-command (prefix)
(comint-send-string (racket--get-repl-buffer-process)
(if prefix ",exp!" ",exp ")))
(defun racket-expand-again ()
"Macro expand again the previous expansion done by one of:
- `racket-expand-region'
- `racket-expand-definition'
- `racket-expand-last-sexp'
- `racket-expand-again'"
(interactive)
(comint-send-string (racket--get-repl-buffer-process) ",exp+\n"))
(defun racket-gui-macro-stepper ()
"Run the DrRacket GUI macro stepper.
Runs on the active region, if any, else the entire buffer.
EXPERIMENTAL: May be changed or removed.
BUGGY: The first-ever invocation might not display a GUI window.
If so, try again."
(interactive)
(save-buffer)
(racket--eval
(format "%S\n"
`(begin
(require macro-debugger/stepper racket/port)
,(if (region-active-p)
`(expand/step
(with-input-from-string ,(buffer-substring-no-properties
(region-beginning)
(region-end))
read-syntax))
`(expand-module/step
(string->path
,(substring-no-properties (buffer-file-name)))))))))
;;; requires
(defun racket-tidy-requires ()
"Make a single top-level `require`, modules sorted, one per line.
All top-level `require` forms are combined into a single form.
Within that form:
- A single subform is used for each phase level, sorted in this
order: for-syntax, for-template, for-label, for-meta, and
plain (phase 0).
- Within each level subform, the modules are sorted:
- Collection path modules -- sorted alphabetically.
- Subforms such as `only-in`.
- Quoted relative requires -- sorted alphabetically.
At most one module is listed per line.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-trim-requires' and `racket-base-requires'."
(interactive)
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/tidy %S" reqs)))))
(when new
(goto-char beg)
(insert (concat (read new) "\n")))))
(defun racket-trim-requires ()
"Like `racket-tidy-requires' but also deletes unused modules.
Note: This only works when the source file can be evaluated with
no errors.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-base-requires'."
(interactive)
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/trim \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs))))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))))
(defun racket-base-requires ()
"Change from `#lang racket` to `#lang racket/base`.
Adds explicit requires for modules that are provided by `racket`
but not by `racket/base`.
This is a recommended optimization for Racket applications.
Avoiding loading all of `racket` can reduce load time and memory
footprint.
Also, as does `racket-trim-requires', this removes unneeded
modules and tidies everything into a single, sorted require form.
Note: This only works when the source file can be evaluated with
no errors.
Note: Currently this only helps change `#lang racket` to
`#lang racket/base`. It does *not* help with other similar conversions,
such as changing `#lang typed/racket` to `#lang typed/racket/base`."
(interactive)
(when (racket--buffer-start-re "^#lang.*? racket/base$")
(error "Already using #lang racket/base. Nothing to change."))
(unless (racket--buffer-start-re "^#lang.*? racket$")
(error "File does not use use #lang racket. Cannot change."))
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (or (nth 0 result)
(save-excursion
(goto-char 0) (forward-line 1) (insert "\n") (point))))
(reqs (nth 1 result))
(new (racket--eval/string
(format ",requires/base \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs)))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))
(goto-char (point-min))
(re-search-forward "^#lang.*? racket$")
(insert "/base")))
(defun racket--buffer-start-re (re)
(save-excursion
(condition-case ()
(progn
(goto-char (point-min))
(re-search-forward re)
t)
(error nil))))
(defun racket--kill-top-level-requires ()
"Delete all top-level `require`s. Return list with two results:
The first element is point where the first require was found, or
nil.
The second element is a list of require s-expressions found.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
Note: It might work better to shift this work into Racket code,
and have it return a list of file offsets and replacements. Doing
so would make it easier to match require forms syntactically
instead of textually, and handle module and submodule forms."
(save-excursion
(goto-char (point-min))
(let ((first-beg nil)
(requires nil))
(while (condition-case ()
(progn
(re-search-forward "^(require")
(let* ((beg (progn (backward-up-list) (point)))
(end (progn (forward-sexp) (point)))
(str (buffer-substring-no-properties beg end))
(sexpr (read str)))
(unless first-beg (setq first-beg beg))
(setq requires (cons sexpr requires))
(kill-sexp -1)
(delete-blank-lines))
t)
(error nil)))
(list first-beg requires))))
(provide 'racket-edit)
;;; misc
(defun racket--quoted-buffer-file-name ()
"`shell-quote-argument' ∘ `buffer-file-name'
Generally this should be used instead of plain
`buffer-file-name'. For example this will handle path names
containing spaces by escaping them."
(shell-quote-argument (buffer-file-name)))
;; racket-edit.el ends here
| true | ;;; racket-edit.el
;; Copyright (c) 2013-2014 by PI:NAME:<NAME>END_PI.
;; Portions Copyright (C) 1985-1986, 1999-2013 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI
;; URL: https://github.com/greghendershott/racket-mode
;; License:
;; This 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 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. See
;; http://www.gnu.org/licenses/ for details.
;; racket-mode per se, i.e. the .rkt file buffers
(require 'cl-lib)
(require 'racket-common)
(require 'racket-complete)
(require 'racket-eval)
(require 'hideshow)
(defcustom racket-memory-limit 2048
"Terminate the Racket process if memory use exceeds this value in MB.
Changes to this value take effect upon the next `racket-run'.
Caveat: This uses Racket's custodian-limit-memory, which doesn't
enforce the limit exactly. Instead, the program will be
terminated upon the first garbage collection where memory exceeds
the limit (maybe by a significant amount)."
:tag "Memory limit"
:type 'integer
:group 'racket)
(defun racket-run ()
"Save and evaluate the buffer in REPL, like DrRacket's Run."
(interactive)
(save-buffer)
(racket--invalidate-completion-cache)
(racket--invalidate-type-cache)
(racket--eval (format ",run %s %s\n"
(racket--quoted-buffer-file-name)
racket-memory-limit)))
(defun racket-racket ()
"Do `racket <file>` in *shell* buffer."
(interactive)
(racket--shell (concat racket-program
" "
(racket--quoted-buffer-file-name))))
(defun racket-test ()
"Do (require (submod \".\" test)) in *racket* buffer."
(interactive)
(racket-run) ;start fresh, so (require) will have an effect
(racket--eval
(format "%S\n"
`(begin
(displayln "Running tests...")
(require (submod "." test))
(flush-output (current-output-port))))))
(defun racket-raco-test ()
"Do `raco test -x <file>` in *shell* buffer.
To run <file>'s `test` submodule."
(interactive)
(racket--shell (concat raco-program
" test -x "
(racket--quoted-buffer-file-name))))
(defun racket-visit-definition (&optional prefix)
"Visit definition of symbol at point.
Note: Only works if you've `racket-run' the buffer so that its
namespace is active.
Note: Only visits the definition of module level identifiers (i.e.
things for which Racket's `identifier-binding` function returns a
list, as opposed to 'lexical)."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Visit definition of: ")))
(when sym
(racket--do-visit-def-or-mod "def" sym))))
(defun racket--do-visit-def-or-mod (cmd sym)
"CMD must be \"def\" or \"mod\". SYM must be `symbolp`."
(let ((result (racket--eval/sexpr (format ",%s %s\n\n" cmd sym))))
(cond ((and (listp result) (= (length result) 3))
(racket--push-loc)
(cl-destructuring-bind (path line col) result
(find-file path)
(goto-char (point-min))
(forward-line (1- line))
(forward-char col))
(message "Type M-, to return"))
((eq result 'kernel)
(message "`%s' defined in #%%kernel -- source not available." sym))
((y-or-n-p "Not found. Run current buffer and try again? ")
(racket--eval/buffer (format ",run %s\n"
(racket--quoted-buffer-file-name)))
(racket--do-visit-def-or-mod cmd sym)))))
(defun racket--get-def-file+line (sym)
"For use by company-mode 'location option."
(let ((result (racket--eval/sexpr (format ",def %s\n\n" sym))))
(cond ((and (listp result) (= (length result) 3))
(cl-destructuring-bind (path line col) result
(cons path line)))
(t nil))))
(defun racket-visit-module (&optional prefix)
"Visit definition of module at point, e.g. net/url or \"file.rkt\".
Only works if you've `racket-run' the buffer so that its
namespace is active."
(interactive "P")
(let* ((v (thing-at-point 'filename)) ;matches both net/url and "file.rkt"
(v (and v (substring-no-properties v)))
(v (if (or prefix (not v))
(read-from-minibuffer "Visit module: " (or v ""))
v)))
(racket--do-visit-def-or-mod "mod" v)))
(defun racket-doc (&optional prefix)
"View documentation of the identifier or string at point.
If point is an identifier required in the current namespace that
has help, opens the web browser directly at that help
topic. (i.e. Uses the identifier variant of racket/help.)
Otherwise, opens the 'search for a term' page, where you can
choose among multiple possibilities. (i.e. Uses the string
variant of racket/help.)
With a C-u prefix, prompts for the identifier or quoted string,
instead of looking at point."
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Racket help for: ")))
(when sym
(unless (string-match-p "^Sending to web browser..."
(racket--eval/string (format ",doc %s" sym)))
(racket--eval/buffer (format ",doc \"%s\"" sym)))))) ;quoted
(defun racket--symbol-at-point-or-prompt (prefix prompt)
"Helper for functions that want symbol-at-point, or, to prompt
when there is no symbol-at-point or prefix is true."
(let ((sap (symbol-at-point)))
(if (or prefix (not sap))
(read-from-minibuffer prompt (if sap (symbol-name sap) ""))
sap)))
(defvar racket--loc-stack '())
(defun racket--push-loc ()
(push (cons (current-buffer) (point))
racket--loc-stack))
(defun racket-unvisit ()
"Return from previous `racket-visit-definition' or `racket-visit-module'."
(interactive)
(if racket--loc-stack
(cl-destructuring-bind (buffer . pt) (pop racket--loc-stack)
(racket-pop-to-buffer-same-window buffer)
(goto-char pt))
(message "Stack empty.")))
;;; racket-describe-mode
(defun racket-describe (&optional prefix)
(interactive "P")
(let ((sym (racket--symbol-at-point-or-prompt prefix "Describe: ")))
(when sym
(racket--do-describe sym t))))
(defun racket--do-describe (sym pop-to)
"A helper for `racket-describe' and `racket-company-backend'.
POP-TO should be t for the former (in which case some buttons are
added) and nil for the latter.
Returns the buffer in which the description was written."
(with-current-buffer (get-buffer-create "*Racket Describe*")
(racket-describe-mode)
(read-only-mode -1)
(erase-buffer)
(let ((file (racket--eval/sexpr (format ",describe %s" sym)))
(spc (string #x2020))) ;unlikely character (hopefully)
;; Emacs shr renderer removes leading from <td> elements
;; -- which messes up the indentation of s-expressions including
;; contracts. So replace   with `spc' in the source HTML,
;; and replace `spc' with " " after shr-insert-document outputs.
(shr-insert-document
(with-temp-buffer
(insert-file-contents file)
(goto-char (point-min))
(while (re-search-forward " " nil t)
(replace-match spc t t))
(libxml-parse-html-region (point-min) (point-max))))
(goto-char (point-min))
(while (re-search-forward spc nil t)
(replace-match " " t t)))
(goto-char (point-max))
(when pop-to
(insert-text-button
"Definition"
'action
`(lambda (btn)
(racket--do-visit-def-or-mod
"def"
,(substring-no-properties (format "%s" sym)))))
(insert " ")
(insert-text-button
"Documentation in Browser"
'action
`(lambda (btn)
(racket--eval/buffer
,(substring-no-properties (format ",doc %s\n" sym)))))
(insert " [q]uit"))
(read-only-mode 1)
(goto-char (point-min))
(display-buffer (current-buffer) t)
(when pop-to
(pop-to-buffer (current-buffer))
(message "Type TAB to move to links, 'q' to restore previous window"))
(current-buffer)))
(defvar racket-describe-mode-map
(let ((m (make-sparse-keymap)))
(set-keymap-parent m nil)
(mapc (lambda (x)
(define-key m (kbd (car x)) (cadr x)))
'(("q" quit-window)
("<tab>" racket-describe--next-button)
("S-<tab>" racket-describe--prev-button)))
m)
"Keymap for Racket Describe mode.")
;;;###autoload
(define-derived-mode racket-describe-mode fundamental-mode
"RacketDescribe"
"Major mode for describing Racket functions.
\\{racket-describe-mode-map}")
(defun racket-describe--next-button ()
(interactive)
(forward-button 1 t t))
(defun racket-describe--prev-button ()
(interactive)
(forward-button -1 t t))
;;; code folding
;;;###autoload
(add-to-list 'hs-special-modes-alist
'(racket-mode "(" ")" ";" nil nil))
(defun racket--for-all-tests (verb f)
(save-excursion
(goto-char (point-min))
(let ((n 0))
(while (re-search-forward "^(module[+*]? test" (point-max) t)
(funcall f)
(cl-incf n)
(goto-char (match-end 0)))
(message "%s %d test submodules" verb n))))
(defun racket-fold-all-tests ()
"Fold (hide) all test submodules."
(interactive)
(racket--for-all-tests "Folded" 'hs-hide-block))
(defun racket-unfold-all-tests ()
"Unfold (show) all test submodules."
(interactive)
(racket--for-all-tests "Unfolded" 'hs-show-block))
;;; macro expansion
(defun racket-expand-region (start end &optional prefix)
"Like `racket-send-region', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "rP")
(if (region-active-p)
(progn
(racket--repl-send-expand-command prefix)
(racket--send-region-to-repl start end))
(beep)
(message "No region.")))
(defun racket-expand-definition (&optional prefix)
"Like `racket-send-definition', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-definition))
(defun racket-expand-last-sexp (&optional prefix)
"Like `racket-send-last-sexp', but macro expand.
With C-u prefix, expands fully.
Otherwise, expands once. You may use `racket-expand-again'."
(interactive "P")
(racket--repl-send-expand-command prefix)
(racket-send-last-sexp))
(defun racket--repl-send-expand-command (prefix)
(comint-send-string (racket--get-repl-buffer-process)
(if prefix ",exp!" ",exp ")))
(defun racket-expand-again ()
"Macro expand again the previous expansion done by one of:
- `racket-expand-region'
- `racket-expand-definition'
- `racket-expand-last-sexp'
- `racket-expand-again'"
(interactive)
(comint-send-string (racket--get-repl-buffer-process) ",exp+\n"))
(defun racket-gui-macro-stepper ()
"Run the DrRacket GUI macro stepper.
Runs on the active region, if any, else the entire buffer.
EXPERIMENTAL: May be changed or removed.
BUGGY: The first-ever invocation might not display a GUI window.
If so, try again."
(interactive)
(save-buffer)
(racket--eval
(format "%S\n"
`(begin
(require macro-debugger/stepper racket/port)
,(if (region-active-p)
`(expand/step
(with-input-from-string ,(buffer-substring-no-properties
(region-beginning)
(region-end))
read-syntax))
`(expand-module/step
(string->path
,(substring-no-properties (buffer-file-name)))))))))
;;; requires
(defun racket-tidy-requires ()
"Make a single top-level `require`, modules sorted, one per line.
All top-level `require` forms are combined into a single form.
Within that form:
- A single subform is used for each phase level, sorted in this
order: for-syntax, for-template, for-label, for-meta, and
plain (phase 0).
- Within each level subform, the modules are sorted:
- Collection path modules -- sorted alphabetically.
- Subforms such as `only-in`.
- Quoted relative requires -- sorted alphabetically.
At most one module is listed per line.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-trim-requires' and `racket-base-requires'."
(interactive)
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/tidy %S" reqs)))))
(when new
(goto-char beg)
(insert (concat (read new) "\n")))))
(defun racket-trim-requires ()
"Like `racket-tidy-requires' but also deletes unused modules.
Note: This only works when the source file can be evaluated with
no errors.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
See also: `racket-base-requires'."
(interactive)
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (nth 0 result))
(reqs (nth 1 result))
(new (and beg reqs
(racket--eval/string
(format ",requires/trim \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs))))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))))
(defun racket-base-requires ()
"Change from `#lang racket` to `#lang racket/base`.
Adds explicit requires for modules that are provided by `racket`
but not by `racket/base`.
This is a recommended optimization for Racket applications.
Avoiding loading all of `racket` can reduce load time and memory
footprint.
Also, as does `racket-trim-requires', this removes unneeded
modules and tidies everything into a single, sorted require form.
Note: This only works when the source file can be evaluated with
no errors.
Note: Currently this only helps change `#lang racket` to
`#lang racket/base`. It does *not* help with other similar conversions,
such as changing `#lang typed/racket` to `#lang typed/racket/base`."
(interactive)
(when (racket--buffer-start-re "^#lang.*? racket/base$")
(error "Already using #lang racket/base. Nothing to change."))
(unless (racket--buffer-start-re "^#lang.*? racket$")
(error "File does not use use #lang racket. Cannot change."))
(when (buffer-modified-p) (save-buffer))
(let* ((result (racket--kill-top-level-requires))
(beg (or (nth 0 result)
(save-excursion
(goto-char 0) (forward-line 1) (insert "\n") (point))))
(reqs (nth 1 result))
(new (racket--eval/string
(format ",requires/base \"%s\" %S"
(substring-no-properties (buffer-file-name))
reqs)))
(new (and new
(condition-case () (read new)
(error (revert-buffer t t t) ;restore original requires
(error "Can't do, source file has error"))))))
(when new
(goto-char beg)
(insert (concat new "\n")))
(goto-char (point-min))
(re-search-forward "^#lang.*? racket$")
(insert "/base")))
(defun racket--buffer-start-re (re)
(save-excursion
(condition-case ()
(progn
(goto-char (point-min))
(re-search-forward re)
t)
(error nil))))
(defun racket--kill-top-level-requires ()
"Delete all top-level `require`s. Return list with two results:
The first element is point where the first require was found, or
nil.
The second element is a list of require s-expressions found.
Note: This only works for requires at the top level of a source
file using `#lang`. It does *not* work for `require`s inside
`module` forms.
Note: It might work better to shift this work into Racket code,
and have it return a list of file offsets and replacements. Doing
so would make it easier to match require forms syntactically
instead of textually, and handle module and submodule forms."
(save-excursion
(goto-char (point-min))
(let ((first-beg nil)
(requires nil))
(while (condition-case ()
(progn
(re-search-forward "^(require")
(let* ((beg (progn (backward-up-list) (point)))
(end (progn (forward-sexp) (point)))
(str (buffer-substring-no-properties beg end))
(sexpr (read str)))
(unless first-beg (setq first-beg beg))
(setq requires (cons sexpr requires))
(kill-sexp -1)
(delete-blank-lines))
t)
(error nil)))
(list first-beg requires))))
(provide 'racket-edit)
;;; misc
(defun racket--quoted-buffer-file-name ()
"`shell-quote-argument' ∘ `buffer-file-name'
Generally this should be used instead of plain
`buffer-file-name'. For example this will handle path names
containing spaces by escaping them."
(shell-quote-argument (buffer-file-name)))
;; racket-edit.el ends here
|
[
{
"context": "xical-binding: t -*-\n\n;; Copyright (C) 2012 ~ 2017 Thierry Volpiatto <thierry.volpiatto@gmail.com>\n\n;; This program is",
"end": 124,
"score": 0.9998897314071655,
"start": 107,
"tag": "NAME",
"value": "Thierry Volpiatto"
},
{
"context": "\n\n;; Copyright (C) 2012 ~ 2017 Thierry Volpiatto <thierry.volpiatto@gmail.com>\n\n;; This program is free software; you can redis",
"end": 153,
"score": 0.999931275844574,
"start": 126,
"tag": "EMAIL",
"value": "thierry.volpiatto@gmail.com"
}
] | elpa/helm-20170906.426/helm-font.el | kwojt/useful-emacs | 0 | ;;; helm-font --- Font and ucs selection for Helm -*- lexical-binding: t -*-
;; Copyright (C) 2012 ~ 2017 Thierry Volpiatto <thierry.volpiatto@gmail.com>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'cl-lib)
(require 'helm)
(require 'helm-help)
(defgroup helm-font nil
"Related applications to display fonts in helm."
:group 'helm)
(defvar helm-ucs-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "<C-backspace>") 'helm-ucs-persistent-delete)
(define-key map (kbd "<C-left>") 'helm-ucs-persistent-backward)
(define-key map (kbd "<C-right>") 'helm-ucs-persistent-forward)
(define-key map (kbd "<C-return>") 'helm-ucs-persistent-insert)
(define-key map (kbd "C-c SPC") 'helm-ucs-persistent-insert-space)
map)
"Keymap for `helm-ucs'.")
(defface helm-ucs-char
'((((class color) (background dark)) (:foreground "Gold")))
"Face used to display ucs characters."
:group 'helm-font)
;;; Xfont selection
;;
;;
(defvar helm-xfonts-cache nil)
(defvar helm-previous-font nil)
(defvar helm-source-xfonts
(helm-build-sync-source "X Fonts"
:init (lambda ()
(unless helm-xfonts-cache
(setq helm-xfonts-cache
(x-list-fonts "*")))
;; Save current font so it can be restored in cleanup
(setq helm-previous-font (cdr (assq 'font (frame-parameters)))))
:candidates 'helm-xfonts-cache
:action '(("Copy font to kill ring" . (lambda (elm)
(kill-new elm)))
("Set font" . (lambda (elm)
(kill-new elm)
(set-frame-font elm 'keep-size)
(message "Font copied to kill ring"))))
:cleanup (lambda ()
;; Restore previous font
(set-frame-font helm-previous-font 'keep-size))
:persistent-action (lambda (new-font)
(set-frame-font new-font 'keep-size)
(kill-new new-font))
:persistent-help "Preview font and copy to kill-ring"))
;;; 𝕌𝕔𝕤 𝕊𝕪𝕞𝕓𝕠𝕝 𝕔𝕠𝕞𝕡𝕝𝕖𝕥𝕚𝕠𝕟
;;
;;
(defvar helm-ucs--max-len nil)
(defvar helm-ucs--names nil)
(defvar helm-ucs-history nil)
(defun helm-calculate-ucs-max-len ()
"Calculate the length of longest `ucs-names' candidate."
(cl-loop for (_n . v) in (ucs-names)
maximize (length (format "#x%x:" v)) into code
maximize (max 1 (string-width (format "%c" v))) into char
finally return (cons code char)))
(defun helm-ucs-init ()
"Initialize an helm buffer with ucs symbols.
Only math* symbols are collected."
(unless helm-ucs--max-len
(setq helm-ucs--max-len
(helm-calculate-ucs-max-len)))
(or helm-ucs--names
(setq helm-ucs--names
(cl-loop with pr = (make-progress-reporter
"collecting ucs names"
0 (length (ucs-names)))
for (n . v) in (ucs-names)
for count from 1
for xcode = (format "#x%x:" v)
for len = (length xcode)
for diff = (- (car helm-ucs--max-len) len)
for code = (format "(#x%x): " v)
for char = (propertize (format "%c" v)
'face 'helm-ucs-char)
unless (or (string= "" n)
(not (char-displayable-p (read xcode))))
collect
(concat code (make-string diff ? )
char " " n)
and do (progress-reporter-update pr count)))))
;; Actions (insertion)
(defun helm-ucs-match (candidate n)
"Return the N part of an ucs CANDIDATE.
Where N=1 is the ucs code, N=2 the ucs char and N=3 the ucs name."
(when (string-match
"^(\\(#x[a-f0-9]+\\)): *\\(.\\) *\\([^:]+\\)+"
candidate)
(match-string n candidate)))
(defun helm-ucs-insert (candidate n)
"Insert the N part of CANDIDATE."
(with-helm-current-buffer
(insert (helm-ucs-match candidate n))))
(defun helm-ucs-insert-char (candidate)
"Insert ucs char part of CANDIDATE at point."
(helm-ucs-insert candidate 2))
(defun helm-ucs-insert-code (candidate)
"Insert ucs code part of CANDIDATE at point."
(helm-ucs-insert candidate 1))
(defun helm-ucs-insert-name (candidate)
"Insert ucs name part of CANDIDATE at point."
(helm-ucs-insert candidate 3))
(defun helm-ucs-persistent-insert ()
"Insert ucs char without quitting helm."
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert 'helm-ucs-insert-char)
(helm-execute-persistent-action 'action-insert)))
(put 'helm-ucs-persistent-insert 'helm-only t)
;; Kill actions
(defun helm-ucs-kill-char (_candidate)
"Action that concatenate ucs marked chars."
(kill-new (mapconcat (lambda (x)
(helm-ucs-match x 2))
(helm-marked-candidates) "")))
(defun helm-ucs-kill-code (candidate)
(kill-new (helm-ucs-match candidate 1)))
(defun helm-ucs-kill-name (candidate)
(kill-new (helm-ucs-match candidate 3)))
;; Navigation in current-buffer (persistent)
(defun helm-ucs-forward-char (_candidate)
(with-helm-current-buffer
(forward-char 1)))
(defun helm-ucs-backward-char (_candidate)
(with-helm-current-buffer
(forward-char -1)))
(defun helm-ucs-delete-backward (_candidate)
(with-helm-current-buffer
(delete-char -1)))
(defun helm-ucs-insert-space (_candidate)
(with-helm-current-buffer
(insert " ")))
(defun helm-ucs-persistent-forward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-forward 'helm-ucs-forward-char)
(helm-execute-persistent-action 'action-forward)))
(put 'helm-ucs-persistent-forward 'helm-only t)
(defun helm-ucs-persistent-backward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-back 'helm-ucs-backward-char)
(helm-execute-persistent-action 'action-back)))
(put 'helm-ucs-persistent-backward 'helm-only t)
(defun helm-ucs-persistent-delete ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-delete 'helm-ucs-delete-backward)
(helm-execute-persistent-action 'action-delete)))
(put 'helm-ucs-persistent-delete 'helm-only t)
(defun helm-ucs-persistent-insert-space ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert-space 'helm-ucs-insert-space)
(helm-execute-persistent-action 'action-insert-space)))
(defvar helm-source-ucs
(helm-build-in-buffer-source "Ucs names"
:data #'helm-ucs-init
:get-line #'buffer-substring
:help-message 'helm-ucs-help-message
:match-part (lambda (candidate) (cadr (split-string candidate ":")))
:filtered-candidate-transformer
(lambda (candidates _source) (sort candidates #'helm-generic-sort-fn))
:action '(("Insert character" . helm-ucs-insert-char)
("Insert character name" . helm-ucs-insert-name)
("Insert character code in hex" . helm-ucs-insert-code)
("Kill marked characters" . helm-ucs-kill-char)
("Kill name" . helm-ucs-kill-name)
("Kill code" . helm-ucs-kill-code))
:keymap helm-ucs-map)
"Source for collecting `ucs-names' math symbols.")
;;;###autoload
(defun helm-select-xfont ()
"Preconfigured `helm' to select Xfont."
(interactive)
(helm :sources 'helm-source-xfonts
:buffer "*helm select xfont*"))
;;;###autoload
(defun helm-ucs (arg)
"Preconfigured helm for `ucs-names'.
Called with a prefix arg force reloading cache."
(interactive "P")
(when arg
(setq helm-ucs--names nil
helm-ucs--max-len nil
ucs-names nil))
(let ((char (helm-aif (char-after) (string it))))
(helm :sources 'helm-source-ucs
:history 'helm-ucs-history
:input (and char (multibyte-string-p char) char)
:buffer "*helm ucs*")))
(provide 'helm-font)
;; Local Variables:
;; byte-compile-warnings: (not obsolete)
;; coding: utf-8
;; indent-tabs-mode: nil
;; End:
;;; helm-font.el ends here
| 19953 | ;;; helm-font --- Font and ucs selection for Helm -*- lexical-binding: t -*-
;; Copyright (C) 2012 ~ 2017 <NAME> <<EMAIL>>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'cl-lib)
(require 'helm)
(require 'helm-help)
(defgroup helm-font nil
"Related applications to display fonts in helm."
:group 'helm)
(defvar helm-ucs-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "<C-backspace>") 'helm-ucs-persistent-delete)
(define-key map (kbd "<C-left>") 'helm-ucs-persistent-backward)
(define-key map (kbd "<C-right>") 'helm-ucs-persistent-forward)
(define-key map (kbd "<C-return>") 'helm-ucs-persistent-insert)
(define-key map (kbd "C-c SPC") 'helm-ucs-persistent-insert-space)
map)
"Keymap for `helm-ucs'.")
(defface helm-ucs-char
'((((class color) (background dark)) (:foreground "Gold")))
"Face used to display ucs characters."
:group 'helm-font)
;;; Xfont selection
;;
;;
(defvar helm-xfonts-cache nil)
(defvar helm-previous-font nil)
(defvar helm-source-xfonts
(helm-build-sync-source "X Fonts"
:init (lambda ()
(unless helm-xfonts-cache
(setq helm-xfonts-cache
(x-list-fonts "*")))
;; Save current font so it can be restored in cleanup
(setq helm-previous-font (cdr (assq 'font (frame-parameters)))))
:candidates 'helm-xfonts-cache
:action '(("Copy font to kill ring" . (lambda (elm)
(kill-new elm)))
("Set font" . (lambda (elm)
(kill-new elm)
(set-frame-font elm 'keep-size)
(message "Font copied to kill ring"))))
:cleanup (lambda ()
;; Restore previous font
(set-frame-font helm-previous-font 'keep-size))
:persistent-action (lambda (new-font)
(set-frame-font new-font 'keep-size)
(kill-new new-font))
:persistent-help "Preview font and copy to kill-ring"))
;;; 𝕌𝕔𝕤 𝕊𝕪𝕞𝕓𝕠𝕝 𝕔𝕠𝕞𝕡𝕝𝕖𝕥𝕚𝕠𝕟
;;
;;
(defvar helm-ucs--max-len nil)
(defvar helm-ucs--names nil)
(defvar helm-ucs-history nil)
(defun helm-calculate-ucs-max-len ()
"Calculate the length of longest `ucs-names' candidate."
(cl-loop for (_n . v) in (ucs-names)
maximize (length (format "#x%x:" v)) into code
maximize (max 1 (string-width (format "%c" v))) into char
finally return (cons code char)))
(defun helm-ucs-init ()
"Initialize an helm buffer with ucs symbols.
Only math* symbols are collected."
(unless helm-ucs--max-len
(setq helm-ucs--max-len
(helm-calculate-ucs-max-len)))
(or helm-ucs--names
(setq helm-ucs--names
(cl-loop with pr = (make-progress-reporter
"collecting ucs names"
0 (length (ucs-names)))
for (n . v) in (ucs-names)
for count from 1
for xcode = (format "#x%x:" v)
for len = (length xcode)
for diff = (- (car helm-ucs--max-len) len)
for code = (format "(#x%x): " v)
for char = (propertize (format "%c" v)
'face 'helm-ucs-char)
unless (or (string= "" n)
(not (char-displayable-p (read xcode))))
collect
(concat code (make-string diff ? )
char " " n)
and do (progress-reporter-update pr count)))))
;; Actions (insertion)
(defun helm-ucs-match (candidate n)
"Return the N part of an ucs CANDIDATE.
Where N=1 is the ucs code, N=2 the ucs char and N=3 the ucs name."
(when (string-match
"^(\\(#x[a-f0-9]+\\)): *\\(.\\) *\\([^:]+\\)+"
candidate)
(match-string n candidate)))
(defun helm-ucs-insert (candidate n)
"Insert the N part of CANDIDATE."
(with-helm-current-buffer
(insert (helm-ucs-match candidate n))))
(defun helm-ucs-insert-char (candidate)
"Insert ucs char part of CANDIDATE at point."
(helm-ucs-insert candidate 2))
(defun helm-ucs-insert-code (candidate)
"Insert ucs code part of CANDIDATE at point."
(helm-ucs-insert candidate 1))
(defun helm-ucs-insert-name (candidate)
"Insert ucs name part of CANDIDATE at point."
(helm-ucs-insert candidate 3))
(defun helm-ucs-persistent-insert ()
"Insert ucs char without quitting helm."
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert 'helm-ucs-insert-char)
(helm-execute-persistent-action 'action-insert)))
(put 'helm-ucs-persistent-insert 'helm-only t)
;; Kill actions
(defun helm-ucs-kill-char (_candidate)
"Action that concatenate ucs marked chars."
(kill-new (mapconcat (lambda (x)
(helm-ucs-match x 2))
(helm-marked-candidates) "")))
(defun helm-ucs-kill-code (candidate)
(kill-new (helm-ucs-match candidate 1)))
(defun helm-ucs-kill-name (candidate)
(kill-new (helm-ucs-match candidate 3)))
;; Navigation in current-buffer (persistent)
(defun helm-ucs-forward-char (_candidate)
(with-helm-current-buffer
(forward-char 1)))
(defun helm-ucs-backward-char (_candidate)
(with-helm-current-buffer
(forward-char -1)))
(defun helm-ucs-delete-backward (_candidate)
(with-helm-current-buffer
(delete-char -1)))
(defun helm-ucs-insert-space (_candidate)
(with-helm-current-buffer
(insert " ")))
(defun helm-ucs-persistent-forward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-forward 'helm-ucs-forward-char)
(helm-execute-persistent-action 'action-forward)))
(put 'helm-ucs-persistent-forward 'helm-only t)
(defun helm-ucs-persistent-backward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-back 'helm-ucs-backward-char)
(helm-execute-persistent-action 'action-back)))
(put 'helm-ucs-persistent-backward 'helm-only t)
(defun helm-ucs-persistent-delete ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-delete 'helm-ucs-delete-backward)
(helm-execute-persistent-action 'action-delete)))
(put 'helm-ucs-persistent-delete 'helm-only t)
(defun helm-ucs-persistent-insert-space ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert-space 'helm-ucs-insert-space)
(helm-execute-persistent-action 'action-insert-space)))
(defvar helm-source-ucs
(helm-build-in-buffer-source "Ucs names"
:data #'helm-ucs-init
:get-line #'buffer-substring
:help-message 'helm-ucs-help-message
:match-part (lambda (candidate) (cadr (split-string candidate ":")))
:filtered-candidate-transformer
(lambda (candidates _source) (sort candidates #'helm-generic-sort-fn))
:action '(("Insert character" . helm-ucs-insert-char)
("Insert character name" . helm-ucs-insert-name)
("Insert character code in hex" . helm-ucs-insert-code)
("Kill marked characters" . helm-ucs-kill-char)
("Kill name" . helm-ucs-kill-name)
("Kill code" . helm-ucs-kill-code))
:keymap helm-ucs-map)
"Source for collecting `ucs-names' math symbols.")
;;;###autoload
(defun helm-select-xfont ()
"Preconfigured `helm' to select Xfont."
(interactive)
(helm :sources 'helm-source-xfonts
:buffer "*helm select xfont*"))
;;;###autoload
(defun helm-ucs (arg)
"Preconfigured helm for `ucs-names'.
Called with a prefix arg force reloading cache."
(interactive "P")
(when arg
(setq helm-ucs--names nil
helm-ucs--max-len nil
ucs-names nil))
(let ((char (helm-aif (char-after) (string it))))
(helm :sources 'helm-source-ucs
:history 'helm-ucs-history
:input (and char (multibyte-string-p char) char)
:buffer "*helm ucs*")))
(provide 'helm-font)
;; Local Variables:
;; byte-compile-warnings: (not obsolete)
;; coding: utf-8
;; indent-tabs-mode: nil
;; End:
;;; helm-font.el ends here
| true | ;;; helm-font --- Font and ucs selection for Helm -*- lexical-binding: t -*-
;; Copyright (C) 2012 ~ 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'cl-lib)
(require 'helm)
(require 'helm-help)
(defgroup helm-font nil
"Related applications to display fonts in helm."
:group 'helm)
(defvar helm-ucs-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "<C-backspace>") 'helm-ucs-persistent-delete)
(define-key map (kbd "<C-left>") 'helm-ucs-persistent-backward)
(define-key map (kbd "<C-right>") 'helm-ucs-persistent-forward)
(define-key map (kbd "<C-return>") 'helm-ucs-persistent-insert)
(define-key map (kbd "C-c SPC") 'helm-ucs-persistent-insert-space)
map)
"Keymap for `helm-ucs'.")
(defface helm-ucs-char
'((((class color) (background dark)) (:foreground "Gold")))
"Face used to display ucs characters."
:group 'helm-font)
;;; Xfont selection
;;
;;
(defvar helm-xfonts-cache nil)
(defvar helm-previous-font nil)
(defvar helm-source-xfonts
(helm-build-sync-source "X Fonts"
:init (lambda ()
(unless helm-xfonts-cache
(setq helm-xfonts-cache
(x-list-fonts "*")))
;; Save current font so it can be restored in cleanup
(setq helm-previous-font (cdr (assq 'font (frame-parameters)))))
:candidates 'helm-xfonts-cache
:action '(("Copy font to kill ring" . (lambda (elm)
(kill-new elm)))
("Set font" . (lambda (elm)
(kill-new elm)
(set-frame-font elm 'keep-size)
(message "Font copied to kill ring"))))
:cleanup (lambda ()
;; Restore previous font
(set-frame-font helm-previous-font 'keep-size))
:persistent-action (lambda (new-font)
(set-frame-font new-font 'keep-size)
(kill-new new-font))
:persistent-help "Preview font and copy to kill-ring"))
;;; 𝕌𝕔𝕤 𝕊𝕪𝕞𝕓𝕠𝕝 𝕔𝕠𝕞𝕡𝕝𝕖𝕥𝕚𝕠𝕟
;;
;;
(defvar helm-ucs--max-len nil)
(defvar helm-ucs--names nil)
(defvar helm-ucs-history nil)
(defun helm-calculate-ucs-max-len ()
"Calculate the length of longest `ucs-names' candidate."
(cl-loop for (_n . v) in (ucs-names)
maximize (length (format "#x%x:" v)) into code
maximize (max 1 (string-width (format "%c" v))) into char
finally return (cons code char)))
(defun helm-ucs-init ()
"Initialize an helm buffer with ucs symbols.
Only math* symbols are collected."
(unless helm-ucs--max-len
(setq helm-ucs--max-len
(helm-calculate-ucs-max-len)))
(or helm-ucs--names
(setq helm-ucs--names
(cl-loop with pr = (make-progress-reporter
"collecting ucs names"
0 (length (ucs-names)))
for (n . v) in (ucs-names)
for count from 1
for xcode = (format "#x%x:" v)
for len = (length xcode)
for diff = (- (car helm-ucs--max-len) len)
for code = (format "(#x%x): " v)
for char = (propertize (format "%c" v)
'face 'helm-ucs-char)
unless (or (string= "" n)
(not (char-displayable-p (read xcode))))
collect
(concat code (make-string diff ? )
char " " n)
and do (progress-reporter-update pr count)))))
;; Actions (insertion)
(defun helm-ucs-match (candidate n)
"Return the N part of an ucs CANDIDATE.
Where N=1 is the ucs code, N=2 the ucs char and N=3 the ucs name."
(when (string-match
"^(\\(#x[a-f0-9]+\\)): *\\(.\\) *\\([^:]+\\)+"
candidate)
(match-string n candidate)))
(defun helm-ucs-insert (candidate n)
"Insert the N part of CANDIDATE."
(with-helm-current-buffer
(insert (helm-ucs-match candidate n))))
(defun helm-ucs-insert-char (candidate)
"Insert ucs char part of CANDIDATE at point."
(helm-ucs-insert candidate 2))
(defun helm-ucs-insert-code (candidate)
"Insert ucs code part of CANDIDATE at point."
(helm-ucs-insert candidate 1))
(defun helm-ucs-insert-name (candidate)
"Insert ucs name part of CANDIDATE at point."
(helm-ucs-insert candidate 3))
(defun helm-ucs-persistent-insert ()
"Insert ucs char without quitting helm."
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert 'helm-ucs-insert-char)
(helm-execute-persistent-action 'action-insert)))
(put 'helm-ucs-persistent-insert 'helm-only t)
;; Kill actions
(defun helm-ucs-kill-char (_candidate)
"Action that concatenate ucs marked chars."
(kill-new (mapconcat (lambda (x)
(helm-ucs-match x 2))
(helm-marked-candidates) "")))
(defun helm-ucs-kill-code (candidate)
(kill-new (helm-ucs-match candidate 1)))
(defun helm-ucs-kill-name (candidate)
(kill-new (helm-ucs-match candidate 3)))
;; Navigation in current-buffer (persistent)
(defun helm-ucs-forward-char (_candidate)
(with-helm-current-buffer
(forward-char 1)))
(defun helm-ucs-backward-char (_candidate)
(with-helm-current-buffer
(forward-char -1)))
(defun helm-ucs-delete-backward (_candidate)
(with-helm-current-buffer
(delete-char -1)))
(defun helm-ucs-insert-space (_candidate)
(with-helm-current-buffer
(insert " ")))
(defun helm-ucs-persistent-forward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-forward 'helm-ucs-forward-char)
(helm-execute-persistent-action 'action-forward)))
(put 'helm-ucs-persistent-forward 'helm-only t)
(defun helm-ucs-persistent-backward ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-back 'helm-ucs-backward-char)
(helm-execute-persistent-action 'action-back)))
(put 'helm-ucs-persistent-backward 'helm-only t)
(defun helm-ucs-persistent-delete ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-delete 'helm-ucs-delete-backward)
(helm-execute-persistent-action 'action-delete)))
(put 'helm-ucs-persistent-delete 'helm-only t)
(defun helm-ucs-persistent-insert-space ()
(interactive)
(with-helm-alive-p
(helm-attrset 'action-insert-space 'helm-ucs-insert-space)
(helm-execute-persistent-action 'action-insert-space)))
(defvar helm-source-ucs
(helm-build-in-buffer-source "Ucs names"
:data #'helm-ucs-init
:get-line #'buffer-substring
:help-message 'helm-ucs-help-message
:match-part (lambda (candidate) (cadr (split-string candidate ":")))
:filtered-candidate-transformer
(lambda (candidates _source) (sort candidates #'helm-generic-sort-fn))
:action '(("Insert character" . helm-ucs-insert-char)
("Insert character name" . helm-ucs-insert-name)
("Insert character code in hex" . helm-ucs-insert-code)
("Kill marked characters" . helm-ucs-kill-char)
("Kill name" . helm-ucs-kill-name)
("Kill code" . helm-ucs-kill-code))
:keymap helm-ucs-map)
"Source for collecting `ucs-names' math symbols.")
;;;###autoload
(defun helm-select-xfont ()
"Preconfigured `helm' to select Xfont."
(interactive)
(helm :sources 'helm-source-xfonts
:buffer "*helm select xfont*"))
;;;###autoload
(defun helm-ucs (arg)
"Preconfigured helm for `ucs-names'.
Called with a prefix arg force reloading cache."
(interactive "P")
(when arg
(setq helm-ucs--names nil
helm-ucs--max-len nil
ucs-names nil))
(let ((char (helm-aif (char-after) (string it))))
(helm :sources 'helm-source-ucs
:history 'helm-ucs-history
:input (and char (multibyte-string-p char) char)
:buffer "*helm ucs*")))
(provide 'helm-font)
;; Local Variables:
;; byte-compile-warnings: (not obsolete)
;; coding: utf-8
;; indent-tabs-mode: nil
;; End:
;;; helm-font.el ends here
|
[
{
"context": "-*- lexical-binding: t; -*-\n\n; Copyright (C) 2018 Ye Zhaoliang\n\n;; Author: Ye Zhaoliang <yzl@DESKTOP-MVNHR6D>\n;;",
"end": 130,
"score": 0.9998724460601807,
"start": 118,
"tag": "NAME",
"value": "Ye Zhaoliang"
},
{
"context": "*-\n\n; Copyright (C) 2018 Ye Zhaoliang\n\n;; Author: Ye Zhaoliang <yzl@DESKTOP-MVNHR6D>\n;; Keywords: tools, local, ",
"end": 155,
"score": 0.999884307384491,
"start": 143,
"tag": "NAME",
"value": "Ye Zhaoliang"
},
{
"context": "e.net\" :port 6667 :nick irc-nick\n :password irc-password :full-name irc-full-name)\n (erc-tls :server \"irc",
"end": 611,
"score": 0.9331147074699402,
"start": 599,
"tag": "PASSWORD",
"value": "irc-password"
},
{
"context": "t\" :port 6697 :nick irc-nick\n :password irc-password :full-name irc-full-name)\n (erc-tls :server \"irc",
"end": 731,
"score": 0.8150262236595154,
"start": 719,
"tag": "PASSWORD",
"value": "irc-password"
},
{
"context": "t\" :port 6697 :nick irc-nick\n :password irc-password :full-name irc-full-name))\n\n\n(setq erc-q",
"end": 843,
"score": 0.9380913376808167,
"start": 840,
"tag": "PASSWORD",
"value": "irc"
},
{
"context": "port 6697 :nick irc-nick\n :password irc-password :full-name irc-full-name))\n\n\n(setq erc-quit-reaso",
"end": 852,
"score": 0.6211271286010742,
"start": 844,
"tag": "PASSWORD",
"value": "password"
}
] | customizations/setup-erc.el | jueqingsizhe66/ranEmacs.d | 11 | ;;; setup-erc.el --- configuration for internet chat inside emacs -*- lexical-binding: t; -*-
; Copyright (C) 2018 Ye Zhaoliang
;; Author: Ye Zhaoliang <yzl@DESKTOP-MVNHR6D>
;; Keywords: tools, local, news,
(defconst irc-channels
'(("freenode.net" "#ubuntu-cn" "#archlinux-cn" "#emacs.tw"
;; "#geekhack"
)
("oftc.net" "#arch-cn" "#njulug" "#wormux-cn" "#emacs-cn")
("esper.net" "#minecraft-cn")))
(ignore-errors (setq erc-autojoin-channels-alist irc-channels))
(defun erc-start ()
(interactive)
(erc :server "irc.freenode.net" :port 6667 :nick irc-nick
:password irc-password :full-name irc-full-name)
(erc-tls :server "irc.oftc.net" :port 6697 :nick irc-nick
:password irc-password :full-name irc-full-name)
(erc-tls :server "irc.esper.net" :port 6697 :nick irc-nick
:password irc-password :full-name irc-full-name))
(setq erc-quit-reason-various-alist
'(("dinner" "Having dinner...")
("z" "Zzz...")
("^$" yow)))
(setq erc-quit-reason 'erc-quit-reason-various)
| 21374 | ;;; setup-erc.el --- configuration for internet chat inside emacs -*- lexical-binding: t; -*-
; Copyright (C) 2018 <NAME>
;; Author: <NAME> <yzl@DESKTOP-MVNHR6D>
;; Keywords: tools, local, news,
(defconst irc-channels
'(("freenode.net" "#ubuntu-cn" "#archlinux-cn" "#emacs.tw"
;; "#geekhack"
)
("oftc.net" "#arch-cn" "#njulug" "#wormux-cn" "#emacs-cn")
("esper.net" "#minecraft-cn")))
(ignore-errors (setq erc-autojoin-channels-alist irc-channels))
(defun erc-start ()
(interactive)
(erc :server "irc.freenode.net" :port 6667 :nick irc-nick
:password <PASSWORD> :full-name irc-full-name)
(erc-tls :server "irc.oftc.net" :port 6697 :nick irc-nick
:password <PASSWORD> :full-name irc-full-name)
(erc-tls :server "irc.esper.net" :port 6697 :nick irc-nick
:password <PASSWORD>-<PASSWORD> :full-name irc-full-name))
(setq erc-quit-reason-various-alist
'(("dinner" "Having dinner...")
("z" "Zzz...")
("^$" yow)))
(setq erc-quit-reason 'erc-quit-reason-various)
| true | ;;; setup-erc.el --- configuration for internet chat inside emacs -*- lexical-binding: t; -*-
; Copyright (C) 2018 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <yzl@DESKTOP-MVNHR6D>
;; Keywords: tools, local, news,
(defconst irc-channels
'(("freenode.net" "#ubuntu-cn" "#archlinux-cn" "#emacs.tw"
;; "#geekhack"
)
("oftc.net" "#arch-cn" "#njulug" "#wormux-cn" "#emacs-cn")
("esper.net" "#minecraft-cn")))
(ignore-errors (setq erc-autojoin-channels-alist irc-channels))
(defun erc-start ()
(interactive)
(erc :server "irc.freenode.net" :port 6667 :nick irc-nick
:password PI:PASSWORD:<PASSWORD>END_PI :full-name irc-full-name)
(erc-tls :server "irc.oftc.net" :port 6697 :nick irc-nick
:password PI:PASSWORD:<PASSWORD>END_PI :full-name irc-full-name)
(erc-tls :server "irc.esper.net" :port 6697 :nick irc-nick
:password PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI :full-name irc-full-name))
(setq erc-quit-reason-various-alist
'(("dinner" "Having dinner...")
("z" "Zzz...")
("^$" yow)))
(setq erc-quit-reason 'erc-quit-reason-various)
|
[
{
"context": "Description: Select windows by numbers.\n;; Author: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; ",
"end": 155,
"score": 0.9627925157546997,
"start": 137,
"tag": "NAME",
"value": "Johann \"Myrkraverk"
},
{
"context": "windows by numbers.\n;; Author: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; Maintainer:",
"end": 166,
"score": 0.9997348189353943,
"start": 157,
"tag": "NAME",
"value": "Oskarsson"
},
{
"context": "umbers.\n;; Author: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; Maintainer: Johann \"Myrkraverk\" Oskarsson <my",
"end": 200,
"score": 0.9999346137046814,
"start": 168,
"tag": "EMAIL",
"value": "myrkraverk@users.sourceforge.net"
},
{
"context": " <myrkraverk@users.sourceforge.net>\n;; Maintainer: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforg",
"end": 223,
"score": 0.9982320070266724,
"start": 217,
"tag": "NAME",
"value": "Johann"
},
{
"context": "erk@users.sourceforge.net>\n;; Maintainer: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; ",
"end": 235,
"score": 0.9858797192573547,
"start": 225,
"tag": "NAME",
"value": "Myrkraverk"
},
{
"context": "ourceforge.net>\n;; Maintainer: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; ",
"end": 246,
"score": 0.9998266100883484,
"start": 237,
"tag": "NAME",
"value": "Oskarsson"
},
{
"context": "et>\n;; Maintainer: Johann \"Myrkraverk\" Oskarsson <myrkraverk@users.sourceforge.net>\n;; Andy Stewart <lazycat.manatee@gma",
"end": 280,
"score": 0.999932050704956,
"start": 248,
"tag": "EMAIL",
"value": "myrkraverk@users.sourceforge.net"
},
{
"context": " <myrkraverk@users.sourceforge.net>\n;; Andy Stewart <lazycat.manatee@gmail.com>\n;; Copyright (C) 2004",
"end": 309,
"score": 0.9998869895935059,
"start": 297,
"tag": "NAME",
"value": "Andy Stewart"
},
{
"context": "ers.sourceforge.net>\n;; Andy Stewart <lazycat.manatee@gmail.com>\n;; Copyright (C) 2004, Johann \"Myrkraverk\" Oskar",
"end": 336,
"score": 0.9999338388442993,
"start": 311,
"tag": "EMAIL",
"value": "lazycat.manatee@gmail.com"
},
{
"context": "<lazycat.manatee@gmail.com>\n;; Copyright (C) 2004, Johann \"Myrkraverk\" Oskarsson, all rights reserved.\n;; Cop",
"end": 367,
"score": 0.9977283477783203,
"start": 361,
"tag": "NAME",
"value": "Johann"
},
{
"context": "manatee@gmail.com>\n;; Copyright (C) 2004, Johann \"Myrkraverk\" Oskarsson, all rights reserved.\n;; Copyright (C) ",
"end": 379,
"score": 0.8511105179786682,
"start": 369,
"tag": "NAME",
"value": "Myrkraverk"
},
{
"context": "il.com>\n;; Copyright (C) 2004, Johann \"Myrkraverk\" Oskarsson, all rights reserved.\n;; Copyright (C) 2014, Andy",
"end": 390,
"score": 0.9993156790733337,
"start": 381,
"tag": "NAME",
"value": "Oskarsson"
},
{
"context": "rsson, all rights reserved.\n;; Copyright (C) 2014, Andy Stewart, all rights reserved.\n;; Created: 2004\n;; Version",
"end": 448,
"score": 0.999884307384491,
"start": 436,
"tag": "NAME",
"value": "Andy Stewart"
},
{
"context": "Last-Updated: 2014-01-01 22:25:03\n;; By: Andy Stewart\n;; URL: http://www.emacswiki.org/emacs/download/w",
"end": 570,
"score": 0.9998810887336731,
"start": 558,
"tag": "NAME",
"value": "Andy Stewart"
}
] | emacs-24.x/.emacs.d/lisp/window-number.el | jfischer/dotfiles | 0 | ;;; window-number.el --- Select windows by numbers.
;; Filename: window-number.el
;; Description: Select windows by numbers.
;; Author: Johann "Myrkraverk" Oskarsson <myrkraverk@users.sourceforge.net>
;; Maintainer: Johann "Myrkraverk" Oskarsson <myrkraverk@users.sourceforge.net>
;; Andy Stewart <lazycat.manatee@gmail.com>
;; Copyright (C) 2004, Johann "Myrkraverk" Oskarsson, all rights reserved.
;; Copyright (C) 2014, Andy Stewart, all rights reserved.
;; Created: 2004
;; Version: 0.1
;; Last-Updated: 2014-01-01 22:25:03
;; By: Andy Stewart
;; URL: http://www.emacswiki.org/emacs/download/window-number.el
;; Keywords:
;; Compatibility: GNU Emacs 24.3.50.1
;;
;; Features that might be required by this library:
;;
;; `cl'
;;
;;; This file is NOT part of GNU Emacs
;;; License
;;
;; 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 3, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; Window number mode allows you to select windows by numbers.
;;
;; `window-number-switch' same as `other-window' (C-x o) when windows less than three.
;; If have three windows (or more) showing, `window-number-switch' will
;; highlight window number at mode-line then prompt you input window number.
;;
;; I binding `window-number-switch' on 'C-x o' to instead `other-window'.
;;
;;; Installation:
;;
;; Put window-number.el to your load-path.
;; The load-path is usually ~/elisp/.
;; It's set in your ~/.emacs like this:
;; (add-to-list 'load-path (expand-file-name "~/elisp"))
;;
;; And the following to your ~/.emacs startup file.
;;
;; (require 'window-number)
;; (window-number-mode 1)
;;
;; No need more.
;;; Customize:
;;
;; `window-number-active-foreground'
;; `window-number-active-background'
;; `window-number-inactive-foreground'
;; `window-number-inactive-background'
;;
;; All of the above can customize by:
;; M-x customize-group RET window-number RET
;;
;;; Change log:
;;
;; 2014/01/01
;; * Add new function `window-number-switch'
;; * Add group `window-number' and customize colors.
;; * Highlight window number on mode-line when `window-number-switch' prompt input.
;; * Use `completing-read' instead `read-string' for better input experience.
;;
;; 2004
;; * First released.
;;
;;; Acknowledgements:
;;
;;
;;
;;; TODO
;;
;;
;;
;;; Require
(require 'cl) ; for set-difference and loop
;;; Code:
(defgroup window-number nil
"Window number group")
(defcustom window-number-active-foreground "black"
"The foreground color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-active-background "gold"
"The background color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-foreground "white"
"The foreground color when window number inactive."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-background "darkred"
"The background color when window number inactive."
:type 'string
:group 'window-number)
(defface window-number-face nil
"The face used for the window number in the mode-line.")
(defun window-number-list ()
"Returns a list of the windows, in fixed order and the
minibuffer (even if not active) last."
(let* ((walk-windows-start
(car (set-difference
(window-list (selected-frame) t)
(window-list (selected-frame) 1))))
(walk-windows-current walk-windows-start)
list)
(while (progn
(setq walk-windows-current
(next-window walk-windows-current t))
(setq list (cons walk-windows-current list))
(not (eq walk-windows-current walk-windows-start))))
(reverse (cons (car list) (cdr list)))))
(defun window-number-switch ()
"Call `other-window' when just two windows.
Prompt user input window number if have more windows."
(interactive)
(if (< (length (window-list)) 3)
(call-interactively 'other-window)
(window-number-set-active-color)
(unwind-protect
(let* ((window-numbers (number-sequence 1 (length (window-list))))
(window-buffer-names (mapcar (lambda (x) (buffer-name (window-buffer x))) (window-number-list)))
(completing-list (mapcar (lambda (x) (list (concat (number-to-string x) " <" (elt window-buffer-names (- x 1)) ">") x)) window-numbers))
(current-window-index (1+ (position (selected-window) (window-number-list))))
(next-window-index (if (= current-window-index (length (window-list))) 1 (+ current-window-index 1)))
(select-index-string (completing-read (format "Window number (%s): " next-window-index) completing-list))
)
(window-number-select
(if (string= select-index-string "")
next-window-index
(string-to-int select-index-string))))
;; Reset to inactive color if interactive is intercept by Ctrl+g
(window-number-set-inactive-color)
))
;; Always reset to inactive color at end.
(window-number-set-inactive-color))
(defun window-number-select (number)
"Selects the nth window."
(interactive "P")
(if (integerp number)
(let ((window (nth (1- number) (window-number-list))))
(if (and window (or (not (window-minibuffer-p window))
(minibuffer-window-active-p window)))
(select-window window)
(error "No such window.")))))
(defun window-number-set-inactive-color ()
(set-face-foreground 'window-number-face "white")
(set-face-background 'window-number-face "darkred")
(force-mode-line-update))
(defun window-number-set-active-color ()
(set-face-foreground 'window-number-face "black")
(set-face-background 'window-number-face "gold")
(force-mode-line-update))
(defun window-number ()
"Returns the the number of the current window."
(length
(memq (selected-window)
(nreverse (window-number-list)))))
(defun window-number-string ()
"Returns the string containing the number of the current window"
(propertize
(concat " [" (number-to-string (window-number)) "] ")
'face
'window-number-face))
(defvar window-number-mode-map nil
"Keymap for the window number mode.")
(defvar window-number-meta-mode-map nil
"Keymap for the window number meta mode.")
(defmacro window-number-define-keys (mode-map prefix)
`(progn
,@(loop for number from 1 to 10 collect
`(define-key ,mode-map
(kbd ,(concat prefix (number-to-string
(if (>= number 10) 0 number))))
(lambda nil (interactive)
(window-number-select ,number))))))
; define C-x C-j 1 to switch to win 1, etc (C-x C-j 0 = win 10)
(unless window-number-mode-map
(setq window-number-mode-map (make-sparse-keymap))
; space after C-j is important
(window-number-define-keys window-number-mode-map "C-x C-j "))
; define M-1 to switch to win 1, etc (M-0 = win 10)
(unless window-number-meta-mode-map
(setq window-number-meta-mode-map (make-sparse-keymap))
(window-number-define-keys window-number-meta-mode-map "M-"))
(if (featurep 'xemacs)
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter " -?-"
(window-number-set-inactive-color))
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter (:eval (window-number-string))
(window-number-set-inactive-color)
))
(define-minor-mode window-number-meta-mode
"A global minor mode that enables use of the M- prefix to
select windows, use `window-number-mode' to display the window
numbers in the mode-line."
:global t
:init-value nil)
(provide 'window-number)
;;; window-number.el ends here
| 12848 | ;;; window-number.el --- Select windows by numbers.
;; Filename: window-number.el
;; Description: Select windows by numbers.
;; Author: <NAME>" <NAME> <<EMAIL>>
;; Maintainer: <NAME> "<NAME>" <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; Copyright (C) 2004, <NAME> "<NAME>" <NAME>, all rights reserved.
;; Copyright (C) 2014, <NAME>, all rights reserved.
;; Created: 2004
;; Version: 0.1
;; Last-Updated: 2014-01-01 22:25:03
;; By: <NAME>
;; URL: http://www.emacswiki.org/emacs/download/window-number.el
;; Keywords:
;; Compatibility: GNU Emacs 24.3.50.1
;;
;; Features that might be required by this library:
;;
;; `cl'
;;
;;; This file is NOT part of GNU Emacs
;;; License
;;
;; 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 3, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; Window number mode allows you to select windows by numbers.
;;
;; `window-number-switch' same as `other-window' (C-x o) when windows less than three.
;; If have three windows (or more) showing, `window-number-switch' will
;; highlight window number at mode-line then prompt you input window number.
;;
;; I binding `window-number-switch' on 'C-x o' to instead `other-window'.
;;
;;; Installation:
;;
;; Put window-number.el to your load-path.
;; The load-path is usually ~/elisp/.
;; It's set in your ~/.emacs like this:
;; (add-to-list 'load-path (expand-file-name "~/elisp"))
;;
;; And the following to your ~/.emacs startup file.
;;
;; (require 'window-number)
;; (window-number-mode 1)
;;
;; No need more.
;;; Customize:
;;
;; `window-number-active-foreground'
;; `window-number-active-background'
;; `window-number-inactive-foreground'
;; `window-number-inactive-background'
;;
;; All of the above can customize by:
;; M-x customize-group RET window-number RET
;;
;;; Change log:
;;
;; 2014/01/01
;; * Add new function `window-number-switch'
;; * Add group `window-number' and customize colors.
;; * Highlight window number on mode-line when `window-number-switch' prompt input.
;; * Use `completing-read' instead `read-string' for better input experience.
;;
;; 2004
;; * First released.
;;
;;; Acknowledgements:
;;
;;
;;
;;; TODO
;;
;;
;;
;;; Require
(require 'cl) ; for set-difference and loop
;;; Code:
(defgroup window-number nil
"Window number group")
(defcustom window-number-active-foreground "black"
"The foreground color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-active-background "gold"
"The background color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-foreground "white"
"The foreground color when window number inactive."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-background "darkred"
"The background color when window number inactive."
:type 'string
:group 'window-number)
(defface window-number-face nil
"The face used for the window number in the mode-line.")
(defun window-number-list ()
"Returns a list of the windows, in fixed order and the
minibuffer (even if not active) last."
(let* ((walk-windows-start
(car (set-difference
(window-list (selected-frame) t)
(window-list (selected-frame) 1))))
(walk-windows-current walk-windows-start)
list)
(while (progn
(setq walk-windows-current
(next-window walk-windows-current t))
(setq list (cons walk-windows-current list))
(not (eq walk-windows-current walk-windows-start))))
(reverse (cons (car list) (cdr list)))))
(defun window-number-switch ()
"Call `other-window' when just two windows.
Prompt user input window number if have more windows."
(interactive)
(if (< (length (window-list)) 3)
(call-interactively 'other-window)
(window-number-set-active-color)
(unwind-protect
(let* ((window-numbers (number-sequence 1 (length (window-list))))
(window-buffer-names (mapcar (lambda (x) (buffer-name (window-buffer x))) (window-number-list)))
(completing-list (mapcar (lambda (x) (list (concat (number-to-string x) " <" (elt window-buffer-names (- x 1)) ">") x)) window-numbers))
(current-window-index (1+ (position (selected-window) (window-number-list))))
(next-window-index (if (= current-window-index (length (window-list))) 1 (+ current-window-index 1)))
(select-index-string (completing-read (format "Window number (%s): " next-window-index) completing-list))
)
(window-number-select
(if (string= select-index-string "")
next-window-index
(string-to-int select-index-string))))
;; Reset to inactive color if interactive is intercept by Ctrl+g
(window-number-set-inactive-color)
))
;; Always reset to inactive color at end.
(window-number-set-inactive-color))
(defun window-number-select (number)
"Selects the nth window."
(interactive "P")
(if (integerp number)
(let ((window (nth (1- number) (window-number-list))))
(if (and window (or (not (window-minibuffer-p window))
(minibuffer-window-active-p window)))
(select-window window)
(error "No such window.")))))
(defun window-number-set-inactive-color ()
(set-face-foreground 'window-number-face "white")
(set-face-background 'window-number-face "darkred")
(force-mode-line-update))
(defun window-number-set-active-color ()
(set-face-foreground 'window-number-face "black")
(set-face-background 'window-number-face "gold")
(force-mode-line-update))
(defun window-number ()
"Returns the the number of the current window."
(length
(memq (selected-window)
(nreverse (window-number-list)))))
(defun window-number-string ()
"Returns the string containing the number of the current window"
(propertize
(concat " [" (number-to-string (window-number)) "] ")
'face
'window-number-face))
(defvar window-number-mode-map nil
"Keymap for the window number mode.")
(defvar window-number-meta-mode-map nil
"Keymap for the window number meta mode.")
(defmacro window-number-define-keys (mode-map prefix)
`(progn
,@(loop for number from 1 to 10 collect
`(define-key ,mode-map
(kbd ,(concat prefix (number-to-string
(if (>= number 10) 0 number))))
(lambda nil (interactive)
(window-number-select ,number))))))
; define C-x C-j 1 to switch to win 1, etc (C-x C-j 0 = win 10)
(unless window-number-mode-map
(setq window-number-mode-map (make-sparse-keymap))
; space after C-j is important
(window-number-define-keys window-number-mode-map "C-x C-j "))
; define M-1 to switch to win 1, etc (M-0 = win 10)
(unless window-number-meta-mode-map
(setq window-number-meta-mode-map (make-sparse-keymap))
(window-number-define-keys window-number-meta-mode-map "M-"))
(if (featurep 'xemacs)
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter " -?-"
(window-number-set-inactive-color))
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter (:eval (window-number-string))
(window-number-set-inactive-color)
))
(define-minor-mode window-number-meta-mode
"A global minor mode that enables use of the M- prefix to
select windows, use `window-number-mode' to display the window
numbers in the mode-line."
:global t
:init-value nil)
(provide 'window-number)
;;; window-number.el ends here
| true | ;;; window-number.el --- Select windows by numbers.
;; Filename: window-number.el
;; Description: Select windows by numbers.
;; Author: PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Copyright (C) 2004, PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI, all rights reserved.
;; Copyright (C) 2014, PI:NAME:<NAME>END_PI, all rights reserved.
;; Created: 2004
;; Version: 0.1
;; Last-Updated: 2014-01-01 22:25:03
;; By: PI:NAME:<NAME>END_PI
;; URL: http://www.emacswiki.org/emacs/download/window-number.el
;; Keywords:
;; Compatibility: GNU Emacs 24.3.50.1
;;
;; Features that might be required by this library:
;;
;; `cl'
;;
;;; This file is NOT part of GNU Emacs
;;; License
;;
;; 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 3, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;;
;; Window number mode allows you to select windows by numbers.
;;
;; `window-number-switch' same as `other-window' (C-x o) when windows less than three.
;; If have three windows (or more) showing, `window-number-switch' will
;; highlight window number at mode-line then prompt you input window number.
;;
;; I binding `window-number-switch' on 'C-x o' to instead `other-window'.
;;
;;; Installation:
;;
;; Put window-number.el to your load-path.
;; The load-path is usually ~/elisp/.
;; It's set in your ~/.emacs like this:
;; (add-to-list 'load-path (expand-file-name "~/elisp"))
;;
;; And the following to your ~/.emacs startup file.
;;
;; (require 'window-number)
;; (window-number-mode 1)
;;
;; No need more.
;;; Customize:
;;
;; `window-number-active-foreground'
;; `window-number-active-background'
;; `window-number-inactive-foreground'
;; `window-number-inactive-background'
;;
;; All of the above can customize by:
;; M-x customize-group RET window-number RET
;;
;;; Change log:
;;
;; 2014/01/01
;; * Add new function `window-number-switch'
;; * Add group `window-number' and customize colors.
;; * Highlight window number on mode-line when `window-number-switch' prompt input.
;; * Use `completing-read' instead `read-string' for better input experience.
;;
;; 2004
;; * First released.
;;
;;; Acknowledgements:
;;
;;
;;
;;; TODO
;;
;;
;;
;;; Require
(require 'cl) ; for set-difference and loop
;;; Code:
(defgroup window-number nil
"Window number group")
(defcustom window-number-active-foreground "black"
"The foreground color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-active-background "gold"
"The background color when window number active."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-foreground "white"
"The foreground color when window number inactive."
:type 'string
:group 'window-number)
(defcustom window-number-inactive-background "darkred"
"The background color when window number inactive."
:type 'string
:group 'window-number)
(defface window-number-face nil
"The face used for the window number in the mode-line.")
(defun window-number-list ()
"Returns a list of the windows, in fixed order and the
minibuffer (even if not active) last."
(let* ((walk-windows-start
(car (set-difference
(window-list (selected-frame) t)
(window-list (selected-frame) 1))))
(walk-windows-current walk-windows-start)
list)
(while (progn
(setq walk-windows-current
(next-window walk-windows-current t))
(setq list (cons walk-windows-current list))
(not (eq walk-windows-current walk-windows-start))))
(reverse (cons (car list) (cdr list)))))
(defun window-number-switch ()
"Call `other-window' when just two windows.
Prompt user input window number if have more windows."
(interactive)
(if (< (length (window-list)) 3)
(call-interactively 'other-window)
(window-number-set-active-color)
(unwind-protect
(let* ((window-numbers (number-sequence 1 (length (window-list))))
(window-buffer-names (mapcar (lambda (x) (buffer-name (window-buffer x))) (window-number-list)))
(completing-list (mapcar (lambda (x) (list (concat (number-to-string x) " <" (elt window-buffer-names (- x 1)) ">") x)) window-numbers))
(current-window-index (1+ (position (selected-window) (window-number-list))))
(next-window-index (if (= current-window-index (length (window-list))) 1 (+ current-window-index 1)))
(select-index-string (completing-read (format "Window number (%s): " next-window-index) completing-list))
)
(window-number-select
(if (string= select-index-string "")
next-window-index
(string-to-int select-index-string))))
;; Reset to inactive color if interactive is intercept by Ctrl+g
(window-number-set-inactive-color)
))
;; Always reset to inactive color at end.
(window-number-set-inactive-color))
(defun window-number-select (number)
"Selects the nth window."
(interactive "P")
(if (integerp number)
(let ((window (nth (1- number) (window-number-list))))
(if (and window (or (not (window-minibuffer-p window))
(minibuffer-window-active-p window)))
(select-window window)
(error "No such window.")))))
(defun window-number-set-inactive-color ()
(set-face-foreground 'window-number-face "white")
(set-face-background 'window-number-face "darkred")
(force-mode-line-update))
(defun window-number-set-active-color ()
(set-face-foreground 'window-number-face "black")
(set-face-background 'window-number-face "gold")
(force-mode-line-update))
(defun window-number ()
"Returns the the number of the current window."
(length
(memq (selected-window)
(nreverse (window-number-list)))))
(defun window-number-string ()
"Returns the string containing the number of the current window"
(propertize
(concat " [" (number-to-string (window-number)) "] ")
'face
'window-number-face))
(defvar window-number-mode-map nil
"Keymap for the window number mode.")
(defvar window-number-meta-mode-map nil
"Keymap for the window number meta mode.")
(defmacro window-number-define-keys (mode-map prefix)
`(progn
,@(loop for number from 1 to 10 collect
`(define-key ,mode-map
(kbd ,(concat prefix (number-to-string
(if (>= number 10) 0 number))))
(lambda nil (interactive)
(window-number-select ,number))))))
; define C-x C-j 1 to switch to win 1, etc (C-x C-j 0 = win 10)
(unless window-number-mode-map
(setq window-number-mode-map (make-sparse-keymap))
; space after C-j is important
(window-number-define-keys window-number-mode-map "C-x C-j "))
; define M-1 to switch to win 1, etc (M-0 = win 10)
(unless window-number-meta-mode-map
(setq window-number-meta-mode-map (make-sparse-keymap))
(window-number-define-keys window-number-meta-mode-map "M-"))
(if (featurep 'xemacs)
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter " -?-"
(window-number-set-inactive-color))
(define-minor-mode window-number-mode
"A global minor mode that enables selection of windows
according to numbers with the C-x C-j prefix. Another mode,
`window-number-meta-mode' enables the use of the M- prefix."
:global t
:init-value nil
:lighter (:eval (window-number-string))
(window-number-set-inactive-color)
))
(define-minor-mode window-number-meta-mode
"A global minor mode that enables use of the M- prefix to
select windows, use `window-number-mode' to display the window
numbers in the mode-line."
:global t
:init-value nil)
(provide 'window-number)
;;; window-number.el ends here
|
[
{
"context": ";;;;;;\n\n;; user\n(setq-default\n user-full-name \"Vivek Menon\"\n user-mail-address \"v+emacs@vvkmnn.xyz\")\n\n;; edi",
"end": 1462,
"score": 0.9998828172683716,
"start": 1451,
"tag": "NAME",
"value": "Vivek Menon"
},
{
"context": "er-full-name \"Vivek Menon\"\n user-mail-address \"v+emacs@vvkmnn.xyz\")\n\n;; editor\n(setq frame-title-format '(\"vDoom Em",
"end": 1502,
"score": 0.9999216198921204,
"start": 1484,
"tag": "EMAIL",
"value": "v+emacs@vvkmnn.xyz"
},
{
"context": " ;; For Yabai WM NOTE https://github.com/koekeishiya/yabai/issues/86#issuecomment-507934212\n doom",
"end": 1750,
"score": 0.9992406368255615,
"start": 1739,
"tag": "USERNAME",
"value": "koekeishiya"
},
{
"context": ")\n;; transient-values '((magit-commit \"--gpg-sign=5F6C0EA160557395\"\n;; (magit-reba",
"end": 4493,
"score": 0.6600808501243591,
"start": 4491,
"tag": "PASSWORD",
"value": "5F"
},
{
"context": "ient-values '((magit-commit \"--gpg-sign=5F6C0EA160557395\"\n;; (magit-rebase \"--autos",
"end": 4504,
"score": 0.5506229400634766,
"start": 4501,
"tag": "PASSWORD",
"value": "557"
},
{
"context": "-values '((magit-commit \"--gpg-sign=5F6C0EA160557395\"\n;; (magit-rebase \"--autosqu",
"end": 4506,
"score": 0.51233971118927,
"start": 4505,
"tag": "PASSWORD",
"value": "9"
},
{
"context": " (magit-rebase \"--autosquash\" \"--gpg-sign=5F6C0EA160557395\")\n;; (magit-pu",
"end": 4574,
"score": 0.7012319564819336,
"start": 4573,
"tag": "PASSWORD",
"value": "5"
},
{
"context": " (magit-pull \"--rebase\" \"--gpg-sign=5F6C0EA160557395\"))))\n\n;; editor/evil\n;; (map! :n \"",
"end": 4651,
"score": 0.742619514465332,
"start": 4650,
"tag": "PASSWORD",
"value": "5"
},
{
"context": "eshold 666)\n\n;; lang/python\n;; https://github.com/hlissner/doom-emacs/issues/212 FIXME install pyenv?\n;; (wh",
"end": 5649,
"score": 0.9942447543144226,
"start": 5641,
"tag": "USERNAME",
"value": "hlissner"
}
] | config.el | Vvkmnn/v.doom.d | 0 | ;;; ~/.config/doom/config.el -*- lexical-binding: t; -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;; ;;;;;;; ;;;;;;;;;;;
;; ;;;;;;;;;;; ;;;;;;;;; ;;;;;;;;;
;; ;;;;;;;;; ;;;;;;;; ;;;;;;;
;; ;;;;;;;; ;;;;;; ;;;;;;
;; ;;;;;;; ;;;;;; ;;;;;
;; ;;;;;; ;;;;;;; ;;;;;; ;;;;
;; ;;;;; ;;;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;; ;;;;; ;;;
;; ;;;;; ;;;;;; ;;;; ;;;
;; ;;;;; ;;;;;; ;;; ;;;
;; ;;;;; ;;;;;; ; ;;;
;; ;;;;;; ;;;;;; ;;;;
;; ;;;;;;; ;;;;; ;;;;;
;; ;;;;;;;; ;;;;; ;;;;;;
;; ;;;;;;;;;; ;;;;; ;;;;;;;;
;; ;;;;;;;;;;;; ;;;;; ;;;;;;;;;;
;; ;;;;;;;;;;;;;; ;;;;; ;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; user
(setq-default
user-full-name "Vivek Menon"
user-mail-address "v+emacs@vvkmnn.xyz")
;; editor
(setq frame-title-format '("vDoom Emacs | %m | %b") ;; Title
;; doom-private-dir "~/.v.doom.d/" ;; Private Dir
menu-bar-mode t ;; For Yabai WM NOTE https://github.com/koekeishiya/yabai/issues/86#issuecomment-507934212
doom-theme 'doom-city-lights) ;; Theme
;;; ui/pretty-code
;; Iosevka
;; (setq doom-font (font-spec :family "Iosevka" :size 13)
;; doom-unicode-font (font-spec :family "Iosevka" :size 13)
;; doom-variable-pitch-font (font-spec :family "Iosevka" :size 13))
;; Fira
(setq doom-font (font-spec :family "Fira Code" :size 13)
doom-unicode-font (font-spec :family "Fira Mono" :size 13)
doom-variable-pitch-font (font-spec :family "Fira Sans" :size 13))
; Package Lists
; (add-to-list 'package-archives
; '("melpa" . "http://melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("melpa-stable" . "http://stable.melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("marmalade" . "https://marmalade-repo.org/packages/") t)
; (add-to-list 'package-archives
; '("gnu elpa" . "https://elpa.gnu.org/packages/") t)
; Certificates
; (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
; Dictionary
; (setq ispell-program-name "aspell"
; ispell-silently-savep t)
;; tools/lsp
;; (setq lsp-enable-file-watchers nil)
;; lang/latex
(setq-default TeX-engine 'xetex
TeX-PDF-mode t
TeX-master nil)
(setenv "PATH" (concat (getenv "PATH") ":/Library/TeX/texbin/"))
(setq exec-path (append exec-path '("/Library/TeX/texbin/")))
;; lang/cc
;; (after! ccls
;; (setq ccls-initialization-options
;; '(:clang (:extraArgs ["-isystem/Library/Developer/CommandLineTools/usr/include/c++/v1"
;; "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/usr/local/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"]
;; :resourceDir "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0")))
;; )
;; app/rss
; (add-hook! 'elfeed-show-mode-hook (text-scale-set 2))
;; tools/magit
; (setq magit-save-repository-buffers nil)
;; magit-repository-directories '(("~/work" . 2))
;; transient-values '((magit-commit "--gpg-sign=5F6C0EA160557395"
;; (magit-rebase "--autosquash" "--gpg-sign=5F6C0EA160557395")
;; (magit-pull "--rebase" "--gpg-sign=5F6C0EA160557395"))))
;; editor/evil
;; (map! :n "C-h" 'evil-window-left
;; :n "C-j" 'evil-window-down
;; :n "C-k" 'evil-window-up
;; :n "C-l" 'evil-window-right
;;
;; ;; :m "M-j" '+default:multi-next-line
;; ;; :m "M-k" '+default:multi-previous-line
;;
;; (:map evil-treemacs-state-map
;; "C-h" 'evil-window-left
;; "C-l" 'evil-window-right))
;; :tools/macos
(when (eq system-type 'darwin) ;; macOS
(setq ns-use-thin-smoothing t)
;; (mac-auto-operator-composition-mode)
(add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
(add-to-list 'default-frame-alist '(ns-appearance . dark))
(add-hook 'window-setup-hook #'toggle-frame-maximized))
;; lang/org
;; (setq org-dir "~/.org"
;; org-directory "~/.org/"
;; org-ellipsis " ▼ ")
;; editor/flycheck
(setq flycheck-checker-error-threshold 666)
;; lang/python
;; https://github.com/hlissner/doom-emacs/issues/212 FIXME install pyenv?
;; (when (and (executable-find "python3")
;; (string= python-shell-interpreter "python"))
;; (setq python-shell-interpreter "python3"))
;;
;; ;; Env vars
;; (with-eval-after-load 'exec-path-from-shell
;; (exec-path-from-shell-copy-env "PYTHONPATH"))
;;; lang/plantuml
;; (org-babel-do-load-languages
;; 'org-babel-load-languages
;; '((plantuml . t))) ;; Add Plant UML to Org
;; NOTE Review upstream
;; (defvar xdg-data (getenv "XDG_DATA_HOME"))
;; (defvar xdg-bin (getenv "XDG_BIN_HOME"))
;; (defvar xdg-cache (getenv "XDG_CACHE_HOME"))
;; (defvar xdg-config (getenv "XDG_CONFIG_HOME"))
;; +workspaces-switch-project-function #'ignore
;; (add-to-list 'org-modules 'org-habit t)
;; ;;
;; ;; Host-specific config
;; (when (equal (system-name) "triton")
;; ;; I've swapped these keys on my keyboard
;; (setq x-super-keysym 'meta
;; x-meta-keysym 'super))
;; (pcase (system-name)
;; ("halimede"
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 9)))
;; (_
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 12)
;; +modeline-height 25)))
;; ; (:when IS-LINUX
;; ; "s-x" #'execute-extended-command
;; ; "s-;" #'eval-expression
;; ; ;; use super for window/frame navigation/manipulation
;; ; "s-w" #'delete-window
;; ; "s-W" #'delete-frame
;; ; "s-n" #'+default/new-buffer
;; ; "s-N" #'make-frame
;; ; "s-q" (if (daemonp) #'delete-frame #'evil-quit-all)
;; ; ;; Restore OS undo, save, copy, & paste keys (without cua-mode, because
;; ; ;; it imposes some other functionality and overhead we don't need)
;; ; "s-z" #'undo
;; ; "s-c" (if (featurep 'evil) #'evil-yank #'copy-region-as-kill)
;; ; "s-v" #'yank
;; ; "s-s" #'save-buffer
;; ; ;; Buffer-local font scaling
;; ; "s-+" (λ! (text-scale-set 0))
;; ; "s-=" #'text-scale-increase
;; ; "s--" #'text-scale-decrease
;; ; ;; Conventional text-editing keys
;; ; "s-a" #'mark-whole-buffer
;; ; :gi [s-return] #'+default/newline-below
;; ; :gi [s-S-return] #'+default/newline-above
;; ; :gi [s-backspace] #'doom/backward-kill-to-bol-and-indent)
;; ; :leader
;; ; (:prefix "f"
;; ; :desc "Find file in dotfiles" "t" #'+hlissner/find-in-dotfiles
;; ; :desc "Browse dotfiles" "T" #'+hlissner/browse-dotfiles)
;; ; (:prefix "n"
;; ; :desc "Open mode notes" "m" #'+hlissner/find-notes-for-major-mode
;; ; :desc "Open project notes" "p" #'+hlissner/find-notes-for-project))
;; ; ;;
;; ; ;; Modules
;; ; ;; emacs/eshell
;; ; (after! eshell
;; ; (set-eshell-alias!
;; ; "f" "find-file $1"
;; ; "l" "ls -lh"
;; ; "d" "dired $1"
;; ; "gl" "(call-interactively 'magit-log-current)"
;; ; "gs" "magit-status"
;; ; "gc" "magit-commit"))
;; ; ;;
;; ; ;; Custom
;; ; (def-project-mode! +javascript-screeps-mode
;; ; :match "/screeps\\(?:-ai\\)?/.+$"
;; ; :modes (+javascript-npm-mode)
;; ; :add-hooks (+javascript|init-screeps-mode)
;; ; :on-load (load! "lisp/screeps"))
| 48857 | ;;; ~/.config/doom/config.el -*- lexical-binding: t; -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;; ;;;;;;; ;;;;;;;;;;;
;; ;;;;;;;;;;; ;;;;;;;;; ;;;;;;;;;
;; ;;;;;;;;; ;;;;;;;; ;;;;;;;
;; ;;;;;;;; ;;;;;; ;;;;;;
;; ;;;;;;; ;;;;;; ;;;;;
;; ;;;;;; ;;;;;;; ;;;;;; ;;;;
;; ;;;;; ;;;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;; ;;;;; ;;;
;; ;;;;; ;;;;;; ;;;; ;;;
;; ;;;;; ;;;;;; ;;; ;;;
;; ;;;;; ;;;;;; ; ;;;
;; ;;;;;; ;;;;;; ;;;;
;; ;;;;;;; ;;;;; ;;;;;
;; ;;;;;;;; ;;;;; ;;;;;;
;; ;;;;;;;;;; ;;;;; ;;;;;;;;
;; ;;;;;;;;;;;; ;;;;; ;;;;;;;;;;
;; ;;;;;;;;;;;;;; ;;;;; ;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; user
(setq-default
user-full-name "<NAME>"
user-mail-address "<EMAIL>")
;; editor
(setq frame-title-format '("vDoom Emacs | %m | %b") ;; Title
;; doom-private-dir "~/.v.doom.d/" ;; Private Dir
menu-bar-mode t ;; For Yabai WM NOTE https://github.com/koekeishiya/yabai/issues/86#issuecomment-507934212
doom-theme 'doom-city-lights) ;; Theme
;;; ui/pretty-code
;; Iosevka
;; (setq doom-font (font-spec :family "Iosevka" :size 13)
;; doom-unicode-font (font-spec :family "Iosevka" :size 13)
;; doom-variable-pitch-font (font-spec :family "Iosevka" :size 13))
;; Fira
(setq doom-font (font-spec :family "Fira Code" :size 13)
doom-unicode-font (font-spec :family "Fira Mono" :size 13)
doom-variable-pitch-font (font-spec :family "Fira Sans" :size 13))
; Package Lists
; (add-to-list 'package-archives
; '("melpa" . "http://melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("melpa-stable" . "http://stable.melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("marmalade" . "https://marmalade-repo.org/packages/") t)
; (add-to-list 'package-archives
; '("gnu elpa" . "https://elpa.gnu.org/packages/") t)
; Certificates
; (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
; Dictionary
; (setq ispell-program-name "aspell"
; ispell-silently-savep t)
;; tools/lsp
;; (setq lsp-enable-file-watchers nil)
;; lang/latex
(setq-default TeX-engine 'xetex
TeX-PDF-mode t
TeX-master nil)
(setenv "PATH" (concat (getenv "PATH") ":/Library/TeX/texbin/"))
(setq exec-path (append exec-path '("/Library/TeX/texbin/")))
;; lang/cc
;; (after! ccls
;; (setq ccls-initialization-options
;; '(:clang (:extraArgs ["-isystem/Library/Developer/CommandLineTools/usr/include/c++/v1"
;; "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/usr/local/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"]
;; :resourceDir "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0")))
;; )
;; app/rss
; (add-hook! 'elfeed-show-mode-hook (text-scale-set 2))
;; tools/magit
; (setq magit-save-repository-buffers nil)
;; magit-repository-directories '(("~/work" . 2))
;; transient-values '((magit-commit "--gpg-sign=<PASSWORD>6C0EA160<PASSWORD>3<PASSWORD>5"
;; (magit-rebase "--autosquash" "--gpg-sign=<PASSWORD>F6C0EA160557395")
;; (magit-pull "--rebase" "--gpg-sign=<PASSWORD>F6C0EA160557395"))))
;; editor/evil
;; (map! :n "C-h" 'evil-window-left
;; :n "C-j" 'evil-window-down
;; :n "C-k" 'evil-window-up
;; :n "C-l" 'evil-window-right
;;
;; ;; :m "M-j" '+default:multi-next-line
;; ;; :m "M-k" '+default:multi-previous-line
;;
;; (:map evil-treemacs-state-map
;; "C-h" 'evil-window-left
;; "C-l" 'evil-window-right))
;; :tools/macos
(when (eq system-type 'darwin) ;; macOS
(setq ns-use-thin-smoothing t)
;; (mac-auto-operator-composition-mode)
(add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
(add-to-list 'default-frame-alist '(ns-appearance . dark))
(add-hook 'window-setup-hook #'toggle-frame-maximized))
;; lang/org
;; (setq org-dir "~/.org"
;; org-directory "~/.org/"
;; org-ellipsis " ▼ ")
;; editor/flycheck
(setq flycheck-checker-error-threshold 666)
;; lang/python
;; https://github.com/hlissner/doom-emacs/issues/212 FIXME install pyenv?
;; (when (and (executable-find "python3")
;; (string= python-shell-interpreter "python"))
;; (setq python-shell-interpreter "python3"))
;;
;; ;; Env vars
;; (with-eval-after-load 'exec-path-from-shell
;; (exec-path-from-shell-copy-env "PYTHONPATH"))
;;; lang/plantuml
;; (org-babel-do-load-languages
;; 'org-babel-load-languages
;; '((plantuml . t))) ;; Add Plant UML to Org
;; NOTE Review upstream
;; (defvar xdg-data (getenv "XDG_DATA_HOME"))
;; (defvar xdg-bin (getenv "XDG_BIN_HOME"))
;; (defvar xdg-cache (getenv "XDG_CACHE_HOME"))
;; (defvar xdg-config (getenv "XDG_CONFIG_HOME"))
;; +workspaces-switch-project-function #'ignore
;; (add-to-list 'org-modules 'org-habit t)
;; ;;
;; ;; Host-specific config
;; (when (equal (system-name) "triton")
;; ;; I've swapped these keys on my keyboard
;; (setq x-super-keysym 'meta
;; x-meta-keysym 'super))
;; (pcase (system-name)
;; ("halimede"
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 9)))
;; (_
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 12)
;; +modeline-height 25)))
;; ; (:when IS-LINUX
;; ; "s-x" #'execute-extended-command
;; ; "s-;" #'eval-expression
;; ; ;; use super for window/frame navigation/manipulation
;; ; "s-w" #'delete-window
;; ; "s-W" #'delete-frame
;; ; "s-n" #'+default/new-buffer
;; ; "s-N" #'make-frame
;; ; "s-q" (if (daemonp) #'delete-frame #'evil-quit-all)
;; ; ;; Restore OS undo, save, copy, & paste keys (without cua-mode, because
;; ; ;; it imposes some other functionality and overhead we don't need)
;; ; "s-z" #'undo
;; ; "s-c" (if (featurep 'evil) #'evil-yank #'copy-region-as-kill)
;; ; "s-v" #'yank
;; ; "s-s" #'save-buffer
;; ; ;; Buffer-local font scaling
;; ; "s-+" (λ! (text-scale-set 0))
;; ; "s-=" #'text-scale-increase
;; ; "s--" #'text-scale-decrease
;; ; ;; Conventional text-editing keys
;; ; "s-a" #'mark-whole-buffer
;; ; :gi [s-return] #'+default/newline-below
;; ; :gi [s-S-return] #'+default/newline-above
;; ; :gi [s-backspace] #'doom/backward-kill-to-bol-and-indent)
;; ; :leader
;; ; (:prefix "f"
;; ; :desc "Find file in dotfiles" "t" #'+hlissner/find-in-dotfiles
;; ; :desc "Browse dotfiles" "T" #'+hlissner/browse-dotfiles)
;; ; (:prefix "n"
;; ; :desc "Open mode notes" "m" #'+hlissner/find-notes-for-major-mode
;; ; :desc "Open project notes" "p" #'+hlissner/find-notes-for-project))
;; ; ;;
;; ; ;; Modules
;; ; ;; emacs/eshell
;; ; (after! eshell
;; ; (set-eshell-alias!
;; ; "f" "find-file $1"
;; ; "l" "ls -lh"
;; ; "d" "dired $1"
;; ; "gl" "(call-interactively 'magit-log-current)"
;; ; "gs" "magit-status"
;; ; "gc" "magit-commit"))
;; ; ;;
;; ; ;; Custom
;; ; (def-project-mode! +javascript-screeps-mode
;; ; :match "/screeps\\(?:-ai\\)?/.+$"
;; ; :modes (+javascript-npm-mode)
;; ; :add-hooks (+javascript|init-screeps-mode)
;; ; :on-load (load! "lisp/screeps"))
| true | ;;; ~/.config/doom/config.el -*- lexical-binding: t; -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;; ;;;;;;; ;;;;;;;;;;;
;; ;;;;;;;;;;; ;;;;;;;;; ;;;;;;;;;
;; ;;;;;;;;; ;;;;;;;; ;;;;;;;
;; ;;;;;;;; ;;;;;; ;;;;;;
;; ;;;;;;; ;;;;;; ;;;;;
;; ;;;;;; ;;;;;;; ;;;;;; ;;;;
;; ;;;;; ;;;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;;; ;;;;;; ;;;
;; ;;;;; ;;;;;; ;;;;; ;;;
;; ;;;;; ;;;;;; ;;;; ;;;
;; ;;;;; ;;;;;; ;;; ;;;
;; ;;;;; ;;;;;; ; ;;;
;; ;;;;;; ;;;;;; ;;;;
;; ;;;;;;; ;;;;; ;;;;;
;; ;;;;;;;; ;;;;; ;;;;;;
;; ;;;;;;;;;; ;;;;; ;;;;;;;;
;; ;;;;;;;;;;;; ;;;;; ;;;;;;;;;;
;; ;;;;;;;;;;;;;; ;;;;; ;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; user
(setq-default
user-full-name "PI:NAME:<NAME>END_PI"
user-mail-address "PI:EMAIL:<EMAIL>END_PI")
;; editor
(setq frame-title-format '("vDoom Emacs | %m | %b") ;; Title
;; doom-private-dir "~/.v.doom.d/" ;; Private Dir
menu-bar-mode t ;; For Yabai WM NOTE https://github.com/koekeishiya/yabai/issues/86#issuecomment-507934212
doom-theme 'doom-city-lights) ;; Theme
;;; ui/pretty-code
;; Iosevka
;; (setq doom-font (font-spec :family "Iosevka" :size 13)
;; doom-unicode-font (font-spec :family "Iosevka" :size 13)
;; doom-variable-pitch-font (font-spec :family "Iosevka" :size 13))
;; Fira
(setq doom-font (font-spec :family "Fira Code" :size 13)
doom-unicode-font (font-spec :family "Fira Mono" :size 13)
doom-variable-pitch-font (font-spec :family "Fira Sans" :size 13))
; Package Lists
; (add-to-list 'package-archives
; '("melpa" . "http://melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("melpa-stable" . "http://stable.melpa.org/packages/") t)
; (add-to-list 'package-archives
; '("marmalade" . "https://marmalade-repo.org/packages/") t)
; (add-to-list 'package-archives
; '("gnu elpa" . "https://elpa.gnu.org/packages/") t)
; Certificates
; (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
; Dictionary
; (setq ispell-program-name "aspell"
; ispell-silently-savep t)
;; tools/lsp
;; (setq lsp-enable-file-watchers nil)
;; lang/latex
(setq-default TeX-engine 'xetex
TeX-PDF-mode t
TeX-master nil)
(setenv "PATH" (concat (getenv "PATH") ":/Library/TeX/texbin/"))
(setq exec-path (append exec-path '("/Library/TeX/texbin/")))
;; lang/cc
;; (after! ccls
;; (setq ccls-initialization-options
;; '(:clang (:extraArgs ["-isystem/Library/Developer/CommandLineTools/usr/include/c++/v1"
;; "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/usr/local/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include"
;; "-isystem/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"]
;; :resourceDir "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0")))
;; )
;; app/rss
; (add-hook! 'elfeed-show-mode-hook (text-scale-set 2))
;; tools/magit
; (setq magit-save-repository-buffers nil)
;; magit-repository-directories '(("~/work" . 2))
;; transient-values '((magit-commit "--gpg-sign=PI:PASSWORD:<PASSWORD>END_PI6C0EA160PI:PASSWORD:<PASSWORD>END_PI3PI:PASSWORD:<PASSWORD>END_PI5"
;; (magit-rebase "--autosquash" "--gpg-sign=PI:PASSWORD:<PASSWORD>END_PIF6C0EA160557395")
;; (magit-pull "--rebase" "--gpg-sign=PI:PASSWORD:<PASSWORD>END_PIF6C0EA160557395"))))
;; editor/evil
;; (map! :n "C-h" 'evil-window-left
;; :n "C-j" 'evil-window-down
;; :n "C-k" 'evil-window-up
;; :n "C-l" 'evil-window-right
;;
;; ;; :m "M-j" '+default:multi-next-line
;; ;; :m "M-k" '+default:multi-previous-line
;;
;; (:map evil-treemacs-state-map
;; "C-h" 'evil-window-left
;; "C-l" 'evil-window-right))
;; :tools/macos
(when (eq system-type 'darwin) ;; macOS
(setq ns-use-thin-smoothing t)
;; (mac-auto-operator-composition-mode)
(add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(add-to-list 'default-frame-alist '(ns-transparent-titlebar . t))
(add-to-list 'default-frame-alist '(ns-appearance . dark))
(add-hook 'window-setup-hook #'toggle-frame-maximized))
;; lang/org
;; (setq org-dir "~/.org"
;; org-directory "~/.org/"
;; org-ellipsis " ▼ ")
;; editor/flycheck
(setq flycheck-checker-error-threshold 666)
;; lang/python
;; https://github.com/hlissner/doom-emacs/issues/212 FIXME install pyenv?
;; (when (and (executable-find "python3")
;; (string= python-shell-interpreter "python"))
;; (setq python-shell-interpreter "python3"))
;;
;; ;; Env vars
;; (with-eval-after-load 'exec-path-from-shell
;; (exec-path-from-shell-copy-env "PYTHONPATH"))
;;; lang/plantuml
;; (org-babel-do-load-languages
;; 'org-babel-load-languages
;; '((plantuml . t))) ;; Add Plant UML to Org
;; NOTE Review upstream
;; (defvar xdg-data (getenv "XDG_DATA_HOME"))
;; (defvar xdg-bin (getenv "XDG_BIN_HOME"))
;; (defvar xdg-cache (getenv "XDG_CACHE_HOME"))
;; (defvar xdg-config (getenv "XDG_CONFIG_HOME"))
;; +workspaces-switch-project-function #'ignore
;; (add-to-list 'org-modules 'org-habit t)
;; ;;
;; ;; Host-specific config
;; (when (equal (system-name) "triton")
;; ;; I've swapped these keys on my keyboard
;; (setq x-super-keysym 'meta
;; x-meta-keysym 'super))
;; (pcase (system-name)
;; ("halimede"
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 9)))
;; (_
;; (setq doom-font (font-spec :family "Input Mono Narrow" :size 12)
;; +modeline-height 25)))
;; ; (:when IS-LINUX
;; ; "s-x" #'execute-extended-command
;; ; "s-;" #'eval-expression
;; ; ;; use super for window/frame navigation/manipulation
;; ; "s-w" #'delete-window
;; ; "s-W" #'delete-frame
;; ; "s-n" #'+default/new-buffer
;; ; "s-N" #'make-frame
;; ; "s-q" (if (daemonp) #'delete-frame #'evil-quit-all)
;; ; ;; Restore OS undo, save, copy, & paste keys (without cua-mode, because
;; ; ;; it imposes some other functionality and overhead we don't need)
;; ; "s-z" #'undo
;; ; "s-c" (if (featurep 'evil) #'evil-yank #'copy-region-as-kill)
;; ; "s-v" #'yank
;; ; "s-s" #'save-buffer
;; ; ;; Buffer-local font scaling
;; ; "s-+" (λ! (text-scale-set 0))
;; ; "s-=" #'text-scale-increase
;; ; "s--" #'text-scale-decrease
;; ; ;; Conventional text-editing keys
;; ; "s-a" #'mark-whole-buffer
;; ; :gi [s-return] #'+default/newline-below
;; ; :gi [s-S-return] #'+default/newline-above
;; ; :gi [s-backspace] #'doom/backward-kill-to-bol-and-indent)
;; ; :leader
;; ; (:prefix "f"
;; ; :desc "Find file in dotfiles" "t" #'+hlissner/find-in-dotfiles
;; ; :desc "Browse dotfiles" "T" #'+hlissner/browse-dotfiles)
;; ; (:prefix "n"
;; ; :desc "Open mode notes" "m" #'+hlissner/find-notes-for-major-mode
;; ; :desc "Open project notes" "p" #'+hlissner/find-notes-for-project))
;; ; ;;
;; ; ;; Modules
;; ; ;; emacs/eshell
;; ; (after! eshell
;; ; (set-eshell-alias!
;; ; "f" "find-file $1"
;; ; "l" "ls -lh"
;; ; "d" "dired $1"
;; ; "gl" "(call-interactively 'magit-log-current)"
;; ; "gs" "magit-status"
;; ; "gc" "magit-commit"))
;; ; ;;
;; ; ;; Custom
;; ; (def-project-mode! +javascript-screeps-mode
;; ; :match "/screeps\\(?:-ai\\)?/.+$"
;; ; :modes (+javascript-npm-mode)
;; ; :add-hooks (+javascript|init-screeps-mode)
;; ; :on-load (load! "lisp/screeps"))
|
[
{
"context": "see http://cc-mode.sourceforge.net/index.php\n;;\n;; Paolo de Dios <paolodedios@gmail.com>\n;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 113,
"score": 0.9998682141304016,
"start": 100,
"tag": "NAME",
"value": "Paolo de Dios"
},
{
"context": "de.sourceforge.net/index.php\n;;\n;; Paolo de Dios <paolodedios@gmail.com>\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 136,
"score": 0.9999265670776367,
"start": 115,
"tag": "EMAIL",
"value": "paolodedios@gmail.com"
}
] | .emacs.d/modules/config-cc-mode.el | paolodedios/dot-files | 0 | ;; -*- mode: emacs-lisp -*-
;;
;; C/C++ mode
;; @see http://cc-mode.sourceforge.net/index.php
;;
;; Paolo de Dios <paolodedios@gmail.com>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode. Esp for identation settings, require CC-mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'cc-mode)
(autoload 'c++-mode "cc-mode" "C++ Editing Mode" t)
(autoload 'c-mode "cc-mode" "C Editing Mode" t)
(autoload 'objc-mode "cc-mode" "Objective-C Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Define Programming constants
;;
;; Note - default code identation styles
;; gnu, k&r, bsd, stroustrup, whitesmith, ellemtel, linux, python, java, awk
;;
;; @see http://www.gnu.org/software/emacs/manual/html_node/ccmode/Indentation-Engine-Basics.html
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode style
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst my-cc-mode-programming-style
;; hanging brace setup
'((c-hanging-braces-alist .
((brace-list-open after)
(brace-entry-open after)
(substatement-open before)
(block-close . c-snug-do-while)
(extern-lang-open after)
(inexpr-class-open after)
(inexpr-class-close before)
))
;; cleanup shortcuts
(c-cleanup-list .
((brace-else-brace )
(brace-elseif-brace )
(brace-catch-brace )
(list-close-comma )
))
;; indentation offsets
;; + 'c-basic-offset' times 1
;; - 'c-basic-offset' times -1
;; ++ 'c-basic-offset' times 2
;; -- 'c-basic-offset' times -2
;; * 'c-basic-offset' times 0.5
;; / 'c-basic-offset' times -0.5
(c-offsets-alist .
((access-label . -2)
(inline-open . 0)
(substatement-open . 0)
(statement-block-intro . +)
(block-close . 0)
(do-while-closure . 0)
(case-label . +)
(statement-case-intro . +)
(statement-cont c-lineup-cascaded-calls +)
(stream-op . c-lineup-streamop)
;; Don't indent inside namespaces, extern, etc
(incomposition . 0)
(inextern-lang . 0)
(inmodule . 0)
(innamespace . 0)
;; Preprocessor macros
(cpp-define-intro c-lineup-cpp-define +)
(cpp-macro . [ 0 ])
(cpp-macro-cont . +)
))
(c-lineup-math 1)
(c-lineup-inexpr-block 1)
) "My C/C++ Programming Style")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C++ mode hook section, called on entry of C++ mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; function to lineup stream operators in c++
(defun c-lineup-streamop (langelem)
(save-excursion
(goto-char (cdr langelem))
(re-search-forward "<<\\|>>" (c-point 'eol) 'move)
(goto-char (match-beginning 0))
(vector (current-column))
)
)
(add-hook 'c++-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Objective-C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'objc-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C-mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mozilla/NSPR specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("nsresult"
"PRStatus"
"PRBool"
"PRPackedBool"
"PRFloat64"
"PRIntn"
"PRUWord"
"PRInt8"
"PRInt16"
"PRInt32"
"PRInt64"
"PRUint"
"PRUint8"
"PRUint16"
"PRUnichar"
"PRUint32"
"PRUint64"
"PLOptStatus"
"PLOptState"
"PRThread"
"PRThreadType"
"PRThreadScope"
"PRThreadState"
"PRThreadPriority"
"PRLock"
"PRCondVar"
"PRMonitor"
"PRRWLock"
"PRDir"
"PRPollDesc"
"PRFileDesc"
"PRIOMethods"
"PRFilePrivate"
"PRDescIdentity"
"PRFileInfo"
"PRFileInfo64"
"PRFileType"
"PRNetAddr"
"PRIPv6Addr"
"PRSocketOptionData"
"PRSockOption"
"PRLinger"
"PRMcastRequest"
"PRFileMap"
"PRHostEnt"
"PRProtoEnt"
"PRIntervalTime"
"PRTime"
"PRTimeParameters"
"PRExplodedTime"
"prbitmap_t"
"PRCList"
"PRLibrary"
"PRStaticLinkTable"
"PRProcess"
"PRProcessAttr"
"PRSysInfo"
"PRCounterHandle"
"PRJobIoDesc"
"PRJobFn"
"PRThreadPool"
"PRJob"
"PLHashEntry"
"PLHashTable"
"PLHashNumber"
"PLHashFunction"
"PLHashComparator"
"PLHashEnumerator"
"PLHashAllocOps"
"PRCallOnceType"
)
c-font-lock-extra-types)
)
;; Win32 specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("LPC?\\(W\\|T\\|OLE\\)?\\STR" "HRESULT"
"BOOL"
"BYTE"
"DWORD"
"SOCKET"
"idl_char"
"idl_boolean"
"idl_byte"
"idl_\\(short\\|long\\)_float"
"idl_u?\\(small\\|short\\|long\\)_int"
"boolean32"
"unsigned\\(32\\|16\\)"
"SAFEARRAY"
"boolean"
"UINT"
"ULONG"
"VARIANT"
)
c-font-lock-extra-types)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C++ mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq c++-font-lock-extra-types
(append
c-font-lock-extra-types
c++-font-lock-extra-types
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook 'turn-on-font-lock)
(add-hook 'objc-mode-hook 'turn-on-font-lock)
(add-hook 'c++-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.c$" . c-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.m$" . objc-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.h$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.hpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.H$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cxx$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.C$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.idl$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.ac$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.mk$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("Makefile$" . makefile-mode )) auto-mode-alist))
| 40370 | ;; -*- mode: emacs-lisp -*-
;;
;; C/C++ mode
;; @see http://cc-mode.sourceforge.net/index.php
;;
;; <NAME> <<EMAIL>>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode. Esp for identation settings, require CC-mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'cc-mode)
(autoload 'c++-mode "cc-mode" "C++ Editing Mode" t)
(autoload 'c-mode "cc-mode" "C Editing Mode" t)
(autoload 'objc-mode "cc-mode" "Objective-C Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Define Programming constants
;;
;; Note - default code identation styles
;; gnu, k&r, bsd, stroustrup, whitesmith, ellemtel, linux, python, java, awk
;;
;; @see http://www.gnu.org/software/emacs/manual/html_node/ccmode/Indentation-Engine-Basics.html
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode style
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst my-cc-mode-programming-style
;; hanging brace setup
'((c-hanging-braces-alist .
((brace-list-open after)
(brace-entry-open after)
(substatement-open before)
(block-close . c-snug-do-while)
(extern-lang-open after)
(inexpr-class-open after)
(inexpr-class-close before)
))
;; cleanup shortcuts
(c-cleanup-list .
((brace-else-brace )
(brace-elseif-brace )
(brace-catch-brace )
(list-close-comma )
))
;; indentation offsets
;; + 'c-basic-offset' times 1
;; - 'c-basic-offset' times -1
;; ++ 'c-basic-offset' times 2
;; -- 'c-basic-offset' times -2
;; * 'c-basic-offset' times 0.5
;; / 'c-basic-offset' times -0.5
(c-offsets-alist .
((access-label . -2)
(inline-open . 0)
(substatement-open . 0)
(statement-block-intro . +)
(block-close . 0)
(do-while-closure . 0)
(case-label . +)
(statement-case-intro . +)
(statement-cont c-lineup-cascaded-calls +)
(stream-op . c-lineup-streamop)
;; Don't indent inside namespaces, extern, etc
(incomposition . 0)
(inextern-lang . 0)
(inmodule . 0)
(innamespace . 0)
;; Preprocessor macros
(cpp-define-intro c-lineup-cpp-define +)
(cpp-macro . [ 0 ])
(cpp-macro-cont . +)
))
(c-lineup-math 1)
(c-lineup-inexpr-block 1)
) "My C/C++ Programming Style")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C++ mode hook section, called on entry of C++ mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; function to lineup stream operators in c++
(defun c-lineup-streamop (langelem)
(save-excursion
(goto-char (cdr langelem))
(re-search-forward "<<\\|>>" (c-point 'eol) 'move)
(goto-char (match-beginning 0))
(vector (current-column))
)
)
(add-hook 'c++-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Objective-C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'objc-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C-mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mozilla/NSPR specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("nsresult"
"PRStatus"
"PRBool"
"PRPackedBool"
"PRFloat64"
"PRIntn"
"PRUWord"
"PRInt8"
"PRInt16"
"PRInt32"
"PRInt64"
"PRUint"
"PRUint8"
"PRUint16"
"PRUnichar"
"PRUint32"
"PRUint64"
"PLOptStatus"
"PLOptState"
"PRThread"
"PRThreadType"
"PRThreadScope"
"PRThreadState"
"PRThreadPriority"
"PRLock"
"PRCondVar"
"PRMonitor"
"PRRWLock"
"PRDir"
"PRPollDesc"
"PRFileDesc"
"PRIOMethods"
"PRFilePrivate"
"PRDescIdentity"
"PRFileInfo"
"PRFileInfo64"
"PRFileType"
"PRNetAddr"
"PRIPv6Addr"
"PRSocketOptionData"
"PRSockOption"
"PRLinger"
"PRMcastRequest"
"PRFileMap"
"PRHostEnt"
"PRProtoEnt"
"PRIntervalTime"
"PRTime"
"PRTimeParameters"
"PRExplodedTime"
"prbitmap_t"
"PRCList"
"PRLibrary"
"PRStaticLinkTable"
"PRProcess"
"PRProcessAttr"
"PRSysInfo"
"PRCounterHandle"
"PRJobIoDesc"
"PRJobFn"
"PRThreadPool"
"PRJob"
"PLHashEntry"
"PLHashTable"
"PLHashNumber"
"PLHashFunction"
"PLHashComparator"
"PLHashEnumerator"
"PLHashAllocOps"
"PRCallOnceType"
)
c-font-lock-extra-types)
)
;; Win32 specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("LPC?\\(W\\|T\\|OLE\\)?\\STR" "HRESULT"
"BOOL"
"BYTE"
"DWORD"
"SOCKET"
"idl_char"
"idl_boolean"
"idl_byte"
"idl_\\(short\\|long\\)_float"
"idl_u?\\(small\\|short\\|long\\)_int"
"boolean32"
"unsigned\\(32\\|16\\)"
"SAFEARRAY"
"boolean"
"UINT"
"ULONG"
"VARIANT"
)
c-font-lock-extra-types)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C++ mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq c++-font-lock-extra-types
(append
c-font-lock-extra-types
c++-font-lock-extra-types
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook 'turn-on-font-lock)
(add-hook 'objc-mode-hook 'turn-on-font-lock)
(add-hook 'c++-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.c$" . c-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.m$" . objc-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.h$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.hpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.H$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cxx$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.C$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.idl$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.ac$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.mk$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("Makefile$" . makefile-mode )) auto-mode-alist))
| true | ;; -*- mode: emacs-lisp -*-
;;
;; C/C++ mode
;; @see http://cc-mode.sourceforge.net/index.php
;;
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode. Esp for identation settings, require CC-mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'cc-mode)
(autoload 'c++-mode "cc-mode" "C++ Editing Mode" t)
(autoload 'c-mode "cc-mode" "C Editing Mode" t)
(autoload 'objc-mode "cc-mode" "Objective-C Editing Mode" t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Define Programming constants
;;
;; Note - default code identation styles
;; gnu, k&r, bsd, stroustrup, whitesmith, ellemtel, linux, python, java, awk
;;
;; @see http://www.gnu.org/software/emacs/manual/html_node/ccmode/Indentation-Engine-Basics.html
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C/C++ mode style
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst my-cc-mode-programming-style
;; hanging brace setup
'((c-hanging-braces-alist .
((brace-list-open after)
(brace-entry-open after)
(substatement-open before)
(block-close . c-snug-do-while)
(extern-lang-open after)
(inexpr-class-open after)
(inexpr-class-close before)
))
;; cleanup shortcuts
(c-cleanup-list .
((brace-else-brace )
(brace-elseif-brace )
(brace-catch-brace )
(list-close-comma )
))
;; indentation offsets
;; + 'c-basic-offset' times 1
;; - 'c-basic-offset' times -1
;; ++ 'c-basic-offset' times 2
;; -- 'c-basic-offset' times -2
;; * 'c-basic-offset' times 0.5
;; / 'c-basic-offset' times -0.5
(c-offsets-alist .
((access-label . -2)
(inline-open . 0)
(substatement-open . 0)
(statement-block-intro . +)
(block-close . 0)
(do-while-closure . 0)
(case-label . +)
(statement-case-intro . +)
(statement-cont c-lineup-cascaded-calls +)
(stream-op . c-lineup-streamop)
;; Don't indent inside namespaces, extern, etc
(incomposition . 0)
(inextern-lang . 0)
(inmodule . 0)
(innamespace . 0)
;; Preprocessor macros
(cpp-define-intro c-lineup-cpp-define +)
(cpp-macro . [ 0 ])
(cpp-macro-cont . +)
))
(c-lineup-math 1)
(c-lineup-inexpr-block 1)
) "My C/C++ Programming Style")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C++ mode hook section, called on entry of C++ mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; function to lineup stream operators in c++
(defun c-lineup-streamop (langelem)
(save-excursion
(goto-char (cdr langelem))
(re-search-forward "<<\\|>>" (c-point 'eol) 'move)
(goto-char (match-beginning 0))
(vector (current-column))
)
)
(add-hook 'c++-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Objective-C hook section, called on entry of C mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'objc-mode-hook
'(lambda ()
;; toggle major mode editor options
(c-toggle-auto-state 1)
(c-toggle-hungry-state 1)
(show-paren-mode t)
(subword-mode 1)
(setq fill-column 100)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(auto-fill-mode 1)
;; bind buffer local keys
(local-set-key (quote [C-f12]) (quote compile))
(local-set-key "" (quote compile))
(local-set-key (quote [C-f11]) (quote gdb))
;; set programming style
(c-add-style "sourcery" my-cc-mode-programming-style t)
(c-set-style "sourcery")
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C-mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Mozilla/NSPR specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("nsresult"
"PRStatus"
"PRBool"
"PRPackedBool"
"PRFloat64"
"PRIntn"
"PRUWord"
"PRInt8"
"PRInt16"
"PRInt32"
"PRInt64"
"PRUint"
"PRUint8"
"PRUint16"
"PRUnichar"
"PRUint32"
"PRUint64"
"PLOptStatus"
"PLOptState"
"PRThread"
"PRThreadType"
"PRThreadScope"
"PRThreadState"
"PRThreadPriority"
"PRLock"
"PRCondVar"
"PRMonitor"
"PRRWLock"
"PRDir"
"PRPollDesc"
"PRFileDesc"
"PRIOMethods"
"PRFilePrivate"
"PRDescIdentity"
"PRFileInfo"
"PRFileInfo64"
"PRFileType"
"PRNetAddr"
"PRIPv6Addr"
"PRSocketOptionData"
"PRSockOption"
"PRLinger"
"PRMcastRequest"
"PRFileMap"
"PRHostEnt"
"PRProtoEnt"
"PRIntervalTime"
"PRTime"
"PRTimeParameters"
"PRExplodedTime"
"prbitmap_t"
"PRCList"
"PRLibrary"
"PRStaticLinkTable"
"PRProcess"
"PRProcessAttr"
"PRSysInfo"
"PRCounterHandle"
"PRJobIoDesc"
"PRJobFn"
"PRThreadPool"
"PRJob"
"PLHashEntry"
"PLHashTable"
"PLHashNumber"
"PLHashFunction"
"PLHashComparator"
"PLHashEnumerator"
"PLHashAllocOps"
"PRCallOnceType"
)
c-font-lock-extra-types)
)
;; Win32 specific extra font-lock data types
(setq c-font-lock-extra-types
(append
'("LPC?\\(W\\|T\\|OLE\\)?\\STR" "HRESULT"
"BOOL"
"BYTE"
"DWORD"
"SOCKET"
"idl_char"
"idl_boolean"
"idl_byte"
"idl_\\(short\\|long\\)_float"
"idl_u?\\(small\\|short\\|long\\)_int"
"boolean32"
"unsigned\\(32\\|16\\)"
"SAFEARRAY"
"boolean"
"UINT"
"ULONG"
"VARIANT"
)
c-font-lock-extra-types)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set C++ mode font lock extra types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq c++-font-lock-extra-types
(append
c-font-lock-extra-types
c++-font-lock-extra-types
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Turn on font-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-hook 'turn-on-font-lock)
(add-hook 'objc-mode-hook 'turn-on-font-lock)
(add-hook 'c++-mode-hook 'turn-on-font-lock)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File associations
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setq auto-mode-alist (append '(("\\.c$" . c-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.m$" . objc-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.h$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.hpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.H$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cpp$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.cxx$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.C$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.idl$" . c++-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.ac$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.mk$" . makefile-mode )) auto-mode-alist))
(setq auto-mode-alist (append '(("Makefile$" . makefile-mode )) auto-mode-alist))
|
[
{
"context": "functions -*- lexical-binding: t -*-\n;;\n;; Author: lambdart <lambdart@protonmail.com>\n;; Maintainer: lambdart",
"end": 92,
"score": 0.9993239045143127,
"start": 84,
"tag": "USERNAME",
"value": "lambdart"
},
{
"context": "*- lexical-binding: t -*-\n;;\n;; Author: lambdart <lambdart@protonmail.com>\n;; Maintainer: lambdart\n;; Version: 0.0.4 Alpha\n",
"end": 117,
"score": 0.9999309182167053,
"start": 94,
"tag": "EMAIL",
"value": "lambdart@protonmail.com"
},
{
"context": " lambdart <lambdart@protonmail.com>\n;; Maintainer: lambdart\n;; Version: 0.0.4 Alpha\n;; URL: https://github.co",
"end": 142,
"score": 0.999316930770874,
"start": 134,
"tag": "USERNAME",
"value": "lambdart"
},
{
"context": "; Version: 0.0.4 Alpha\n;; URL: https://github.com/lambdart/lex\n;; Keywords: mark mark-ring\n;;\n;; This file i",
"end": 202,
"score": 0.9993746280670166,
"start": 194,
"tag": "USERNAME",
"value": "lambdart"
},
{
"context": "Emacs.\n;;\n;;; MIT License\n;;\n;; Copyright (c) 2020 lambdart\n;;\n;; Permission is hereby granted, free of charg",
"end": 329,
"score": 0.9994940161705017,
"start": 321,
"tag": "USERNAME",
"value": "lambdart"
}
] | lex-mark.el | lambdart/lex | 3 | ;;; lex-mark.el --- mark related functions -*- lexical-binding: t -*-
;;
;; Author: lambdart <lambdart@protonmail.com>
;; Maintainer: lambdart
;; Version: 0.0.4 Alpha
;; URL: https://github.com/lambdart/lex
;; Keywords: mark mark-ring
;;
;; This file is NOT part of GNU Emacs.
;;
;;; MIT License
;;
;; Copyright (c) 2020 lambdart
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;
;;; Commentary:
;;
;; Each buffer has a special marker, which is designated “the mark”.
;; When a buffer is newly created, this marker exists but does not point
;; anywhere; this means that the mark doesn’t exist in that buffer yet.
;;
;; Add more functions/commands to facility the usage of the marks in a
;; interactive way, i.e, provides candidates/completions and a quick
;; way to select then.
;;
;; TODO: add goto-mark-in-all-buffers
;;
;; The functions names follows the code convection:
;; ([prefix-]action-target-object).
;;
;;; Code:
(require 'simple)
(eval-when-compile
(require 'cl-macs))
(defun parse-mark-line-to-string (pos)
"Return line string at position POS."
(save-excursion
(goto-char pos)
(forward-line 0)
(let ((line (car (split-string (thing-at-point 'line) "[\n\r]"))))
(remove-text-properties 0 (length line) '(read-only) line)
(if (string= "" line)
"<EMPTY LINE>"
line))))
(defun mark-ring-collection ()
"Return parsed mark ring candidates."
(cl-loop with marks = (if (mark t)
(cons (mark-marker) mark-ring)
mark-ring)
for mark in marks
with max-line-number = (line-number-at-pos (point-max))
with width = (length (number-to-string max-line-number))
for m = (format (concat "%" (number-to-string width) "d: %s")
(line-number-at-pos mark)
(parse-mark-line-to-string mark))
unless (and recip (assoc m recip))
collect (cons m mark) into recip
finally return recip))
;;;###autoload
(defun goto-mark ()
"Goto selected `mark' position."
(interactive)
(let ((collection (mark-ring-collection))
(choice nil))
(cond
;; no candidates, logs and leave
((not collection)
(message "Mark ring is empty"))
;; default, goto position (char in the buffer)
(t
;; select candidate from mark-ring-collection
(setq choice (completing-read "Goto: " collection nil t))
;; mark to char and finally go to it!
(goto-char (cdr (assoc choice collection)))))))
(provide 'lex-mark)
;;; lex-mark.el ends here
| 8256 | ;;; lex-mark.el --- mark related functions -*- lexical-binding: t -*-
;;
;; Author: lambdart <<EMAIL>>
;; Maintainer: lambdart
;; Version: 0.0.4 Alpha
;; URL: https://github.com/lambdart/lex
;; Keywords: mark mark-ring
;;
;; This file is NOT part of GNU Emacs.
;;
;;; MIT License
;;
;; Copyright (c) 2020 lambdart
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;
;;; Commentary:
;;
;; Each buffer has a special marker, which is designated “the mark”.
;; When a buffer is newly created, this marker exists but does not point
;; anywhere; this means that the mark doesn’t exist in that buffer yet.
;;
;; Add more functions/commands to facility the usage of the marks in a
;; interactive way, i.e, provides candidates/completions and a quick
;; way to select then.
;;
;; TODO: add goto-mark-in-all-buffers
;;
;; The functions names follows the code convection:
;; ([prefix-]action-target-object).
;;
;;; Code:
(require 'simple)
(eval-when-compile
(require 'cl-macs))
(defun parse-mark-line-to-string (pos)
"Return line string at position POS."
(save-excursion
(goto-char pos)
(forward-line 0)
(let ((line (car (split-string (thing-at-point 'line) "[\n\r]"))))
(remove-text-properties 0 (length line) '(read-only) line)
(if (string= "" line)
"<EMPTY LINE>"
line))))
(defun mark-ring-collection ()
"Return parsed mark ring candidates."
(cl-loop with marks = (if (mark t)
(cons (mark-marker) mark-ring)
mark-ring)
for mark in marks
with max-line-number = (line-number-at-pos (point-max))
with width = (length (number-to-string max-line-number))
for m = (format (concat "%" (number-to-string width) "d: %s")
(line-number-at-pos mark)
(parse-mark-line-to-string mark))
unless (and recip (assoc m recip))
collect (cons m mark) into recip
finally return recip))
;;;###autoload
(defun goto-mark ()
"Goto selected `mark' position."
(interactive)
(let ((collection (mark-ring-collection))
(choice nil))
(cond
;; no candidates, logs and leave
((not collection)
(message "Mark ring is empty"))
;; default, goto position (char in the buffer)
(t
;; select candidate from mark-ring-collection
(setq choice (completing-read "Goto: " collection nil t))
;; mark to char and finally go to it!
(goto-char (cdr (assoc choice collection)))))))
(provide 'lex-mark)
;;; lex-mark.el ends here
| true | ;;; lex-mark.el --- mark related functions -*- lexical-binding: t -*-
;;
;; Author: lambdart <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: lambdart
;; Version: 0.0.4 Alpha
;; URL: https://github.com/lambdart/lex
;; Keywords: mark mark-ring
;;
;; This file is NOT part of GNU Emacs.
;;
;;; MIT License
;;
;; Copyright (c) 2020 lambdart
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;
;;; Commentary:
;;
;; Each buffer has a special marker, which is designated “the mark”.
;; When a buffer is newly created, this marker exists but does not point
;; anywhere; this means that the mark doesn’t exist in that buffer yet.
;;
;; Add more functions/commands to facility the usage of the marks in a
;; interactive way, i.e, provides candidates/completions and a quick
;; way to select then.
;;
;; TODO: add goto-mark-in-all-buffers
;;
;; The functions names follows the code convection:
;; ([prefix-]action-target-object).
;;
;;; Code:
(require 'simple)
(eval-when-compile
(require 'cl-macs))
(defun parse-mark-line-to-string (pos)
"Return line string at position POS."
(save-excursion
(goto-char pos)
(forward-line 0)
(let ((line (car (split-string (thing-at-point 'line) "[\n\r]"))))
(remove-text-properties 0 (length line) '(read-only) line)
(if (string= "" line)
"<EMPTY LINE>"
line))))
(defun mark-ring-collection ()
"Return parsed mark ring candidates."
(cl-loop with marks = (if (mark t)
(cons (mark-marker) mark-ring)
mark-ring)
for mark in marks
with max-line-number = (line-number-at-pos (point-max))
with width = (length (number-to-string max-line-number))
for m = (format (concat "%" (number-to-string width) "d: %s")
(line-number-at-pos mark)
(parse-mark-line-to-string mark))
unless (and recip (assoc m recip))
collect (cons m mark) into recip
finally return recip))
;;;###autoload
(defun goto-mark ()
"Goto selected `mark' position."
(interactive)
(let ((collection (mark-ring-collection))
(choice nil))
(cond
;; no candidates, logs and leave
((not collection)
(message "Mark ring is empty"))
;; default, goto position (char in the buffer)
(t
;; select candidate from mark-ring-collection
(setq choice (completing-read "Goto: " collection nil t))
;; mark to char and finally go to it!
(goto-char (cdr (assoc choice collection)))))))
(provide 'lex-mark)
;;; lex-mark.el ends here
|
[
{
"context": "ST)\n;; Registration Number H14PRO021\n\n;; Author: Kenichi HANDA <handa@etl.go.jp>\n;; (according to ack.texi)\n;; K",
"end": 347,
"score": 0.9998031854629517,
"start": 334,
"tag": "NAME",
"value": "Kenichi HANDA"
},
{
"context": "ation Number H14PRO021\n\n;; Author: Kenichi HANDA <handa@etl.go.jp>\n;; (according to ack.texi)\n;; Keywords: mule, mu",
"end": 364,
"score": 0.9999301433563232,
"start": 349,
"tag": "EMAIL",
"value": "handa@etl.go.jp"
}
] | emacs-24.5/lisp/composite.el | emacslisp/emacs | 0 | ;;; composite.el --- support character composition
;; Copyright (C) 2001-2015 Free Software Foundation, Inc.
;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
;; 2008, 2009, 2010, 2011
;; National Institute of Advanced Industrial Science and Technology (AIST)
;; Registration Number H14PRO021
;; Author: Kenichi HANDA <handa@etl.go.jp>
;; (according to ack.texi)
;; Keywords: mule, multilingual, character composition
;; Package: emacs
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(defconst reference-point-alist
'((tl . 0) (tc . 1) (tr . 2)
(Bl . 3) (Bc . 4) (Br . 5)
(bl . 6) (bc . 7) (br . 8)
(cl . 9) (cc . 10) (cr . 11)
(top-left . 0) (top-center . 1) (top-right . 2)
(base-left . 3) (base-center . 4) (base-right . 5)
(bottom-left . 6) (bottom-center . 7) (bottom-right . 8)
(center-left . 9) (center-center . 10) (center-right . 11)
;; For backward compatibility...
(ml . 3) (mc . 10) (mr . 5)
(mid-left . 3) (mid-center . 10) (mid-right . 5))
"Alist of symbols vs integer codes of glyph reference points.
A glyph reference point symbol is to be used to specify a composition
rule in COMPONENTS argument to such functions as `compose-region'.
The meaning of glyph reference point codes is as follows:
0----1----2 <---- ascent 0:tl or top-left
| | 1:tc or top-center
| | 2:tr or top-right
| | 3:Bl or base-left 9:cl or center-left
9 10 11 <---- center 4:Bc or base-center 10:cc or center-center
| | 5:Br or base-right 11:cr or center-right
--3----4----5-- <-- baseline 6:bl or bottom-left
| | 7:bc or bottom-center
6----7----8 <---- descent 8:br or bottom-right
Glyph reference point symbols are to be used to specify a composition
rule of the form (GLOBAL-REF-POINT . NEW-REF-POINT), where
GLOBAL-REF-POINT is a reference point in the overall glyphs already
composed, and NEW-REF-POINT is a reference point in the new glyph to
be added.
For instance, if GLOBAL-REF-POINT is `br' (bottom-right) and
NEW-REF-POINT is `tc' (top-center), the overall glyph is updated as
follows (the point `*' corresponds to both reference points):
+-------+--+ <--- new ascent
| | |
| global| |
| glyph | |
-- | | |-- <--- baseline (doesn't change)
+----+--*--+
| | new |
| |glyph|
+----+-----+ <--- new descent
A composition rule may have the form (GLOBAL-REF-POINT
NEW-REF-POINT XOFF YOFF), where XOFF and YOFF specify how much
to shift NEW-REF-POINT from GLOBAL-REF-POINT. In this case, XOFF
and YOFF are integers in the range -100..100 representing the
shifting percentage against the font size.")
;;;###autoload
(defun encode-composition-rule (rule)
"Encode composition rule RULE into an integer value.
RULE is a cons of global and new reference point symbols
\(see `reference-point-alist')."
;; This must be compatible with C macro COMPOSITION_ENCODE_RULE
;; defined in composite.h.
(if (and (integerp rule) (< rule 144))
;; Already encoded.
rule
(if (consp rule)
(let ((gref (car rule))
(nref (cdr rule))
xoff yoff)
(if (consp nref) ; (GREF NREF XOFF YOFF)
(progn
(setq xoff (nth 1 nref)
yoff (nth 2 nref)
nref (car nref))
(or (and (>= xoff -100) (<= xoff 100)
(>= yoff -100) (<= yoff 100))
(error "Invalid composition rule: %s" rule))
(setq xoff (+ xoff 128) yoff (+ yoff 128)))
;; (GREF . NREF)
(setq xoff 0 yoff 0))
(or (integerp gref)
(setq gref (cdr (assq gref reference-point-alist))))
(or (integerp nref)
(setq nref (cdr (assq nref reference-point-alist))))
(or (and (>= gref 0) (< gref 12) (>= nref 0) (< nref 12))
(error "Invalid composition rule: %S" rule))
(logior (lsh xoff 16) (lsh yoff 8) (+ (* gref 12) nref)))
(error "Invalid composition rule: %S" rule))))
;; Decode encoded composition rule RULE-CODE. The value is a cons of
;; global and new reference point symbols.
;; This must be compatible with C macro COMPOSITION_DECODE_RULE
;; defined in composite.h.
(defun decode-composition-rule (rule-code)
(or (and (natnump rule-code) (< rule-code #x1000000))
(error "Invalid encoded composition rule: %S" rule-code))
(let ((xoff (lsh rule-code -16))
(yoff (logand (lsh rule-code -8) #xFF))
gref nref)
(setq rule-code (logand rule-code #xFF)
gref (car (rassq (/ rule-code 12) reference-point-alist))
nref (car (rassq (% rule-code 12) reference-point-alist)))
(or (and gref (symbolp gref) nref (symbolp nref))
(error "Invalid composition rule code: %S" rule-code))
(if (and (= xoff 0) (= yoff 0))
(cons gref nref)
(setq xoff (- xoff 128) yoff (- yoff 128))
(list gref xoff yoff nref))))
;; Encode composition rules in composition components COMPONENTS. The
;; value is a copy of COMPONENTS, where composition rules (cons of
;; global and new glyph reference point symbols) are replaced with
;; encoded composition rules. Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
(defun encode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(if (vectorp components)
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(encode-composition-rule (aref components i)))
(setq i (+ i 2))))
(let ((tail (cdr components)))
(while tail
(setcar tail
(encode-composition-rule (car tail)))
(setq tail (nthcdr 2 tail)))))
components)
;; Decode composition rule codes in composition components COMPONENTS.
;; The value is a copy of COMPONENTS, where composition rule codes are
;; replaced with composition rules (cons of global and new glyph
;; reference point symbols). Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
;; It is assumed that COMPONENTS is a vector and is for rule-base
;; composition, thus (2N+1)th elements are rule codes.
(defun decode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(decode-composition-rule (aref components i)))
(setq i (+ i 2))))
components)
(defun compose-region (start end &optional components modification-func)
"Compose characters in the current region.
Characters are composed relatively, i.e. composed by overstriking
or stacking depending on ascent, descent and other metrics of
glyphs.
For instance, if the region has three characters \"XYZ\", X is
regarded as BASE glyph, and Y is displayed:
(1) above BASE if Y's descent value is not positive
(2) below BASE if Y's ascent value is not positive
(3) on BASE (i.e. at the BASE position) otherwise
and Z is displayed with the same rule while regarding the whole
XY glyphs as BASE.
When called from a program, expects these four arguments.
First two arguments START and END are positions (integers or markers)
specifying the region.
Optional 3rd argument COMPONENTS, if non-nil, is a character, a string
or a vector or list of integers and rules.
If it is a character, it is an alternate character to display instead
of the text in the region.
If it is a string, the elements are alternate characters. In
this case, TAB element has a special meaning. If the first
character is TAB, the glyphs are displayed with left padding space
so that no pixel overlaps with the previous column. If the last
character is TAB, the glyphs are displayed with right padding
space so that no pixel overlaps with the following column.
If it is a vector or list, it is a sequence of alternate characters and
composition rules, where (2N)th elements are characters and (2N+1)th
elements are composition rules to specify how to compose (2N+2)th
elements with previously composed N glyphs.
A composition rule is a cons of global and new glyph reference point
symbols. See the documentation of `reference-point-alist' for more
details.
Optional 4th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(compose-region-internal start end components modification-func)
(restore-buffer-modified-p modified-p)))
(defun decompose-region (start end)
"Decompose text in the current region.
When called from a program, expects two arguments,
positions (integers or markers) specifying the region."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(remove-text-properties start end '(composition nil))
(restore-buffer-modified-p modified-p)))
(defun compose-string (string &optional start end components modification-func)
"Compose characters in string STRING.
The return value is STRING with the `composition' property put on all
the characters in it.
Optional 2nd and 3rd arguments START and END specify the range of
STRING to be composed. They default to the beginning and the end of
STRING respectively.
Optional 4th argument COMPONENTS, if non-nil, is a character or a
sequence (vector, list, or string) of integers. See the function
`compose-region' for more detail.
Optional 5th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(or start (setq start 0))
(or end (setq end (length string)))
(compose-string-internal string start end components modification-func)
string)
(defun decompose-string (string)
"Return STRING where `composition' property is removed."
(remove-text-properties 0 (length string) '(composition nil) string)
string)
(defun compose-chars (&rest args)
"Return a string from arguments in which all characters are composed.
For relative composition, arguments are characters.
For rule-based composition, Mth (where M is odd) arguments are
characters, and Nth (where N is even) arguments are composition rules.
A composition rule is a cons of glyph reference points of the form
\(GLOBAL-REF-POINT . NEW-REF-POINT). See the documentation of
`reference-point-alist' for more detail."
(let (str components)
(if (consp (car (cdr args)))
;; Rule-base composition.
(let ((tail (encode-composition-components args 'nocopy)))
(while tail
(setq str (cons (car tail) str))
(setq tail (nthcdr 2 tail)))
(setq str (concat (nreverse str))
components args))
;; Relative composition.
(setq str (concat args)))
(compose-string-internal str 0 (length str) components)))
(defun find-composition (pos &optional limit string detail-p)
"Return information about a composition at or near buffer position POS.
If the character at POS has `composition' property, the value is a list
\(FROM TO VALID-P).
FROM and TO specify the range of text that has the same `composition'
property, VALID-P is t if this composition is valid, and nil if not.
If there's no composition at POS, and the optional 2nd argument LIMIT
is non-nil, search for a composition toward the position given by LIMIT.
If no composition is found, return nil.
Optional 3rd argument STRING, if non-nil, is a string to look for a
composition in; nil means the current buffer.
If a valid composition is found and the optional 4th argument DETAIL-P
is non-nil, the return value is a list of the form
(FROM TO COMPONENTS RELATIVE-P MOD-FUNC WIDTH)
COMPONENTS is a vector of integers, the meaning depends on RELATIVE-P.
RELATIVE-P is t if the composition method is relative, else nil.
If RELATIVE-P is t, COMPONENTS is a vector of characters to be
composed. If RELATIVE-P is nil, COMPONENTS is a vector of characters
and composition rules as described in `compose-region'.
MOD-FUNC is a modification function of the composition.
WIDTH is a number of columns the composition occupies on the screen.
When Automatic Composition mode is on, this function also finds a
chunk of text that is automatically composed. If such a chunk is
found closer to POS than the position that has `composition'
property, the value is a list of FROM, TO, and a glyph-string
that specifies how the chunk is to be composed. See the function
`composition-get-gstring' for the format of the glyph-string."
(let ((result (find-composition-internal pos limit string detail-p)))
(if (and detail-p (> (length result) 3) (nth 2 result) (not (nth 3 result)))
;; This is a valid rule-base composition.
(decode-composition-components (nth 2 result) 'nocopy))
result))
(defun compose-chars-after (pos &optional limit object)
"Compose characters in current buffer after position POS.
It looks up the char-table `composition-function-table' (which
see) by a character at POS, and compose characters after POS
according to the contents of `composition-function-table'.
Optional 2nd arg LIMIT, if non-nil, limits characters to compose.
Optional 3rd arg OBJECT, if non-nil, is a string that contains the
text to compose. In that case, POS and LIMIT index into the string.
This function is the default value of `compose-chars-after-function'."
(let ((tail (aref composition-function-table (char-after pos)))
(font-obj (and (display-multi-font-p)
(and (not (stringp object))
(font-at pos (selected-window)))))
pattern func result)
(or limit
(setq limit (if (stringp object) (length object) (point-max))))
(when (and font-obj tail)
(save-match-data
(save-excursion
(while tail
(if (functionp (car tail))
(setq pattern nil func (car tail))
(setq pattern (car (car tail))
func (cdr (car tail))))
(goto-char pos)
(if pattern
(if (and (if (stringp object)
(eq (string-match pattern object) 0)
(looking-at pattern))
(<= (match-end 0) limit))
(setq result
(funcall func pos (match-end 0) font-obj object)))
(setq result (funcall func pos limit font-obj object)))
(if result (setq tail nil))))))
result))
(defun compose-last-chars (args)
"Compose last characters.
The argument is a parameterized event of the form
(compose-last-chars N COMPONENTS),
where N is the number of characters before point to compose,
COMPONENTS, if non-nil, is the same as the argument to `compose-region'
\(which see). If it is nil, `compose-chars-after' is called,
and that function finds a proper rule to compose the target characters.
This function is intended to be used from input methods.
The global keymap binds special event `compose-last-chars' to this
function. Input method may generate an event (compose-last-chars N COMPONENTS)
after a sequence of character events."
(interactive "e")
(let ((chars (nth 1 args)))
(if (and (numberp chars)
(>= (- (point) (point-min)) chars))
(if (nth 2 args)
(compose-region (- (point) chars) (point) (nth 2 args))
(compose-chars-after (- (point) chars) (point))))))
(global-set-key [compose-last-chars] 'compose-last-chars)
;;; Automatic character composition.
;; These macros must match with C macros LGSTRING_XXX and LGLYPH_XXX in font.h
(defsubst lgstring-header (gstring) (aref gstring 0))
(defsubst lgstring-set-header (gstring header) (aset gstring 0 header))
(defsubst lgstring-font (gstring) (aref (lgstring-header gstring) 0))
(defsubst lgstring-char (gstring i) (aref (lgstring-header gstring) (1+ i)))
(defsubst lgstring-char-len (gstring) (1- (length (lgstring-header gstring))))
(defsubst lgstring-shaped-p (gstring) (aref gstring 1))
(defsubst lgstring-set-id (gstring id) (aset gstring 1 id))
(defsubst lgstring-glyph (gstring i) (aref gstring (+ i 2)))
(defsubst lgstring-glyph-len (gstring) (- (length gstring) 2))
(defsubst lgstring-set-glyph (gstring i glyph) (aset gstring (+ i 2) glyph))
(defsubst lglyph-from (glyph) (aref glyph 0))
(defsubst lglyph-to (glyph) (aref glyph 1))
(defsubst lglyph-char (glyph) (aref glyph 2))
(defsubst lglyph-code (glyph) (aref glyph 3))
(defsubst lglyph-width (glyph) (aref glyph 4))
(defsubst lglyph-lbearing (glyph) (aref glyph 5))
(defsubst lglyph-rbearing (glyph) (aref glyph 6))
(defsubst lglyph-ascent (glyph) (aref glyph 7))
(defsubst lglyph-descent (glyph) (aref glyph 8))
(defsubst lglyph-adjustment (glyph) (aref glyph 9))
(defsubst lglyph-set-from-to (glyph from to)
(progn (aset glyph 0 from) (aset glyph 1 to)))
(defsubst lglyph-set-char (glyph char) (aset glyph 2 char))
(defsubst lglyph-set-code (glyph code) (aset glyph 3 code))
(defsubst lglyph-set-width (glyph width) (aset glyph 4 width))
(defsubst lglyph-set-adjustment (glyph &optional xoff yoff wadjust)
(aset glyph 9 (vector (or xoff 0) (or yoff 0) (or wadjust 0))))
(defsubst lglyph-copy (glyph) (copy-sequence glyph))
(defun lgstring-insert-glyph (gstring idx glyph)
(let ((nglyphs (lgstring-glyph-len gstring))
(i idx))
(while (and (< i nglyphs) (lgstring-glyph gstring i))
(setq i (1+ i)))
(if (= i nglyphs)
(setq gstring (vconcat gstring (vector glyph)))
(if (< (1+ i) nglyphs)
(lgstring-set-glyph gstring (1+ i) nil)))
(while (> i idx)
(lgstring-set-glyph gstring i (lgstring-glyph gstring (1- i)))
(setq i (1- i)))
(lgstring-set-glyph gstring i glyph)
gstring))
(defun compose-glyph-string (gstring from to)
(let ((glyph (lgstring-glyph gstring from))
from-pos to-pos)
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to))))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (and (< from to)
(setq glyph (lgstring-glyph gstring from)))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph)))))
(lglyph-set-adjustment glyph xoff 0 0))
(setq from (1+ from)))
gstring))
(defun compose-glyph-string-relative (gstring from to &optional gap)
(let ((font-object (lgstring-font gstring))
(glyph (lgstring-glyph gstring from))
from-pos to-pos
ascent descent)
(if gap
(setq gap (floor (* (font-get font-object :size) gap)))
(setq gap 0))
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to)))
ascent (lglyph-ascent glyph)
descent (lglyph-descent glyph))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (< from to)
(setq glyph (lgstring-glyph gstring from))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((this-ascent (lglyph-ascent glyph))
(this-descent (lglyph-descent glyph))
xoff yoff)
(setq xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph))))
(if (> this-ascent 0)
(if (< this-descent 0)
(setq yoff (- 0 ascent gap this-descent)
ascent (+ ascent gap this-ascent this-descent))
(setq yoff 0))
(setq yoff (+ descent gap this-ascent)
descent (+ descent gap this-ascent this-descent)))
(if (or (/= xoff 0) (/= yoff 0))
(lglyph-set-adjustment glyph xoff yoff 0)))
(setq from (1+ from)))
gstring))
(defun compose-gstring-for-graphic (gstring)
"Compose glyph-string GSTRING for graphic display.
Combining characters are composed with the preceding base
character. If the preceding character is not a base character,
each combining character is composed as a spacing character by
a padding space before and/or after the character.
All non-spacing characters have this function in
`composition-function-table' unless overwritten."
(let ((nchars (lgstring-char-len gstring))
(nglyphs (lgstring-glyph-len gstring))
(glyph (lgstring-glyph gstring 0)))
(cond
;; A non-spacing character not following a proper base character.
((= nchars 1)
(let ((lbearing (lglyph-lbearing glyph))
(rbearing (lglyph-rbearing glyph))
(width (lglyph-width glyph))
xoff)
(if (< lbearing 0)
(setq xoff (- lbearing))
(setq xoff 0 lbearing 0))
(if (< rbearing width)
(setq rbearing width))
(lglyph-set-adjustment glyph xoff 0 (- rbearing lbearing))
gstring))
;; This sequence doesn't start with a proper base character.
((memq (get-char-code-property (lgstring-char gstring 0)
'general-category)
'(Mn Mc Me Zs Zl Zp Cc Cf Cs))
nil)
;; A base character and the following non-spacing characters.
(t
(let ((gstr (font-shape-gstring gstring)))
(if (and gstr
(> (lglyph-to (lgstring-glyph gstr 0)) 0))
gstr
;; The shaper of the font couldn't shape the gstring.
;; Shape them according to canonical-combining-class.
(lgstring-set-id gstring nil)
(let* ((width (lglyph-width glyph))
(ascent (lglyph-ascent glyph))
(descent (lglyph-descent glyph))
(rbearing (lglyph-rbearing glyph))
(lbearing (lglyph-lbearing glyph))
(center (/ (+ lbearing rbearing) 2))
;; Artificial vertical gap between the glyphs.
(gap (round (* (font-get (lgstring-font gstring) :size) 0.1))))
(if (= gap 0)
;; Assure at least 1 pixel vertical gap.
(setq gap 1))
(dotimes (i nchars)
(setq glyph (lgstring-glyph gstring i))
(when (> i 0)
(let* ((class (get-char-code-property
(lglyph-char glyph) 'canonical-combining-class))
(lb (lglyph-lbearing glyph))
(rb (lglyph-rbearing glyph))
(as (lglyph-ascent glyph))
(de (lglyph-descent glyph))
(ce (/ (+ lb rb) 2))
(w (lglyph-width glyph))
xoff yoff)
(cond
((and class (>= class 200) (<= class 240))
(setq xoff 0 yoff 0)
(cond
((= class 200)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 202)
(if (> as 0) (setq as 0))
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 204)
(if (> as 0) (setq as 0))
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 208)
(setq xoff (- lbearing rb)))
((= class 210)
(setq xoff (- rbearing lb)))
((= class 212)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 214)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 216)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 218)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 220)
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 222)
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 224)
(setq xoff (- lbearing rb)))
((= class 226)
(setq xoff (- rbearing lb)))
((= class 228)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 230)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 232)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (+ ascent de) gap)))))
(lglyph-set-adjustment glyph (- xoff width) yoff)
(setq lb (+ lb xoff)
rb (+ lb xoff)
as (- as yoff)
de (+ de yoff)))
((and (= class 0)
(eq (get-char-code-property (lglyph-char glyph)
'general-category) 'Me))
;; Artificially laying out glyphs in an enclosing
;; mark is difficult. All we can do is to adjust
;; the x-offset and width of the base glyph to
;; align it at the center of the glyph of the
;; enclosing mark hoping that the enclosing mark
;; is big enough. We also have to adjust the
;; x-offset and width of the mark ifself properly
;; depending on how the glyph is designed.
;; (non-spacing or not). For instance, when we
;; have these glyphs:
;; X position |
;; base: <-*-> lbearing=0 rbearing=5 width=5
;; mark: <----------.> lb=-11 rb=2 w=0
;; we get a correct layout by moving them as this:
;; base: <-*-> XOFF=4 WAD=9
;; mark: <----------.> xoff=2 wad=4
;; we have moved the base to the left by 4-pixel
;; and make its width 9-pixel, then move the mark
;; to the left 2-pixel and make its width 4-pixel.
(let* (;; Adjustment for the base glyph
(XOFF (/ (- rb lb width) 2))
(WAD (+ width XOFF))
;; Adjustment for the enclosing mark glyph
(xoff (- (+ lb WAD)))
(wad (- rb lb WAD)))
(lglyph-set-adjustment glyph xoff 0 wad)
(setq glyph (lgstring-glyph gstring 0))
(lglyph-set-adjustment glyph XOFF 0 WAD))))
(if (< ascent as)
(setq ascent as))
(if (< descent de)
(setq descent de))))))
(let ((i 0))
(while (and (< i nglyphs) (setq glyph (lgstring-glyph gstring i)))
(lglyph-set-from-to glyph 0 (1- nchars))
(setq i (1+ i))))
gstring))))))
;; Allow for bootstrapping without uni-*.el.
(when unicode-category-table
(let ((elt `([,(purecopy "\\c.\\c^+") 1 compose-gstring-for-graphic]
[nil 0 compose-gstring-for-graphic])))
(map-char-table
#'(lambda (key val)
(if (memq val '(Mn Mc Me))
(set-char-table-range composition-function-table key elt)))
unicode-category-table)))
(defun compose-gstring-for-terminal (gstring)
"Compose glyph-string GSTRING for terminal display.
Non-spacing characters are composed with the preceding base
character. If the preceding character is not a base character,
each non-spacing character is composed as a spacing character by
prepending a space before it."
(let ((nglyphs (lgstring-glyph-len gstring))
(i 0)
(coding (lgstring-font gstring))
glyph)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (not (char-charset (lglyph-char glyph) coding))
(progn
;; As the terminal doesn't support this glyph, return a
;; gstring in which each glyph is its own grapheme-cluster
;; of width 1..
(setq i 0)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (< (lglyph-width glyph) 1)
(lglyph-set-width glyph 1))
(lglyph-set-from-to glyph i i)
(setq i (1+ i))))
(if (= (lglyph-width glyph) 0)
(if (eq (get-char-code-property (lglyph-char glyph)
'general-category)
'Cf)
(progn
;; Compose by replacing with a space.
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (1+ i)))
;; Compose by prepending a space.
(setq gstring (lgstring-insert-glyph gstring i
(lglyph-copy glyph))
nglyphs (lgstring-glyph-len gstring))
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (+ 2)))
(let ((from (lglyph-from glyph))
(to (lglyph-to glyph))
(j (1+ i)))
(while (and (< j nglyphs)
(setq glyph (lgstring-glyph gstring j))
(char-charset (lglyph-char glyph) coding)
(= (lglyph-width glyph) 0))
(setq to (lglyph-to glyph)
j (1+ j)))
(while (< i j)
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-from-to glyph from to)
(setq i (1+ i)))))))
gstring))
(defun auto-compose-chars (func from to font-object string)
"Compose the characters at FROM by FUNC.
FUNC is called with one argument GSTRING which is built for characters
in the region FROM (inclusive) and TO (exclusive).
If the character are composed on a graphic display, FONT-OBJECT
is a font to use. Otherwise, FONT-OBJECT is nil, and the function
`compose-gstring-for-terminal' is used instead of FUNC.
If STRING is non-nil, it is a string, and FROM and TO are indices
into the string. In that case, compose characters in the string.
The value is a gstring containing information for shaping the characters.
This function is the default value of `auto-composition-function' (which see)."
(let ((gstring (composition-get-gstring from to font-object string)))
(if (lgstring-shaped-p gstring)
gstring
(or (fontp font-object 'font-object)
(setq func 'compose-gstring-for-terminal))
(funcall func gstring))))
(put 'auto-composition-mode 'permanent-local t)
(make-variable-buffer-local 'auto-composition-function)
(setq-default auto-composition-function 'auto-compose-chars)
;;;###autoload
(define-minor-mode auto-composition-mode
"Toggle Auto Composition mode.
With a prefix argument ARG, enable Auto Composition mode if ARG
is positive, and disable it otherwise. If called from Lisp,
enable the mode if ARG is omitted or nil.
When Auto Composition mode is enabled, text characters are
automatically composed by functions registered in
`composition-function-table'.
You can use `global-auto-composition-mode' to turn on
Auto Composition mode in all buffers (this is the default)."
;; It's defined in C, this stops the d-m-m macro defining it again.
:variable auto-composition-mode)
;; It's not defined with DEFVAR_PER_BUFFER though.
(make-variable-buffer-local 'auto-composition-mode)
;;;###autoload
(define-minor-mode global-auto-composition-mode
"Toggle Auto Composition mode in all buffers.
With a prefix argument ARG, enable it if ARG is positive, and
disable it otherwise. If called from Lisp, enable it if ARG is
omitted or nil.
For more information on Auto Composition mode, see
`auto-composition-mode' ."
:variable (default-value 'auto-composition-mode))
(defalias 'toggle-auto-composition 'auto-composition-mode)
;;; composite.el ends here
| 7373 | ;;; composite.el --- support character composition
;; Copyright (C) 2001-2015 Free Software Foundation, Inc.
;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
;; 2008, 2009, 2010, 2011
;; National Institute of Advanced Industrial Science and Technology (AIST)
;; Registration Number H14PRO021
;; Author: <NAME> <<EMAIL>>
;; (according to ack.texi)
;; Keywords: mule, multilingual, character composition
;; Package: emacs
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(defconst reference-point-alist
'((tl . 0) (tc . 1) (tr . 2)
(Bl . 3) (Bc . 4) (Br . 5)
(bl . 6) (bc . 7) (br . 8)
(cl . 9) (cc . 10) (cr . 11)
(top-left . 0) (top-center . 1) (top-right . 2)
(base-left . 3) (base-center . 4) (base-right . 5)
(bottom-left . 6) (bottom-center . 7) (bottom-right . 8)
(center-left . 9) (center-center . 10) (center-right . 11)
;; For backward compatibility...
(ml . 3) (mc . 10) (mr . 5)
(mid-left . 3) (mid-center . 10) (mid-right . 5))
"Alist of symbols vs integer codes of glyph reference points.
A glyph reference point symbol is to be used to specify a composition
rule in COMPONENTS argument to such functions as `compose-region'.
The meaning of glyph reference point codes is as follows:
0----1----2 <---- ascent 0:tl or top-left
| | 1:tc or top-center
| | 2:tr or top-right
| | 3:Bl or base-left 9:cl or center-left
9 10 11 <---- center 4:Bc or base-center 10:cc or center-center
| | 5:Br or base-right 11:cr or center-right
--3----4----5-- <-- baseline 6:bl or bottom-left
| | 7:bc or bottom-center
6----7----8 <---- descent 8:br or bottom-right
Glyph reference point symbols are to be used to specify a composition
rule of the form (GLOBAL-REF-POINT . NEW-REF-POINT), where
GLOBAL-REF-POINT is a reference point in the overall glyphs already
composed, and NEW-REF-POINT is a reference point in the new glyph to
be added.
For instance, if GLOBAL-REF-POINT is `br' (bottom-right) and
NEW-REF-POINT is `tc' (top-center), the overall glyph is updated as
follows (the point `*' corresponds to both reference points):
+-------+--+ <--- new ascent
| | |
| global| |
| glyph | |
-- | | |-- <--- baseline (doesn't change)
+----+--*--+
| | new |
| |glyph|
+----+-----+ <--- new descent
A composition rule may have the form (GLOBAL-REF-POINT
NEW-REF-POINT XOFF YOFF), where XOFF and YOFF specify how much
to shift NEW-REF-POINT from GLOBAL-REF-POINT. In this case, XOFF
and YOFF are integers in the range -100..100 representing the
shifting percentage against the font size.")
;;;###autoload
(defun encode-composition-rule (rule)
"Encode composition rule RULE into an integer value.
RULE is a cons of global and new reference point symbols
\(see `reference-point-alist')."
;; This must be compatible with C macro COMPOSITION_ENCODE_RULE
;; defined in composite.h.
(if (and (integerp rule) (< rule 144))
;; Already encoded.
rule
(if (consp rule)
(let ((gref (car rule))
(nref (cdr rule))
xoff yoff)
(if (consp nref) ; (GREF NREF XOFF YOFF)
(progn
(setq xoff (nth 1 nref)
yoff (nth 2 nref)
nref (car nref))
(or (and (>= xoff -100) (<= xoff 100)
(>= yoff -100) (<= yoff 100))
(error "Invalid composition rule: %s" rule))
(setq xoff (+ xoff 128) yoff (+ yoff 128)))
;; (GREF . NREF)
(setq xoff 0 yoff 0))
(or (integerp gref)
(setq gref (cdr (assq gref reference-point-alist))))
(or (integerp nref)
(setq nref (cdr (assq nref reference-point-alist))))
(or (and (>= gref 0) (< gref 12) (>= nref 0) (< nref 12))
(error "Invalid composition rule: %S" rule))
(logior (lsh xoff 16) (lsh yoff 8) (+ (* gref 12) nref)))
(error "Invalid composition rule: %S" rule))))
;; Decode encoded composition rule RULE-CODE. The value is a cons of
;; global and new reference point symbols.
;; This must be compatible with C macro COMPOSITION_DECODE_RULE
;; defined in composite.h.
(defun decode-composition-rule (rule-code)
(or (and (natnump rule-code) (< rule-code #x1000000))
(error "Invalid encoded composition rule: %S" rule-code))
(let ((xoff (lsh rule-code -16))
(yoff (logand (lsh rule-code -8) #xFF))
gref nref)
(setq rule-code (logand rule-code #xFF)
gref (car (rassq (/ rule-code 12) reference-point-alist))
nref (car (rassq (% rule-code 12) reference-point-alist)))
(or (and gref (symbolp gref) nref (symbolp nref))
(error "Invalid composition rule code: %S" rule-code))
(if (and (= xoff 0) (= yoff 0))
(cons gref nref)
(setq xoff (- xoff 128) yoff (- yoff 128))
(list gref xoff yoff nref))))
;; Encode composition rules in composition components COMPONENTS. The
;; value is a copy of COMPONENTS, where composition rules (cons of
;; global and new glyph reference point symbols) are replaced with
;; encoded composition rules. Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
(defun encode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(if (vectorp components)
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(encode-composition-rule (aref components i)))
(setq i (+ i 2))))
(let ((tail (cdr components)))
(while tail
(setcar tail
(encode-composition-rule (car tail)))
(setq tail (nthcdr 2 tail)))))
components)
;; Decode composition rule codes in composition components COMPONENTS.
;; The value is a copy of COMPONENTS, where composition rule codes are
;; replaced with composition rules (cons of global and new glyph
;; reference point symbols). Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
;; It is assumed that COMPONENTS is a vector and is for rule-base
;; composition, thus (2N+1)th elements are rule codes.
(defun decode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(decode-composition-rule (aref components i)))
(setq i (+ i 2))))
components)
(defun compose-region (start end &optional components modification-func)
"Compose characters in the current region.
Characters are composed relatively, i.e. composed by overstriking
or stacking depending on ascent, descent and other metrics of
glyphs.
For instance, if the region has three characters \"XYZ\", X is
regarded as BASE glyph, and Y is displayed:
(1) above BASE if Y's descent value is not positive
(2) below BASE if Y's ascent value is not positive
(3) on BASE (i.e. at the BASE position) otherwise
and Z is displayed with the same rule while regarding the whole
XY glyphs as BASE.
When called from a program, expects these four arguments.
First two arguments START and END are positions (integers or markers)
specifying the region.
Optional 3rd argument COMPONENTS, if non-nil, is a character, a string
or a vector or list of integers and rules.
If it is a character, it is an alternate character to display instead
of the text in the region.
If it is a string, the elements are alternate characters. In
this case, TAB element has a special meaning. If the first
character is TAB, the glyphs are displayed with left padding space
so that no pixel overlaps with the previous column. If the last
character is TAB, the glyphs are displayed with right padding
space so that no pixel overlaps with the following column.
If it is a vector or list, it is a sequence of alternate characters and
composition rules, where (2N)th elements are characters and (2N+1)th
elements are composition rules to specify how to compose (2N+2)th
elements with previously composed N glyphs.
A composition rule is a cons of global and new glyph reference point
symbols. See the documentation of `reference-point-alist' for more
details.
Optional 4th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(compose-region-internal start end components modification-func)
(restore-buffer-modified-p modified-p)))
(defun decompose-region (start end)
"Decompose text in the current region.
When called from a program, expects two arguments,
positions (integers or markers) specifying the region."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(remove-text-properties start end '(composition nil))
(restore-buffer-modified-p modified-p)))
(defun compose-string (string &optional start end components modification-func)
"Compose characters in string STRING.
The return value is STRING with the `composition' property put on all
the characters in it.
Optional 2nd and 3rd arguments START and END specify the range of
STRING to be composed. They default to the beginning and the end of
STRING respectively.
Optional 4th argument COMPONENTS, if non-nil, is a character or a
sequence (vector, list, or string) of integers. See the function
`compose-region' for more detail.
Optional 5th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(or start (setq start 0))
(or end (setq end (length string)))
(compose-string-internal string start end components modification-func)
string)
(defun decompose-string (string)
"Return STRING where `composition' property is removed."
(remove-text-properties 0 (length string) '(composition nil) string)
string)
(defun compose-chars (&rest args)
"Return a string from arguments in which all characters are composed.
For relative composition, arguments are characters.
For rule-based composition, Mth (where M is odd) arguments are
characters, and Nth (where N is even) arguments are composition rules.
A composition rule is a cons of glyph reference points of the form
\(GLOBAL-REF-POINT . NEW-REF-POINT). See the documentation of
`reference-point-alist' for more detail."
(let (str components)
(if (consp (car (cdr args)))
;; Rule-base composition.
(let ((tail (encode-composition-components args 'nocopy)))
(while tail
(setq str (cons (car tail) str))
(setq tail (nthcdr 2 tail)))
(setq str (concat (nreverse str))
components args))
;; Relative composition.
(setq str (concat args)))
(compose-string-internal str 0 (length str) components)))
(defun find-composition (pos &optional limit string detail-p)
"Return information about a composition at or near buffer position POS.
If the character at POS has `composition' property, the value is a list
\(FROM TO VALID-P).
FROM and TO specify the range of text that has the same `composition'
property, VALID-P is t if this composition is valid, and nil if not.
If there's no composition at POS, and the optional 2nd argument LIMIT
is non-nil, search for a composition toward the position given by LIMIT.
If no composition is found, return nil.
Optional 3rd argument STRING, if non-nil, is a string to look for a
composition in; nil means the current buffer.
If a valid composition is found and the optional 4th argument DETAIL-P
is non-nil, the return value is a list of the form
(FROM TO COMPONENTS RELATIVE-P MOD-FUNC WIDTH)
COMPONENTS is a vector of integers, the meaning depends on RELATIVE-P.
RELATIVE-P is t if the composition method is relative, else nil.
If RELATIVE-P is t, COMPONENTS is a vector of characters to be
composed. If RELATIVE-P is nil, COMPONENTS is a vector of characters
and composition rules as described in `compose-region'.
MOD-FUNC is a modification function of the composition.
WIDTH is a number of columns the composition occupies on the screen.
When Automatic Composition mode is on, this function also finds a
chunk of text that is automatically composed. If such a chunk is
found closer to POS than the position that has `composition'
property, the value is a list of FROM, TO, and a glyph-string
that specifies how the chunk is to be composed. See the function
`composition-get-gstring' for the format of the glyph-string."
(let ((result (find-composition-internal pos limit string detail-p)))
(if (and detail-p (> (length result) 3) (nth 2 result) (not (nth 3 result)))
;; This is a valid rule-base composition.
(decode-composition-components (nth 2 result) 'nocopy))
result))
(defun compose-chars-after (pos &optional limit object)
"Compose characters in current buffer after position POS.
It looks up the char-table `composition-function-table' (which
see) by a character at POS, and compose characters after POS
according to the contents of `composition-function-table'.
Optional 2nd arg LIMIT, if non-nil, limits characters to compose.
Optional 3rd arg OBJECT, if non-nil, is a string that contains the
text to compose. In that case, POS and LIMIT index into the string.
This function is the default value of `compose-chars-after-function'."
(let ((tail (aref composition-function-table (char-after pos)))
(font-obj (and (display-multi-font-p)
(and (not (stringp object))
(font-at pos (selected-window)))))
pattern func result)
(or limit
(setq limit (if (stringp object) (length object) (point-max))))
(when (and font-obj tail)
(save-match-data
(save-excursion
(while tail
(if (functionp (car tail))
(setq pattern nil func (car tail))
(setq pattern (car (car tail))
func (cdr (car tail))))
(goto-char pos)
(if pattern
(if (and (if (stringp object)
(eq (string-match pattern object) 0)
(looking-at pattern))
(<= (match-end 0) limit))
(setq result
(funcall func pos (match-end 0) font-obj object)))
(setq result (funcall func pos limit font-obj object)))
(if result (setq tail nil))))))
result))
(defun compose-last-chars (args)
"Compose last characters.
The argument is a parameterized event of the form
(compose-last-chars N COMPONENTS),
where N is the number of characters before point to compose,
COMPONENTS, if non-nil, is the same as the argument to `compose-region'
\(which see). If it is nil, `compose-chars-after' is called,
and that function finds a proper rule to compose the target characters.
This function is intended to be used from input methods.
The global keymap binds special event `compose-last-chars' to this
function. Input method may generate an event (compose-last-chars N COMPONENTS)
after a sequence of character events."
(interactive "e")
(let ((chars (nth 1 args)))
(if (and (numberp chars)
(>= (- (point) (point-min)) chars))
(if (nth 2 args)
(compose-region (- (point) chars) (point) (nth 2 args))
(compose-chars-after (- (point) chars) (point))))))
(global-set-key [compose-last-chars] 'compose-last-chars)
;;; Automatic character composition.
;; These macros must match with C macros LGSTRING_XXX and LGLYPH_XXX in font.h
(defsubst lgstring-header (gstring) (aref gstring 0))
(defsubst lgstring-set-header (gstring header) (aset gstring 0 header))
(defsubst lgstring-font (gstring) (aref (lgstring-header gstring) 0))
(defsubst lgstring-char (gstring i) (aref (lgstring-header gstring) (1+ i)))
(defsubst lgstring-char-len (gstring) (1- (length (lgstring-header gstring))))
(defsubst lgstring-shaped-p (gstring) (aref gstring 1))
(defsubst lgstring-set-id (gstring id) (aset gstring 1 id))
(defsubst lgstring-glyph (gstring i) (aref gstring (+ i 2)))
(defsubst lgstring-glyph-len (gstring) (- (length gstring) 2))
(defsubst lgstring-set-glyph (gstring i glyph) (aset gstring (+ i 2) glyph))
(defsubst lglyph-from (glyph) (aref glyph 0))
(defsubst lglyph-to (glyph) (aref glyph 1))
(defsubst lglyph-char (glyph) (aref glyph 2))
(defsubst lglyph-code (glyph) (aref glyph 3))
(defsubst lglyph-width (glyph) (aref glyph 4))
(defsubst lglyph-lbearing (glyph) (aref glyph 5))
(defsubst lglyph-rbearing (glyph) (aref glyph 6))
(defsubst lglyph-ascent (glyph) (aref glyph 7))
(defsubst lglyph-descent (glyph) (aref glyph 8))
(defsubst lglyph-adjustment (glyph) (aref glyph 9))
(defsubst lglyph-set-from-to (glyph from to)
(progn (aset glyph 0 from) (aset glyph 1 to)))
(defsubst lglyph-set-char (glyph char) (aset glyph 2 char))
(defsubst lglyph-set-code (glyph code) (aset glyph 3 code))
(defsubst lglyph-set-width (glyph width) (aset glyph 4 width))
(defsubst lglyph-set-adjustment (glyph &optional xoff yoff wadjust)
(aset glyph 9 (vector (or xoff 0) (or yoff 0) (or wadjust 0))))
(defsubst lglyph-copy (glyph) (copy-sequence glyph))
(defun lgstring-insert-glyph (gstring idx glyph)
(let ((nglyphs (lgstring-glyph-len gstring))
(i idx))
(while (and (< i nglyphs) (lgstring-glyph gstring i))
(setq i (1+ i)))
(if (= i nglyphs)
(setq gstring (vconcat gstring (vector glyph)))
(if (< (1+ i) nglyphs)
(lgstring-set-glyph gstring (1+ i) nil)))
(while (> i idx)
(lgstring-set-glyph gstring i (lgstring-glyph gstring (1- i)))
(setq i (1- i)))
(lgstring-set-glyph gstring i glyph)
gstring))
(defun compose-glyph-string (gstring from to)
(let ((glyph (lgstring-glyph gstring from))
from-pos to-pos)
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to))))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (and (< from to)
(setq glyph (lgstring-glyph gstring from)))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph)))))
(lglyph-set-adjustment glyph xoff 0 0))
(setq from (1+ from)))
gstring))
(defun compose-glyph-string-relative (gstring from to &optional gap)
(let ((font-object (lgstring-font gstring))
(glyph (lgstring-glyph gstring from))
from-pos to-pos
ascent descent)
(if gap
(setq gap (floor (* (font-get font-object :size) gap)))
(setq gap 0))
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to)))
ascent (lglyph-ascent glyph)
descent (lglyph-descent glyph))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (< from to)
(setq glyph (lgstring-glyph gstring from))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((this-ascent (lglyph-ascent glyph))
(this-descent (lglyph-descent glyph))
xoff yoff)
(setq xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph))))
(if (> this-ascent 0)
(if (< this-descent 0)
(setq yoff (- 0 ascent gap this-descent)
ascent (+ ascent gap this-ascent this-descent))
(setq yoff 0))
(setq yoff (+ descent gap this-ascent)
descent (+ descent gap this-ascent this-descent)))
(if (or (/= xoff 0) (/= yoff 0))
(lglyph-set-adjustment glyph xoff yoff 0)))
(setq from (1+ from)))
gstring))
(defun compose-gstring-for-graphic (gstring)
"Compose glyph-string GSTRING for graphic display.
Combining characters are composed with the preceding base
character. If the preceding character is not a base character,
each combining character is composed as a spacing character by
a padding space before and/or after the character.
All non-spacing characters have this function in
`composition-function-table' unless overwritten."
(let ((nchars (lgstring-char-len gstring))
(nglyphs (lgstring-glyph-len gstring))
(glyph (lgstring-glyph gstring 0)))
(cond
;; A non-spacing character not following a proper base character.
((= nchars 1)
(let ((lbearing (lglyph-lbearing glyph))
(rbearing (lglyph-rbearing glyph))
(width (lglyph-width glyph))
xoff)
(if (< lbearing 0)
(setq xoff (- lbearing))
(setq xoff 0 lbearing 0))
(if (< rbearing width)
(setq rbearing width))
(lglyph-set-adjustment glyph xoff 0 (- rbearing lbearing))
gstring))
;; This sequence doesn't start with a proper base character.
((memq (get-char-code-property (lgstring-char gstring 0)
'general-category)
'(Mn Mc Me Zs Zl Zp Cc Cf Cs))
nil)
;; A base character and the following non-spacing characters.
(t
(let ((gstr (font-shape-gstring gstring)))
(if (and gstr
(> (lglyph-to (lgstring-glyph gstr 0)) 0))
gstr
;; The shaper of the font couldn't shape the gstring.
;; Shape them according to canonical-combining-class.
(lgstring-set-id gstring nil)
(let* ((width (lglyph-width glyph))
(ascent (lglyph-ascent glyph))
(descent (lglyph-descent glyph))
(rbearing (lglyph-rbearing glyph))
(lbearing (lglyph-lbearing glyph))
(center (/ (+ lbearing rbearing) 2))
;; Artificial vertical gap between the glyphs.
(gap (round (* (font-get (lgstring-font gstring) :size) 0.1))))
(if (= gap 0)
;; Assure at least 1 pixel vertical gap.
(setq gap 1))
(dotimes (i nchars)
(setq glyph (lgstring-glyph gstring i))
(when (> i 0)
(let* ((class (get-char-code-property
(lglyph-char glyph) 'canonical-combining-class))
(lb (lglyph-lbearing glyph))
(rb (lglyph-rbearing glyph))
(as (lglyph-ascent glyph))
(de (lglyph-descent glyph))
(ce (/ (+ lb rb) 2))
(w (lglyph-width glyph))
xoff yoff)
(cond
((and class (>= class 200) (<= class 240))
(setq xoff 0 yoff 0)
(cond
((= class 200)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 202)
(if (> as 0) (setq as 0))
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 204)
(if (> as 0) (setq as 0))
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 208)
(setq xoff (- lbearing rb)))
((= class 210)
(setq xoff (- rbearing lb)))
((= class 212)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 214)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 216)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 218)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 220)
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 222)
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 224)
(setq xoff (- lbearing rb)))
((= class 226)
(setq xoff (- rbearing lb)))
((= class 228)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 230)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 232)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (+ ascent de) gap)))))
(lglyph-set-adjustment glyph (- xoff width) yoff)
(setq lb (+ lb xoff)
rb (+ lb xoff)
as (- as yoff)
de (+ de yoff)))
((and (= class 0)
(eq (get-char-code-property (lglyph-char glyph)
'general-category) 'Me))
;; Artificially laying out glyphs in an enclosing
;; mark is difficult. All we can do is to adjust
;; the x-offset and width of the base glyph to
;; align it at the center of the glyph of the
;; enclosing mark hoping that the enclosing mark
;; is big enough. We also have to adjust the
;; x-offset and width of the mark ifself properly
;; depending on how the glyph is designed.
;; (non-spacing or not). For instance, when we
;; have these glyphs:
;; X position |
;; base: <-*-> lbearing=0 rbearing=5 width=5
;; mark: <----------.> lb=-11 rb=2 w=0
;; we get a correct layout by moving them as this:
;; base: <-*-> XOFF=4 WAD=9
;; mark: <----------.> xoff=2 wad=4
;; we have moved the base to the left by 4-pixel
;; and make its width 9-pixel, then move the mark
;; to the left 2-pixel and make its width 4-pixel.
(let* (;; Adjustment for the base glyph
(XOFF (/ (- rb lb width) 2))
(WAD (+ width XOFF))
;; Adjustment for the enclosing mark glyph
(xoff (- (+ lb WAD)))
(wad (- rb lb WAD)))
(lglyph-set-adjustment glyph xoff 0 wad)
(setq glyph (lgstring-glyph gstring 0))
(lglyph-set-adjustment glyph XOFF 0 WAD))))
(if (< ascent as)
(setq ascent as))
(if (< descent de)
(setq descent de))))))
(let ((i 0))
(while (and (< i nglyphs) (setq glyph (lgstring-glyph gstring i)))
(lglyph-set-from-to glyph 0 (1- nchars))
(setq i (1+ i))))
gstring))))))
;; Allow for bootstrapping without uni-*.el.
(when unicode-category-table
(let ((elt `([,(purecopy "\\c.\\c^+") 1 compose-gstring-for-graphic]
[nil 0 compose-gstring-for-graphic])))
(map-char-table
#'(lambda (key val)
(if (memq val '(Mn Mc Me))
(set-char-table-range composition-function-table key elt)))
unicode-category-table)))
(defun compose-gstring-for-terminal (gstring)
"Compose glyph-string GSTRING for terminal display.
Non-spacing characters are composed with the preceding base
character. If the preceding character is not a base character,
each non-spacing character is composed as a spacing character by
prepending a space before it."
(let ((nglyphs (lgstring-glyph-len gstring))
(i 0)
(coding (lgstring-font gstring))
glyph)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (not (char-charset (lglyph-char glyph) coding))
(progn
;; As the terminal doesn't support this glyph, return a
;; gstring in which each glyph is its own grapheme-cluster
;; of width 1..
(setq i 0)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (< (lglyph-width glyph) 1)
(lglyph-set-width glyph 1))
(lglyph-set-from-to glyph i i)
(setq i (1+ i))))
(if (= (lglyph-width glyph) 0)
(if (eq (get-char-code-property (lglyph-char glyph)
'general-category)
'Cf)
(progn
;; Compose by replacing with a space.
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (1+ i)))
;; Compose by prepending a space.
(setq gstring (lgstring-insert-glyph gstring i
(lglyph-copy glyph))
nglyphs (lgstring-glyph-len gstring))
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (+ 2)))
(let ((from (lglyph-from glyph))
(to (lglyph-to glyph))
(j (1+ i)))
(while (and (< j nglyphs)
(setq glyph (lgstring-glyph gstring j))
(char-charset (lglyph-char glyph) coding)
(= (lglyph-width glyph) 0))
(setq to (lglyph-to glyph)
j (1+ j)))
(while (< i j)
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-from-to glyph from to)
(setq i (1+ i)))))))
gstring))
(defun auto-compose-chars (func from to font-object string)
"Compose the characters at FROM by FUNC.
FUNC is called with one argument GSTRING which is built for characters
in the region FROM (inclusive) and TO (exclusive).
If the character are composed on a graphic display, FONT-OBJECT
is a font to use. Otherwise, FONT-OBJECT is nil, and the function
`compose-gstring-for-terminal' is used instead of FUNC.
If STRING is non-nil, it is a string, and FROM and TO are indices
into the string. In that case, compose characters in the string.
The value is a gstring containing information for shaping the characters.
This function is the default value of `auto-composition-function' (which see)."
(let ((gstring (composition-get-gstring from to font-object string)))
(if (lgstring-shaped-p gstring)
gstring
(or (fontp font-object 'font-object)
(setq func 'compose-gstring-for-terminal))
(funcall func gstring))))
(put 'auto-composition-mode 'permanent-local t)
(make-variable-buffer-local 'auto-composition-function)
(setq-default auto-composition-function 'auto-compose-chars)
;;;###autoload
(define-minor-mode auto-composition-mode
"Toggle Auto Composition mode.
With a prefix argument ARG, enable Auto Composition mode if ARG
is positive, and disable it otherwise. If called from Lisp,
enable the mode if ARG is omitted or nil.
When Auto Composition mode is enabled, text characters are
automatically composed by functions registered in
`composition-function-table'.
You can use `global-auto-composition-mode' to turn on
Auto Composition mode in all buffers (this is the default)."
;; It's defined in C, this stops the d-m-m macro defining it again.
:variable auto-composition-mode)
;; It's not defined with DEFVAR_PER_BUFFER though.
(make-variable-buffer-local 'auto-composition-mode)
;;;###autoload
(define-minor-mode global-auto-composition-mode
"Toggle Auto Composition mode in all buffers.
With a prefix argument ARG, enable it if ARG is positive, and
disable it otherwise. If called from Lisp, enable it if ARG is
omitted or nil.
For more information on Auto Composition mode, see
`auto-composition-mode' ."
:variable (default-value 'auto-composition-mode))
(defalias 'toggle-auto-composition 'auto-composition-mode)
;;; composite.el ends here
| true | ;;; composite.el --- support character composition
;; Copyright (C) 2001-2015 Free Software Foundation, Inc.
;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
;; 2008, 2009, 2010, 2011
;; National Institute of Advanced Industrial Science and Technology (AIST)
;; Registration Number H14PRO021
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; (according to ack.texi)
;; Keywords: mule, multilingual, character composition
;; Package: emacs
;; 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(defconst reference-point-alist
'((tl . 0) (tc . 1) (tr . 2)
(Bl . 3) (Bc . 4) (Br . 5)
(bl . 6) (bc . 7) (br . 8)
(cl . 9) (cc . 10) (cr . 11)
(top-left . 0) (top-center . 1) (top-right . 2)
(base-left . 3) (base-center . 4) (base-right . 5)
(bottom-left . 6) (bottom-center . 7) (bottom-right . 8)
(center-left . 9) (center-center . 10) (center-right . 11)
;; For backward compatibility...
(ml . 3) (mc . 10) (mr . 5)
(mid-left . 3) (mid-center . 10) (mid-right . 5))
"Alist of symbols vs integer codes of glyph reference points.
A glyph reference point symbol is to be used to specify a composition
rule in COMPONENTS argument to such functions as `compose-region'.
The meaning of glyph reference point codes is as follows:
0----1----2 <---- ascent 0:tl or top-left
| | 1:tc or top-center
| | 2:tr or top-right
| | 3:Bl or base-left 9:cl or center-left
9 10 11 <---- center 4:Bc or base-center 10:cc or center-center
| | 5:Br or base-right 11:cr or center-right
--3----4----5-- <-- baseline 6:bl or bottom-left
| | 7:bc or bottom-center
6----7----8 <---- descent 8:br or bottom-right
Glyph reference point symbols are to be used to specify a composition
rule of the form (GLOBAL-REF-POINT . NEW-REF-POINT), where
GLOBAL-REF-POINT is a reference point in the overall glyphs already
composed, and NEW-REF-POINT is a reference point in the new glyph to
be added.
For instance, if GLOBAL-REF-POINT is `br' (bottom-right) and
NEW-REF-POINT is `tc' (top-center), the overall glyph is updated as
follows (the point `*' corresponds to both reference points):
+-------+--+ <--- new ascent
| | |
| global| |
| glyph | |
-- | | |-- <--- baseline (doesn't change)
+----+--*--+
| | new |
| |glyph|
+----+-----+ <--- new descent
A composition rule may have the form (GLOBAL-REF-POINT
NEW-REF-POINT XOFF YOFF), where XOFF and YOFF specify how much
to shift NEW-REF-POINT from GLOBAL-REF-POINT. In this case, XOFF
and YOFF are integers in the range -100..100 representing the
shifting percentage against the font size.")
;;;###autoload
(defun encode-composition-rule (rule)
"Encode composition rule RULE into an integer value.
RULE is a cons of global and new reference point symbols
\(see `reference-point-alist')."
;; This must be compatible with C macro COMPOSITION_ENCODE_RULE
;; defined in composite.h.
(if (and (integerp rule) (< rule 144))
;; Already encoded.
rule
(if (consp rule)
(let ((gref (car rule))
(nref (cdr rule))
xoff yoff)
(if (consp nref) ; (GREF NREF XOFF YOFF)
(progn
(setq xoff (nth 1 nref)
yoff (nth 2 nref)
nref (car nref))
(or (and (>= xoff -100) (<= xoff 100)
(>= yoff -100) (<= yoff 100))
(error "Invalid composition rule: %s" rule))
(setq xoff (+ xoff 128) yoff (+ yoff 128)))
;; (GREF . NREF)
(setq xoff 0 yoff 0))
(or (integerp gref)
(setq gref (cdr (assq gref reference-point-alist))))
(or (integerp nref)
(setq nref (cdr (assq nref reference-point-alist))))
(or (and (>= gref 0) (< gref 12) (>= nref 0) (< nref 12))
(error "Invalid composition rule: %S" rule))
(logior (lsh xoff 16) (lsh yoff 8) (+ (* gref 12) nref)))
(error "Invalid composition rule: %S" rule))))
;; Decode encoded composition rule RULE-CODE. The value is a cons of
;; global and new reference point symbols.
;; This must be compatible with C macro COMPOSITION_DECODE_RULE
;; defined in composite.h.
(defun decode-composition-rule (rule-code)
(or (and (natnump rule-code) (< rule-code #x1000000))
(error "Invalid encoded composition rule: %S" rule-code))
(let ((xoff (lsh rule-code -16))
(yoff (logand (lsh rule-code -8) #xFF))
gref nref)
(setq rule-code (logand rule-code #xFF)
gref (car (rassq (/ rule-code 12) reference-point-alist))
nref (car (rassq (% rule-code 12) reference-point-alist)))
(or (and gref (symbolp gref) nref (symbolp nref))
(error "Invalid composition rule code: %S" rule-code))
(if (and (= xoff 0) (= yoff 0))
(cons gref nref)
(setq xoff (- xoff 128) yoff (- yoff 128))
(list gref xoff yoff nref))))
;; Encode composition rules in composition components COMPONENTS. The
;; value is a copy of COMPONENTS, where composition rules (cons of
;; global and new glyph reference point symbols) are replaced with
;; encoded composition rules. Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
(defun encode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(if (vectorp components)
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(encode-composition-rule (aref components i)))
(setq i (+ i 2))))
(let ((tail (cdr components)))
(while tail
(setcar tail
(encode-composition-rule (car tail)))
(setq tail (nthcdr 2 tail)))))
components)
;; Decode composition rule codes in composition components COMPONENTS.
;; The value is a copy of COMPONENTS, where composition rule codes are
;; replaced with composition rules (cons of global and new glyph
;; reference point symbols). Optional 2nd argument NOCOPY non-nil
;; means don't make a copy but modify COMPONENTS directly.
;; It is assumed that COMPONENTS is a vector and is for rule-base
;; composition, thus (2N+1)th elements are rule codes.
(defun decode-composition-components (components &optional nocopy)
(or nocopy
(setq components (copy-sequence components)))
(let ((len (length components))
(i 1))
(while (< i len)
(aset components i
(decode-composition-rule (aref components i)))
(setq i (+ i 2))))
components)
(defun compose-region (start end &optional components modification-func)
"Compose characters in the current region.
Characters are composed relatively, i.e. composed by overstriking
or stacking depending on ascent, descent and other metrics of
glyphs.
For instance, if the region has three characters \"XYZ\", X is
regarded as BASE glyph, and Y is displayed:
(1) above BASE if Y's descent value is not positive
(2) below BASE if Y's ascent value is not positive
(3) on BASE (i.e. at the BASE position) otherwise
and Z is displayed with the same rule while regarding the whole
XY glyphs as BASE.
When called from a program, expects these four arguments.
First two arguments START and END are positions (integers or markers)
specifying the region.
Optional 3rd argument COMPONENTS, if non-nil, is a character, a string
or a vector or list of integers and rules.
If it is a character, it is an alternate character to display instead
of the text in the region.
If it is a string, the elements are alternate characters. In
this case, TAB element has a special meaning. If the first
character is TAB, the glyphs are displayed with left padding space
so that no pixel overlaps with the previous column. If the last
character is TAB, the glyphs are displayed with right padding
space so that no pixel overlaps with the following column.
If it is a vector or list, it is a sequence of alternate characters and
composition rules, where (2N)th elements are characters and (2N+1)th
elements are composition rules to specify how to compose (2N+2)th
elements with previously composed N glyphs.
A composition rule is a cons of global and new glyph reference point
symbols. See the documentation of `reference-point-alist' for more
details.
Optional 4th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(compose-region-internal start end components modification-func)
(restore-buffer-modified-p modified-p)))
(defun decompose-region (start end)
"Decompose text in the current region.
When called from a program, expects two arguments,
positions (integers or markers) specifying the region."
(interactive "r")
(let ((modified-p (buffer-modified-p))
(inhibit-read-only t))
(remove-text-properties start end '(composition nil))
(restore-buffer-modified-p modified-p)))
(defun compose-string (string &optional start end components modification-func)
"Compose characters in string STRING.
The return value is STRING with the `composition' property put on all
the characters in it.
Optional 2nd and 3rd arguments START and END specify the range of
STRING to be composed. They default to the beginning and the end of
STRING respectively.
Optional 4th argument COMPONENTS, if non-nil, is a character or a
sequence (vector, list, or string) of integers. See the function
`compose-region' for more detail.
Optional 5th argument MODIFICATION-FUNC is a function to call to
adjust the composition when it gets invalid because of a change of
text in the composition."
(if (or (vectorp components) (listp components))
(setq components (encode-composition-components components)))
(or start (setq start 0))
(or end (setq end (length string)))
(compose-string-internal string start end components modification-func)
string)
(defun decompose-string (string)
"Return STRING where `composition' property is removed."
(remove-text-properties 0 (length string) '(composition nil) string)
string)
(defun compose-chars (&rest args)
"Return a string from arguments in which all characters are composed.
For relative composition, arguments are characters.
For rule-based composition, Mth (where M is odd) arguments are
characters, and Nth (where N is even) arguments are composition rules.
A composition rule is a cons of glyph reference points of the form
\(GLOBAL-REF-POINT . NEW-REF-POINT). See the documentation of
`reference-point-alist' for more detail."
(let (str components)
(if (consp (car (cdr args)))
;; Rule-base composition.
(let ((tail (encode-composition-components args 'nocopy)))
(while tail
(setq str (cons (car tail) str))
(setq tail (nthcdr 2 tail)))
(setq str (concat (nreverse str))
components args))
;; Relative composition.
(setq str (concat args)))
(compose-string-internal str 0 (length str) components)))
(defun find-composition (pos &optional limit string detail-p)
"Return information about a composition at or near buffer position POS.
If the character at POS has `composition' property, the value is a list
\(FROM TO VALID-P).
FROM and TO specify the range of text that has the same `composition'
property, VALID-P is t if this composition is valid, and nil if not.
If there's no composition at POS, and the optional 2nd argument LIMIT
is non-nil, search for a composition toward the position given by LIMIT.
If no composition is found, return nil.
Optional 3rd argument STRING, if non-nil, is a string to look for a
composition in; nil means the current buffer.
If a valid composition is found and the optional 4th argument DETAIL-P
is non-nil, the return value is a list of the form
(FROM TO COMPONENTS RELATIVE-P MOD-FUNC WIDTH)
COMPONENTS is a vector of integers, the meaning depends on RELATIVE-P.
RELATIVE-P is t if the composition method is relative, else nil.
If RELATIVE-P is t, COMPONENTS is a vector of characters to be
composed. If RELATIVE-P is nil, COMPONENTS is a vector of characters
and composition rules as described in `compose-region'.
MOD-FUNC is a modification function of the composition.
WIDTH is a number of columns the composition occupies on the screen.
When Automatic Composition mode is on, this function also finds a
chunk of text that is automatically composed. If such a chunk is
found closer to POS than the position that has `composition'
property, the value is a list of FROM, TO, and a glyph-string
that specifies how the chunk is to be composed. See the function
`composition-get-gstring' for the format of the glyph-string."
(let ((result (find-composition-internal pos limit string detail-p)))
(if (and detail-p (> (length result) 3) (nth 2 result) (not (nth 3 result)))
;; This is a valid rule-base composition.
(decode-composition-components (nth 2 result) 'nocopy))
result))
(defun compose-chars-after (pos &optional limit object)
"Compose characters in current buffer after position POS.
It looks up the char-table `composition-function-table' (which
see) by a character at POS, and compose characters after POS
according to the contents of `composition-function-table'.
Optional 2nd arg LIMIT, if non-nil, limits characters to compose.
Optional 3rd arg OBJECT, if non-nil, is a string that contains the
text to compose. In that case, POS and LIMIT index into the string.
This function is the default value of `compose-chars-after-function'."
(let ((tail (aref composition-function-table (char-after pos)))
(font-obj (and (display-multi-font-p)
(and (not (stringp object))
(font-at pos (selected-window)))))
pattern func result)
(or limit
(setq limit (if (stringp object) (length object) (point-max))))
(when (and font-obj tail)
(save-match-data
(save-excursion
(while tail
(if (functionp (car tail))
(setq pattern nil func (car tail))
(setq pattern (car (car tail))
func (cdr (car tail))))
(goto-char pos)
(if pattern
(if (and (if (stringp object)
(eq (string-match pattern object) 0)
(looking-at pattern))
(<= (match-end 0) limit))
(setq result
(funcall func pos (match-end 0) font-obj object)))
(setq result (funcall func pos limit font-obj object)))
(if result (setq tail nil))))))
result))
(defun compose-last-chars (args)
"Compose last characters.
The argument is a parameterized event of the form
(compose-last-chars N COMPONENTS),
where N is the number of characters before point to compose,
COMPONENTS, if non-nil, is the same as the argument to `compose-region'
\(which see). If it is nil, `compose-chars-after' is called,
and that function finds a proper rule to compose the target characters.
This function is intended to be used from input methods.
The global keymap binds special event `compose-last-chars' to this
function. Input method may generate an event (compose-last-chars N COMPONENTS)
after a sequence of character events."
(interactive "e")
(let ((chars (nth 1 args)))
(if (and (numberp chars)
(>= (- (point) (point-min)) chars))
(if (nth 2 args)
(compose-region (- (point) chars) (point) (nth 2 args))
(compose-chars-after (- (point) chars) (point))))))
(global-set-key [compose-last-chars] 'compose-last-chars)
;;; Automatic character composition.
;; These macros must match with C macros LGSTRING_XXX and LGLYPH_XXX in font.h
(defsubst lgstring-header (gstring) (aref gstring 0))
(defsubst lgstring-set-header (gstring header) (aset gstring 0 header))
(defsubst lgstring-font (gstring) (aref (lgstring-header gstring) 0))
(defsubst lgstring-char (gstring i) (aref (lgstring-header gstring) (1+ i)))
(defsubst lgstring-char-len (gstring) (1- (length (lgstring-header gstring))))
(defsubst lgstring-shaped-p (gstring) (aref gstring 1))
(defsubst lgstring-set-id (gstring id) (aset gstring 1 id))
(defsubst lgstring-glyph (gstring i) (aref gstring (+ i 2)))
(defsubst lgstring-glyph-len (gstring) (- (length gstring) 2))
(defsubst lgstring-set-glyph (gstring i glyph) (aset gstring (+ i 2) glyph))
(defsubst lglyph-from (glyph) (aref glyph 0))
(defsubst lglyph-to (glyph) (aref glyph 1))
(defsubst lglyph-char (glyph) (aref glyph 2))
(defsubst lglyph-code (glyph) (aref glyph 3))
(defsubst lglyph-width (glyph) (aref glyph 4))
(defsubst lglyph-lbearing (glyph) (aref glyph 5))
(defsubst lglyph-rbearing (glyph) (aref glyph 6))
(defsubst lglyph-ascent (glyph) (aref glyph 7))
(defsubst lglyph-descent (glyph) (aref glyph 8))
(defsubst lglyph-adjustment (glyph) (aref glyph 9))
(defsubst lglyph-set-from-to (glyph from to)
(progn (aset glyph 0 from) (aset glyph 1 to)))
(defsubst lglyph-set-char (glyph char) (aset glyph 2 char))
(defsubst lglyph-set-code (glyph code) (aset glyph 3 code))
(defsubst lglyph-set-width (glyph width) (aset glyph 4 width))
(defsubst lglyph-set-adjustment (glyph &optional xoff yoff wadjust)
(aset glyph 9 (vector (or xoff 0) (or yoff 0) (or wadjust 0))))
(defsubst lglyph-copy (glyph) (copy-sequence glyph))
(defun lgstring-insert-glyph (gstring idx glyph)
(let ((nglyphs (lgstring-glyph-len gstring))
(i idx))
(while (and (< i nglyphs) (lgstring-glyph gstring i))
(setq i (1+ i)))
(if (= i nglyphs)
(setq gstring (vconcat gstring (vector glyph)))
(if (< (1+ i) nglyphs)
(lgstring-set-glyph gstring (1+ i) nil)))
(while (> i idx)
(lgstring-set-glyph gstring i (lgstring-glyph gstring (1- i)))
(setq i (1- i)))
(lgstring-set-glyph gstring i glyph)
gstring))
(defun compose-glyph-string (gstring from to)
(let ((glyph (lgstring-glyph gstring from))
from-pos to-pos)
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to))))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (and (< from to)
(setq glyph (lgstring-glyph gstring from)))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph)))))
(lglyph-set-adjustment glyph xoff 0 0))
(setq from (1+ from)))
gstring))
(defun compose-glyph-string-relative (gstring from to &optional gap)
(let ((font-object (lgstring-font gstring))
(glyph (lgstring-glyph gstring from))
from-pos to-pos
ascent descent)
(if gap
(setq gap (floor (* (font-get font-object :size) gap)))
(setq gap 0))
(setq from-pos (lglyph-from glyph)
to-pos (lglyph-to (lgstring-glyph gstring (1- to)))
ascent (lglyph-ascent glyph)
descent (lglyph-descent glyph))
(lglyph-set-from-to glyph from-pos to-pos)
(setq from (1+ from))
(while (< from to)
(setq glyph (lgstring-glyph gstring from))
(lglyph-set-from-to glyph from-pos to-pos)
(let ((this-ascent (lglyph-ascent glyph))
(this-descent (lglyph-descent glyph))
xoff yoff)
(setq xoff (if (<= (lglyph-rbearing glyph) 0) 0
(- (lglyph-width glyph))))
(if (> this-ascent 0)
(if (< this-descent 0)
(setq yoff (- 0 ascent gap this-descent)
ascent (+ ascent gap this-ascent this-descent))
(setq yoff 0))
(setq yoff (+ descent gap this-ascent)
descent (+ descent gap this-ascent this-descent)))
(if (or (/= xoff 0) (/= yoff 0))
(lglyph-set-adjustment glyph xoff yoff 0)))
(setq from (1+ from)))
gstring))
(defun compose-gstring-for-graphic (gstring)
"Compose glyph-string GSTRING for graphic display.
Combining characters are composed with the preceding base
character. If the preceding character is not a base character,
each combining character is composed as a spacing character by
a padding space before and/or after the character.
All non-spacing characters have this function in
`composition-function-table' unless overwritten."
(let ((nchars (lgstring-char-len gstring))
(nglyphs (lgstring-glyph-len gstring))
(glyph (lgstring-glyph gstring 0)))
(cond
;; A non-spacing character not following a proper base character.
((= nchars 1)
(let ((lbearing (lglyph-lbearing glyph))
(rbearing (lglyph-rbearing glyph))
(width (lglyph-width glyph))
xoff)
(if (< lbearing 0)
(setq xoff (- lbearing))
(setq xoff 0 lbearing 0))
(if (< rbearing width)
(setq rbearing width))
(lglyph-set-adjustment glyph xoff 0 (- rbearing lbearing))
gstring))
;; This sequence doesn't start with a proper base character.
((memq (get-char-code-property (lgstring-char gstring 0)
'general-category)
'(Mn Mc Me Zs Zl Zp Cc Cf Cs))
nil)
;; A base character and the following non-spacing characters.
(t
(let ((gstr (font-shape-gstring gstring)))
(if (and gstr
(> (lglyph-to (lgstring-glyph gstr 0)) 0))
gstr
;; The shaper of the font couldn't shape the gstring.
;; Shape them according to canonical-combining-class.
(lgstring-set-id gstring nil)
(let* ((width (lglyph-width glyph))
(ascent (lglyph-ascent glyph))
(descent (lglyph-descent glyph))
(rbearing (lglyph-rbearing glyph))
(lbearing (lglyph-lbearing glyph))
(center (/ (+ lbearing rbearing) 2))
;; Artificial vertical gap between the glyphs.
(gap (round (* (font-get (lgstring-font gstring) :size) 0.1))))
(if (= gap 0)
;; Assure at least 1 pixel vertical gap.
(setq gap 1))
(dotimes (i nchars)
(setq glyph (lgstring-glyph gstring i))
(when (> i 0)
(let* ((class (get-char-code-property
(lglyph-char glyph) 'canonical-combining-class))
(lb (lglyph-lbearing glyph))
(rb (lglyph-rbearing glyph))
(as (lglyph-ascent glyph))
(de (lglyph-descent glyph))
(ce (/ (+ lb rb) 2))
(w (lglyph-width glyph))
xoff yoff)
(cond
((and class (>= class 200) (<= class 240))
(setq xoff 0 yoff 0)
(cond
((= class 200)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 202)
(if (> as 0) (setq as 0))
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 204)
(if (> as 0) (setq as 0))
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as))))
((= class 208)
(setq xoff (- lbearing rb)))
((= class 210)
(setq xoff (- rbearing lb)))
((= class 212)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 214)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 216)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de))))
((= class 218)
(setq xoff (- lbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 220)
(setq xoff (- center ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 222)
(setq xoff (- rbearing ce)
yoff (if (> as 0) 0 (+ descent as gap))))
((= class 224)
(setq xoff (- lbearing rb)))
((= class 226)
(setq xoff (- rbearing lb)))
((= class 228)
(setq xoff (- lbearing ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 230)
(setq xoff (- center ce)
yoff (if (>= de 0) 0 (- (- ascent) de gap))))
((= class 232)
(setq xoff (- rbearing ce)
yoff (if (>= de 0) 0 (- (+ ascent de) gap)))))
(lglyph-set-adjustment glyph (- xoff width) yoff)
(setq lb (+ lb xoff)
rb (+ lb xoff)
as (- as yoff)
de (+ de yoff)))
((and (= class 0)
(eq (get-char-code-property (lglyph-char glyph)
'general-category) 'Me))
;; Artificially laying out glyphs in an enclosing
;; mark is difficult. All we can do is to adjust
;; the x-offset and width of the base glyph to
;; align it at the center of the glyph of the
;; enclosing mark hoping that the enclosing mark
;; is big enough. We also have to adjust the
;; x-offset and width of the mark ifself properly
;; depending on how the glyph is designed.
;; (non-spacing or not). For instance, when we
;; have these glyphs:
;; X position |
;; base: <-*-> lbearing=0 rbearing=5 width=5
;; mark: <----------.> lb=-11 rb=2 w=0
;; we get a correct layout by moving them as this:
;; base: <-*-> XOFF=4 WAD=9
;; mark: <----------.> xoff=2 wad=4
;; we have moved the base to the left by 4-pixel
;; and make its width 9-pixel, then move the mark
;; to the left 2-pixel and make its width 4-pixel.
(let* (;; Adjustment for the base glyph
(XOFF (/ (- rb lb width) 2))
(WAD (+ width XOFF))
;; Adjustment for the enclosing mark glyph
(xoff (- (+ lb WAD)))
(wad (- rb lb WAD)))
(lglyph-set-adjustment glyph xoff 0 wad)
(setq glyph (lgstring-glyph gstring 0))
(lglyph-set-adjustment glyph XOFF 0 WAD))))
(if (< ascent as)
(setq ascent as))
(if (< descent de)
(setq descent de))))))
(let ((i 0))
(while (and (< i nglyphs) (setq glyph (lgstring-glyph gstring i)))
(lglyph-set-from-to glyph 0 (1- nchars))
(setq i (1+ i))))
gstring))))))
;; Allow for bootstrapping without uni-*.el.
(when unicode-category-table
(let ((elt `([,(purecopy "\\c.\\c^+") 1 compose-gstring-for-graphic]
[nil 0 compose-gstring-for-graphic])))
(map-char-table
#'(lambda (key val)
(if (memq val '(Mn Mc Me))
(set-char-table-range composition-function-table key elt)))
unicode-category-table)))
(defun compose-gstring-for-terminal (gstring)
"Compose glyph-string GSTRING for terminal display.
Non-spacing characters are composed with the preceding base
character. If the preceding character is not a base character,
each non-spacing character is composed as a spacing character by
prepending a space before it."
(let ((nglyphs (lgstring-glyph-len gstring))
(i 0)
(coding (lgstring-font gstring))
glyph)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (not (char-charset (lglyph-char glyph) coding))
(progn
;; As the terminal doesn't support this glyph, return a
;; gstring in which each glyph is its own grapheme-cluster
;; of width 1..
(setq i 0)
(while (and (< i nglyphs)
(setq glyph (lgstring-glyph gstring i)))
(if (< (lglyph-width glyph) 1)
(lglyph-set-width glyph 1))
(lglyph-set-from-to glyph i i)
(setq i (1+ i))))
(if (= (lglyph-width glyph) 0)
(if (eq (get-char-code-property (lglyph-char glyph)
'general-category)
'Cf)
(progn
;; Compose by replacing with a space.
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (1+ i)))
;; Compose by prepending a space.
(setq gstring (lgstring-insert-glyph gstring i
(lglyph-copy glyph))
nglyphs (lgstring-glyph-len gstring))
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-char glyph 32)
(lglyph-set-width glyph 1)
(setq i (+ 2)))
(let ((from (lglyph-from glyph))
(to (lglyph-to glyph))
(j (1+ i)))
(while (and (< j nglyphs)
(setq glyph (lgstring-glyph gstring j))
(char-charset (lglyph-char glyph) coding)
(= (lglyph-width glyph) 0))
(setq to (lglyph-to glyph)
j (1+ j)))
(while (< i j)
(setq glyph (lgstring-glyph gstring i))
(lglyph-set-from-to glyph from to)
(setq i (1+ i)))))))
gstring))
(defun auto-compose-chars (func from to font-object string)
"Compose the characters at FROM by FUNC.
FUNC is called with one argument GSTRING which is built for characters
in the region FROM (inclusive) and TO (exclusive).
If the character are composed on a graphic display, FONT-OBJECT
is a font to use. Otherwise, FONT-OBJECT is nil, and the function
`compose-gstring-for-terminal' is used instead of FUNC.
If STRING is non-nil, it is a string, and FROM and TO are indices
into the string. In that case, compose characters in the string.
The value is a gstring containing information for shaping the characters.
This function is the default value of `auto-composition-function' (which see)."
(let ((gstring (composition-get-gstring from to font-object string)))
(if (lgstring-shaped-p gstring)
gstring
(or (fontp font-object 'font-object)
(setq func 'compose-gstring-for-terminal))
(funcall func gstring))))
(put 'auto-composition-mode 'permanent-local t)
(make-variable-buffer-local 'auto-composition-function)
(setq-default auto-composition-function 'auto-compose-chars)
;;;###autoload
(define-minor-mode auto-composition-mode
"Toggle Auto Composition mode.
With a prefix argument ARG, enable Auto Composition mode if ARG
is positive, and disable it otherwise. If called from Lisp,
enable the mode if ARG is omitted or nil.
When Auto Composition mode is enabled, text characters are
automatically composed by functions registered in
`composition-function-table'.
You can use `global-auto-composition-mode' to turn on
Auto Composition mode in all buffers (this is the default)."
;; It's defined in C, this stops the d-m-m macro defining it again.
:variable auto-composition-mode)
;; It's not defined with DEFVAR_PER_BUFFER though.
(make-variable-buffer-local 'auto-composition-mode)
;;;###autoload
(define-minor-mode global-auto-composition-mode
"Toggle Auto Composition mode in all buffers.
With a prefix argument ARG, enable it if ARG is positive, and
disable it otherwise. If called from Lisp, enable it if ARG is
omitted or nil.
For more information on Auto Composition mode, see
`auto-composition-mode' ."
:variable (default-value 'auto-composition-mode))
(defalias 'toggle-auto-composition 'auto-composition-mode)
;;; composite.el ends here
|
[
{
"context": " If not, see http://magit.vc/authors.\n\n;; Author: Jonas Bernoulli <jonas@bernoul.li>\n;; Maintainer: Jonas Bernoulli",
"end": 282,
"score": 0.9998624920845032,
"start": 267,
"tag": "NAME",
"value": "Jonas Bernoulli"
},
{
"context": "://magit.vc/authors.\n\n;; Author: Jonas Bernoulli <jonas@bernoul.li>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li",
"end": 300,
"score": 0.9999324083328247,
"start": 284,
"tag": "EMAIL",
"value": "jonas@bernoul.li"
},
{
"context": " Jonas Bernoulli <jonas@bernoul.li>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>\n\n;; Magit is free software; yo",
"end": 332,
"score": 0.9998632073402405,
"start": 317,
"tag": "NAME",
"value": "Jonas Bernoulli"
},
{
"context": "jonas@bernoul.li>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>\n\n;; Magit is free software; you can redistribute",
"end": 350,
"score": 0.9999317526817322,
"start": 334,
"tag": "EMAIL",
"value": "jonas@bernoul.li"
}
] | elpa/magit-2.1.0/magit-wip.el | archie14/emacs-conf | 2 | ;;; magit-wip.el --- commit snapshots to work-in-progress refs
;; Copyright (C) 2010-2015 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: Jonas Bernoulli <jonas@bernoul.li>
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; This library defines tree global modes which automatically commit
;; snapshots to branch specific work-in-progress refs before and after
;; making changes, and two commands which can be used to do so on
;; demand.
;;; Code:
(require 'magit-core)
(require 'format-spec)
;;; Options
(defgroup magit-wip nil
"Automatically commit to work-in-progress refs."
:group 'magit-extensions)
(defcustom magit-wip-after-save-local-mode-lighter " sWip"
"Lighter for Magit-Wip-After-Save-Local mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-after-apply-mode-lighter " aWip"
"Lighter for Magit-Wip-After-Apply mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-before-change-mode-lighter " cWip"
"Lighter for Magit-Wip-Before-Change mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-namespace "refs/wip/"
"Namespace used for work-in-progress refs.
The wip refs are named \"<namespace/>index/<branchref>\"
and \"<namespace/>wtree/<branchref>\". When snapshots
are created while the `HEAD' is detached then \"HEAD\"
is used as `branch-ref'."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
;;; Modes
(define-minor-mode magit-wip-after-save-local-mode
"After saving, also commit to a worktree work-in-progress ref.
After saving the current file-visiting buffer this mode also
commits the changes to the worktree work-in-progress ref for
the current branch.
This mode should be enabled globally by turning on the globalized
variant `magit-wip-after-save-mode'."
:package-version '(magit . "2.1.0")
:lighter magit-wip-after-save-local-mode-lighter
(if magit-wip-after-save-local-mode
(if (and buffer-file-name (magit-inside-worktree-p))
(add-hook 'after-save-hook 'magit-wip-commit-buffer-file t t)
(setq magit-wip-after-save-local-mode nil)
(user-error "Need a worktree and a file"))
(remove-hook 'after-save-hook 'magit-wip-commit-buffer-file t)))
(defun magit-wip-after-save-local-mode-turn-on ()
(and buffer-file-name
(ignore-errors (magit-inside-worktree-p))
(magit-file-tracked-p buffer-file-name)
(magit-wip-after-save-local-mode)))
;;;###autoload
(define-globalized-minor-mode magit-wip-after-save-mode
magit-wip-after-save-local-mode magit-wip-after-save-local-mode-turn-on
:package-version '(magit . "2.1.0")
:group 'magit-wip)
(defun magit-wip-commit-buffer-file ()
"Commit visited file to a worktree work-in-progress ref.
Also see `magit-wip-after-save-mode' which calls this function
automatically whenever a buffer visiting a tracked file is saved."
(interactive)
(--when-let (magit-wip-get-ref)
(let* ((default-directory (magit-toplevel))
(file (file-relative-name buffer-file-name )))
(magit-wip-commit-worktree it (list file)
(if (called-interactively-p 'any)
(format "wip-save %s after save" file)
(format "autosave %s after save" file))))))
;;;###autoload
(define-minor-mode magit-wip-after-apply-mode
"Commit to work-in-progress refs"
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-after-change-mode-lighter
:global t)
(defun magit-wip-commit-after-apply (&optional files msg)
(when magit-wip-after-apply-mode
(magit-wip-commit files msg)))
;;;###autoload
(define-minor-mode magit-wip-before-change-mode
"Commit to work-in-progress refs before certain destructive changes.
Before invoking a revert command or an \"apply variant\"
command (apply, stage, unstage, discard, and reverse) commit the
affected tracked files to the current wip refs. For each branch
there may be two wip refs; one contains snapshots of the files
as found in the worktree and the other contains snapshots of the
entries in the index.
Only changes to files which could potentially be affected by the
command which is about to be called are committed."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-before-change-mode-lighter
:global t)
(defun magit-wip-commit-before-change (&optional files msg)
(when magit-wip-before-change-mode
(magit-wip-commit files msg)))
;;; Core
(defun magit-wip-commit (&optional files msg)
"Commit all tracked files to the work-in-progress refs.
Non-interactivly, on behalf of `magit-wip-before-change-hook',
only commit changes to FILES using MSG as commit message."
(interactive (list nil "wip-save tracked files"))
(--when-let (magit-wip-get-ref)
(magit-wip-commit-index it files msg)
(magit-wip-commit-worktree it files msg)))
(defun magit-wip-commit-index (ref files msg &optional cached-only)
(let* ((wipref (concat magit-wip-namespace "index/" ref))
(parent (magit-wip-get-parent ref wipref)))
(when (magit-git-failure "diff-index" "--quiet"
(and cached-only "--cached")
parent "--" files)
(magit-wip-update-wipref wipref (magit-git-string "write-tree")
parent files msg))))
(defun magit-wip-commit-worktree (ref files msg)
(let* ((wipref (concat magit-wip-namespace "wtree/" ref))
(parent (magit-wip-get-parent ref wipref))
(tree (magit-with-temp-index parent
(if files
(magit-call-git "add" "--" files)
(let ((default-directory (magit-toplevel)))
(magit-call-git "add" "-u" ".")))
(magit-git-string "write-tree"))))
(when (magit-git-failure "diff-tree" "--quiet" parent tree "--" files)
(magit-wip-update-wipref wipref tree parent files msg))))
(defun magit-wip-update-wipref (wipref tree parent files msg)
(let ((len (length files)))
(unless (and msg (not (= (aref msg 0) ?\s)))
(setq msg (concat
(cond ((= len 0) "autosave tracked files")
((> len 1) (format "autosave %s files" len))
(t (concat "autosave "
(file-relative-name (car files)
(magit-toplevel)))))
msg)))
(magit-reflog-enable wipref)
(unless (equal parent wipref)
(magit-call-git "update-ref" wipref "-m" "restart autosaving"
(magit-git-string "commit-tree" "-p" parent
"-m" "restart autosaving"
(concat parent "^{tree}")))
(setq parent wipref))
(magit-call-git "update-ref" wipref "-m" msg
(magit-git-string "commit-tree" tree
"-p" parent "-m" msg))))
(defun magit-wip-get-ref ()
(let ((ref (or (magit-git-string "symbolic-ref" "HEAD") "HEAD")))
(when (magit-rev-verify ref)
ref)))
(defun magit-wip-get-parent (ref wipref)
(if (and (magit-rev-verify wipref)
(equal (magit-git-string "merge-base" wipref ref)
(magit-rev-verify ref)))
wipref
ref))
;;; magit-wip.el ends soon
(provide 'magit-wip)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; magit-wip.el ends here
| 28614 | ;;; magit-wip.el --- commit snapshots to work-in-progress refs
;; Copyright (C) 2010-2015 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; This library defines tree global modes which automatically commit
;; snapshots to branch specific work-in-progress refs before and after
;; making changes, and two commands which can be used to do so on
;; demand.
;;; Code:
(require 'magit-core)
(require 'format-spec)
;;; Options
(defgroup magit-wip nil
"Automatically commit to work-in-progress refs."
:group 'magit-extensions)
(defcustom magit-wip-after-save-local-mode-lighter " sWip"
"Lighter for Magit-Wip-After-Save-Local mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-after-apply-mode-lighter " aWip"
"Lighter for Magit-Wip-After-Apply mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-before-change-mode-lighter " cWip"
"Lighter for Magit-Wip-Before-Change mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-namespace "refs/wip/"
"Namespace used for work-in-progress refs.
The wip refs are named \"<namespace/>index/<branchref>\"
and \"<namespace/>wtree/<branchref>\". When snapshots
are created while the `HEAD' is detached then \"HEAD\"
is used as `branch-ref'."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
;;; Modes
(define-minor-mode magit-wip-after-save-local-mode
"After saving, also commit to a worktree work-in-progress ref.
After saving the current file-visiting buffer this mode also
commits the changes to the worktree work-in-progress ref for
the current branch.
This mode should be enabled globally by turning on the globalized
variant `magit-wip-after-save-mode'."
:package-version '(magit . "2.1.0")
:lighter magit-wip-after-save-local-mode-lighter
(if magit-wip-after-save-local-mode
(if (and buffer-file-name (magit-inside-worktree-p))
(add-hook 'after-save-hook 'magit-wip-commit-buffer-file t t)
(setq magit-wip-after-save-local-mode nil)
(user-error "Need a worktree and a file"))
(remove-hook 'after-save-hook 'magit-wip-commit-buffer-file t)))
(defun magit-wip-after-save-local-mode-turn-on ()
(and buffer-file-name
(ignore-errors (magit-inside-worktree-p))
(magit-file-tracked-p buffer-file-name)
(magit-wip-after-save-local-mode)))
;;;###autoload
(define-globalized-minor-mode magit-wip-after-save-mode
magit-wip-after-save-local-mode magit-wip-after-save-local-mode-turn-on
:package-version '(magit . "2.1.0")
:group 'magit-wip)
(defun magit-wip-commit-buffer-file ()
"Commit visited file to a worktree work-in-progress ref.
Also see `magit-wip-after-save-mode' which calls this function
automatically whenever a buffer visiting a tracked file is saved."
(interactive)
(--when-let (magit-wip-get-ref)
(let* ((default-directory (magit-toplevel))
(file (file-relative-name buffer-file-name )))
(magit-wip-commit-worktree it (list file)
(if (called-interactively-p 'any)
(format "wip-save %s after save" file)
(format "autosave %s after save" file))))))
;;;###autoload
(define-minor-mode magit-wip-after-apply-mode
"Commit to work-in-progress refs"
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-after-change-mode-lighter
:global t)
(defun magit-wip-commit-after-apply (&optional files msg)
(when magit-wip-after-apply-mode
(magit-wip-commit files msg)))
;;;###autoload
(define-minor-mode magit-wip-before-change-mode
"Commit to work-in-progress refs before certain destructive changes.
Before invoking a revert command or an \"apply variant\"
command (apply, stage, unstage, discard, and reverse) commit the
affected tracked files to the current wip refs. For each branch
there may be two wip refs; one contains snapshots of the files
as found in the worktree and the other contains snapshots of the
entries in the index.
Only changes to files which could potentially be affected by the
command which is about to be called are committed."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-before-change-mode-lighter
:global t)
(defun magit-wip-commit-before-change (&optional files msg)
(when magit-wip-before-change-mode
(magit-wip-commit files msg)))
;;; Core
(defun magit-wip-commit (&optional files msg)
"Commit all tracked files to the work-in-progress refs.
Non-interactivly, on behalf of `magit-wip-before-change-hook',
only commit changes to FILES using MSG as commit message."
(interactive (list nil "wip-save tracked files"))
(--when-let (magit-wip-get-ref)
(magit-wip-commit-index it files msg)
(magit-wip-commit-worktree it files msg)))
(defun magit-wip-commit-index (ref files msg &optional cached-only)
(let* ((wipref (concat magit-wip-namespace "index/" ref))
(parent (magit-wip-get-parent ref wipref)))
(when (magit-git-failure "diff-index" "--quiet"
(and cached-only "--cached")
parent "--" files)
(magit-wip-update-wipref wipref (magit-git-string "write-tree")
parent files msg))))
(defun magit-wip-commit-worktree (ref files msg)
(let* ((wipref (concat magit-wip-namespace "wtree/" ref))
(parent (magit-wip-get-parent ref wipref))
(tree (magit-with-temp-index parent
(if files
(magit-call-git "add" "--" files)
(let ((default-directory (magit-toplevel)))
(magit-call-git "add" "-u" ".")))
(magit-git-string "write-tree"))))
(when (magit-git-failure "diff-tree" "--quiet" parent tree "--" files)
(magit-wip-update-wipref wipref tree parent files msg))))
(defun magit-wip-update-wipref (wipref tree parent files msg)
(let ((len (length files)))
(unless (and msg (not (= (aref msg 0) ?\s)))
(setq msg (concat
(cond ((= len 0) "autosave tracked files")
((> len 1) (format "autosave %s files" len))
(t (concat "autosave "
(file-relative-name (car files)
(magit-toplevel)))))
msg)))
(magit-reflog-enable wipref)
(unless (equal parent wipref)
(magit-call-git "update-ref" wipref "-m" "restart autosaving"
(magit-git-string "commit-tree" "-p" parent
"-m" "restart autosaving"
(concat parent "^{tree}")))
(setq parent wipref))
(magit-call-git "update-ref" wipref "-m" msg
(magit-git-string "commit-tree" tree
"-p" parent "-m" msg))))
(defun magit-wip-get-ref ()
(let ((ref (or (magit-git-string "symbolic-ref" "HEAD") "HEAD")))
(when (magit-rev-verify ref)
ref)))
(defun magit-wip-get-parent (ref wipref)
(if (and (magit-rev-verify wipref)
(equal (magit-git-string "merge-base" wipref ref)
(magit-rev-verify ref)))
wipref
ref))
;;; magit-wip.el ends soon
(provide 'magit-wip)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; magit-wip.el ends here
| true | ;;; magit-wip.el --- commit snapshots to work-in-progress refs
;; Copyright (C) 2010-2015 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; This library defines tree global modes which automatically commit
;; snapshots to branch specific work-in-progress refs before and after
;; making changes, and two commands which can be used to do so on
;; demand.
;;; Code:
(require 'magit-core)
(require 'format-spec)
;;; Options
(defgroup magit-wip nil
"Automatically commit to work-in-progress refs."
:group 'magit-extensions)
(defcustom magit-wip-after-save-local-mode-lighter " sWip"
"Lighter for Magit-Wip-After-Save-Local mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-after-apply-mode-lighter " aWip"
"Lighter for Magit-Wip-After-Apply mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-before-change-mode-lighter " cWip"
"Lighter for Magit-Wip-Before-Change mode."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
(defcustom magit-wip-namespace "refs/wip/"
"Namespace used for work-in-progress refs.
The wip refs are named \"<namespace/>index/<branchref>\"
and \"<namespace/>wtree/<branchref>\". When snapshots
are created while the `HEAD' is detached then \"HEAD\"
is used as `branch-ref'."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:type 'string)
;;; Modes
(define-minor-mode magit-wip-after-save-local-mode
"After saving, also commit to a worktree work-in-progress ref.
After saving the current file-visiting buffer this mode also
commits the changes to the worktree work-in-progress ref for
the current branch.
This mode should be enabled globally by turning on the globalized
variant `magit-wip-after-save-mode'."
:package-version '(magit . "2.1.0")
:lighter magit-wip-after-save-local-mode-lighter
(if magit-wip-after-save-local-mode
(if (and buffer-file-name (magit-inside-worktree-p))
(add-hook 'after-save-hook 'magit-wip-commit-buffer-file t t)
(setq magit-wip-after-save-local-mode nil)
(user-error "Need a worktree and a file"))
(remove-hook 'after-save-hook 'magit-wip-commit-buffer-file t)))
(defun magit-wip-after-save-local-mode-turn-on ()
(and buffer-file-name
(ignore-errors (magit-inside-worktree-p))
(magit-file-tracked-p buffer-file-name)
(magit-wip-after-save-local-mode)))
;;;###autoload
(define-globalized-minor-mode magit-wip-after-save-mode
magit-wip-after-save-local-mode magit-wip-after-save-local-mode-turn-on
:package-version '(magit . "2.1.0")
:group 'magit-wip)
(defun magit-wip-commit-buffer-file ()
"Commit visited file to a worktree work-in-progress ref.
Also see `magit-wip-after-save-mode' which calls this function
automatically whenever a buffer visiting a tracked file is saved."
(interactive)
(--when-let (magit-wip-get-ref)
(let* ((default-directory (magit-toplevel))
(file (file-relative-name buffer-file-name )))
(magit-wip-commit-worktree it (list file)
(if (called-interactively-p 'any)
(format "wip-save %s after save" file)
(format "autosave %s after save" file))))))
;;;###autoload
(define-minor-mode magit-wip-after-apply-mode
"Commit to work-in-progress refs"
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-after-change-mode-lighter
:global t)
(defun magit-wip-commit-after-apply (&optional files msg)
(when magit-wip-after-apply-mode
(magit-wip-commit files msg)))
;;;###autoload
(define-minor-mode magit-wip-before-change-mode
"Commit to work-in-progress refs before certain destructive changes.
Before invoking a revert command or an \"apply variant\"
command (apply, stage, unstage, discard, and reverse) commit the
affected tracked files to the current wip refs. For each branch
there may be two wip refs; one contains snapshots of the files
as found in the worktree and the other contains snapshots of the
entries in the index.
Only changes to files which could potentially be affected by the
command which is about to be called are committed."
:package-version '(magit . "2.1.0")
:group 'magit-wip
:lighter magit-wip-before-change-mode-lighter
:global t)
(defun magit-wip-commit-before-change (&optional files msg)
(when magit-wip-before-change-mode
(magit-wip-commit files msg)))
;;; Core
(defun magit-wip-commit (&optional files msg)
"Commit all tracked files to the work-in-progress refs.
Non-interactivly, on behalf of `magit-wip-before-change-hook',
only commit changes to FILES using MSG as commit message."
(interactive (list nil "wip-save tracked files"))
(--when-let (magit-wip-get-ref)
(magit-wip-commit-index it files msg)
(magit-wip-commit-worktree it files msg)))
(defun magit-wip-commit-index (ref files msg &optional cached-only)
(let* ((wipref (concat magit-wip-namespace "index/" ref))
(parent (magit-wip-get-parent ref wipref)))
(when (magit-git-failure "diff-index" "--quiet"
(and cached-only "--cached")
parent "--" files)
(magit-wip-update-wipref wipref (magit-git-string "write-tree")
parent files msg))))
(defun magit-wip-commit-worktree (ref files msg)
(let* ((wipref (concat magit-wip-namespace "wtree/" ref))
(parent (magit-wip-get-parent ref wipref))
(tree (magit-with-temp-index parent
(if files
(magit-call-git "add" "--" files)
(let ((default-directory (magit-toplevel)))
(magit-call-git "add" "-u" ".")))
(magit-git-string "write-tree"))))
(when (magit-git-failure "diff-tree" "--quiet" parent tree "--" files)
(magit-wip-update-wipref wipref tree parent files msg))))
(defun magit-wip-update-wipref (wipref tree parent files msg)
(let ((len (length files)))
(unless (and msg (not (= (aref msg 0) ?\s)))
(setq msg (concat
(cond ((= len 0) "autosave tracked files")
((> len 1) (format "autosave %s files" len))
(t (concat "autosave "
(file-relative-name (car files)
(magit-toplevel)))))
msg)))
(magit-reflog-enable wipref)
(unless (equal parent wipref)
(magit-call-git "update-ref" wipref "-m" "restart autosaving"
(magit-git-string "commit-tree" "-p" parent
"-m" "restart autosaving"
(concat parent "^{tree}")))
(setq parent wipref))
(magit-call-git "update-ref" wipref "-m" msg
(magit-git-string "commit-tree" tree
"-p" parent "-m" msg))))
(defun magit-wip-get-ref ()
(let ((ref (or (magit-git-string "symbolic-ref" "HEAD") "HEAD")))
(when (magit-rev-verify ref)
ref)))
(defun magit-wip-get-parent (ref wipref)
(if (and (magit-rev-verify wipref)
(equal (magit-git-string "merge-base" wipref ref)
(magit-rev-verify ref)))
wipref
ref))
;;; magit-wip.el ends soon
(provide 'magit-wip)
;; Local Variables:
;; indent-tabs-mode: nil
;; End:
;;; magit-wip.el ends here
|
[
{
"context": "-*- lexical-binding: t; -*-\n\n;; Copyright (C) 2020 E. Alexander Barbosa\n\n;; Author: E. Alexander Barbosa <elxbarbosa@outl",
"end": 102,
"score": 0.9998501539230347,
"start": 82,
"tag": "NAME",
"value": "E. Alexander Barbosa"
},
{
"context": "opyright (C) 2020 E. Alexander Barbosa\n\n;; Author: E. Alexander Barbosa <elxbarbosa@outlook.com>\n;; Keywords:\n\n;; This pr",
"end": 135,
"score": 0.9998806715011597,
"start": 115,
"tag": "NAME",
"value": "E. Alexander Barbosa"
},
{
"context": "exander Barbosa\n\n;; Author: E. Alexander Barbosa <elxbarbosa@outlook.com>\n;; Keywords:\n\n;; This program is free software; ",
"end": 159,
"score": 0.9999319911003113,
"start": 137,
"tag": "EMAIL",
"value": "elxbarbosa@outlook.com"
},
{
"context": "on \"7.1\"\n :link '(url-link \"https://github.com/EmmyLua/EmmyLua-LanguageServer\"))\n\n(defcustom lsp-clients",
"end": 1117,
"score": 0.5266520977020264,
"start": 1112,
"tag": "USERNAME",
"value": "myLua"
},
{
"context": "sion \"7.1\"\n :link '(url-link \"https://github.com/sumneko/lua-language-server\"))\n\n(defcustom lsp-clients-lu",
"end": 2816,
"score": 0.9991917610168457,
"start": 2809,
"tag": "USERNAME",
"value": "sumneko"
},
{
"context": "sion \"7.1\"\n :link '(url-link \"https://github.com/Alloyed/lua-lsp\"))\n\n(defcustom lsp-clients-luarocks-bin-d",
"end": 19082,
"score": 0.9972867965698242,
"start": 19075,
"tag": "USERNAME",
"value": "Alloyed"
}
] | link/.emacs.d/elpa/lsp-mode-20210613.1645/lsp-lua.el | HarrisonMc555/dotfiles | 1 | ;;; lsp-lua.el --- description -*- lexical-binding: t; -*-
;; Copyright (C) 2020 E. Alexander Barbosa
;; Author: E. Alexander Barbosa <elxbarbosa@outlook.com>
;; Keywords:
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; LSP Clients for the Lua Programming Language
;;; Code:
(require 'lsp-mode)
(require 'f)
(require 'files)
(defgroup lsp-emmy-lua nil
"Lua LSP client, provided by the EmmyLua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/EmmyLua/EmmyLua-LanguageServer"))
(defcustom lsp-clients-emmy-lua-java-path "java"
"Java Runtime binary location."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-jar-path (f-join lsp-server-install-dir "EmmyLua-LS-all.jar")
"Emmy Lua language server jar file."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-args '("-jar")
"Arguments to the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-emmy-lua-command nil
"Final command to call the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defun lsp-clients-emmy-lua-test ()
"Test the Emmy Lua binaries and files."
(and (executable-find lsp-clients-emmy-lua-java-path)
(f-exists? lsp-clients-emmy-lua-jar-path)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-emmy-lua-command
`(,lsp-clients-emmy-lua-java-path
,@lsp-clients-emmy-lua-args
,lsp-clients-emmy-lua-jar-path)))
#'lsp-clients-emmy-lua-test)
:major-modes '(lua-mode)
:server-id 'emmy-lua
:priority -1
:notification-handlers (lsp-ht ("emmy/progressReport" #'ignore))))
;;; lua-language-server
(defgroup lsp-lua-language-server nil
"Lua LSP client, provided by the Lua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/sumneko/lua-language-server"))
(defcustom lsp-clients-lua-language-server-install-dir (f-join lsp-server-install-dir "lua-language-server/")
"Installation directory for Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-language-server-bin
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/bin/"
(pcase system-type
('gnu/linux "Linux/lua-language-server")
('darwin "macOS/lua-language-server")
('windows-nt "Windows/lua-language-server.exe")
(_ "Linux/lua-language-server")))
"Location of Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-main-location
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/main.lua")
"Location of Lua Language Server main.lua."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-args '("-E")
"Arguments to run the Lua Language server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-lua-language-server-command nil
"Command to start Lua Language server."
:group 'lsp-lua-language-server
:type '(repeat string))
(defun lsp-clients-lua-language-server-test ()
"Test Lua language server binaries and files."
(and (f-exists? lsp-clients-lua-language-server-main-location)
(f-exists? lsp-clients-lua-language-server-bin)))
(defcustom lsp-lua-color-mode "Semantic"
"Color mode."
:type '(choice (:tag "Grammar" "Semantic"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-call-snippet "Disable"
"Shows function call snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-display-context 6
"Previewing the relevant code snippet of the suggestion may help you
understand the usage of the suggestion.
The number set indicates the number of intercepted lines in the code
fragment. If it is set to `0`, this feature can be disabled."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-enable t
"Enable completion."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-keyword-snippet "Replace"
"Shows keyword syntax snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-workspace-word t
"Show words within the workspace."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-port 11412
"Listen port of debugger."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-wait nil
"Suspend before debugger connects."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-enable nil
"Developer mode. Do not enable, performance will be affected."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-disable nil
"Disabled diagnostic (Use code in hover brackets).
```json
\"Lua.diagnostics.disable\" : [
\"unused-local\",
\"lowercase-global\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-enable t
"Enable diagnostics."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-globals nil
"Defined global variables.
```json
\"Lua.diagnostics.globals\" : [
\"GLOBAL1\",
\"GLOBAL2\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-needed-file-status nil
"If you want to check only opened files, choice Opened; else choice Any.
```json
\"Lua.diagnostics.neededFileStatus\" : {
\"ambiguity-1\" : \"Any\",
\"circle-doc-class\" : \"Opened\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-severity nil
"Modified diagnostic severity.
```json
\"Lua.diagnostics.severity\" : {
\"redefined-local\" : \"Warning\",
\"emmy-lua\" : \"Hint\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-delay 0
"Latency (milliseconds) for workspace diagnostics. When you start the
workspace, or edit any file, the entire workspace will be re-diagnosed in the
background. Set to negative to disable workspace diagnostics."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-rate 100
"Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage,
but also reduces the speed of workspace diagnostics. The diagnosis of the file
you are currently editing is always done at full speed and is not affected by
this setting."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-enable nil
"Enable hint."
:type 'boolean
:package-version '(lsp-mmode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-name t
"Hint parameter name when the parameter called is literal."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-type t
"Show type hints at the parameter of the function."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-set-type nil
"Hint type at assignment operation."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-enable t
"Enable hover."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-field-infer 3000
"When hovering to view a table, type infer will be performed for each field.
When the accumulated time of type infer reaches the set value (MS), the type
infer of subsequent fields will be skipped."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-preview-fields 100
"When hovering to view a table, limits the maximum number of previews for
fields."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-number t
"Hover to view numeric content (only if literal is not decimal)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string t
"Hover to view the contents of a string (only if the literal contains an
escape character)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string-max 1000
"The maximum length of a hover to view the contents of a string."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-intelli-sense-search-depth 0
"Set the search depth for IntelliSense. Increasing this value increases
accuracy, but decreases performance. Different workspace have different
tolerance for this setting. Please adjust it to the appropriate value."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-file-encoding "utf8"
"File encoding. The 'ansi' option is only available under the 'Windows'
platform."
:type '(choice (:tag "utf8" "ansi"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-nonstandard-symbol nil
"Supports non-standard symbols. Make sure that your runtime environment
supports these symbols."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-path
["?.lua" "?/init.lua" "?/?.lua"]
"`package.path`."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-plugin nil
"(Proposed) Plugin path. Default is `.vscode/lua/plugin.lua`"
:type 'file
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-special nil
"The custom global variables are regarded as some special built-in variables,
and the language server will provide special support.
```json
\"Lua.runtime.special\" : {
\"include\" : \"require\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-unicode-name nil
"Allows Unicode characters in name."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-version "Lua 5.4"
"Lua runtime version."
:type '(choice (:tag "Lua 5.1" "Lua 5.2" "Lua 5.3" "Lua 5.4" "LuaJIT"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-signature-help-enable t
"Enable signature help."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-telemetry-enable nil
"Enable telemetry to send your editor information and error logs over the
network."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-progress-bar t
"Show progress bar in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-status-bar t
"Show extension status in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-dir
[".vscode"]
"Ignored directories (Use `.gitignore` grammar).
```json
\"Lua.workspace.ignoreDir\" : [
\"temp/*.*\",
\"!temp/*.lua\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-submodules t
"Ignore submodules."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-library nil
"Load external library.
This feature can load external Lua files, which can be used for definition,
automatic completion and other functions. Note that the language server does
not monitor changes in external files and needs to restart if the external
files are modified. The following example shows loaded files in `C:/lua`
and `../lib` ,exclude `../lib/temp`.
```json
\"Lua.workspace.library\": {
\"C:/lua\": true,
\"../lib\": [
\"temp/*\"
]
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-max-preload 1000
"Max preloaded files."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-preload-file-size 100
"Skip files larger than this value (KB) when preloading."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-use-git-ignore t
"Ignore files list in `.gitignore` ."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-associations nil
"Files.associations."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-exclude nil
"Files.exclude."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(lsp-register-custom-settings
'(("files.associations" lsp-lua-files-associations t)
("files.exclude" lsp-lua-files-exclude t)
("Lua.workspace.useGitIgnore" lsp-lua-workspace-use-git-ignore t)
("Lua.workspace.preloadFileSize" lsp-lua-workspace-preload-file-size)
("Lua.workspace.maxPreload" lsp-lua-workspace-max-preload)
("Lua.workspace.library" lsp-lua-workspace-library)
("Lua.workspace.ignoreSubmodules" lsp-lua-workspace-ignore-submodules t)
("Lua.workspace.ignoreDir" lsp-lua-workspace-ignore-dir)
("Lua.window.statusBar" lsp-lua-window-status-bar t)
("Lua.window.progressBar" lsp-lua-window-progress-bar t)
("Lua.telemetry.enable" lsp-lua-telemetry-enable t)
("Lua.signatureHelp.enable" lsp-lua-signature-help-enable t)
("Lua.runtime.version" lsp-lua-runtime-version)
("Lua.runtime.unicodeName" lsp-lua-runtime-unicode-name nil)
("Lua.runtime.special" lsp-lua-runtime-special)
("Lua.runtime.plugin" lsp-lua-runtime-plugin)
("Lua.runtime.path" lsp-lua-runtime-path)
("Lua.runtime.nonstandardSymbol" lsp-lua-runtime-nonstandard-symbol)
("Lua.runtime.fileEncoding" lsp-lua-runtime-file-encoding)
("Lua.intelliSense.searchDepth" lsp-lua-intelli-sense-search-depth)
("Lua.hover.viewStringMax" lsp-lua-hover-view-string-max)
("Lua.hover.viewString" lsp-lua-hover-view-string t)
("Lua.hover.viewNumber" lsp-lua-hover-view-number t)
("Lua.hover.previewFields" lsp-lua-hover-preview-fields)
("Lua.hover.fieldInfer" lsp-lua-hover-field-infer)
("Lua.hover.enable" lsp-lua-hover-enable t)
("Lua.hint.setType" lsp-lua-hint-set-type nil)
("Lua.hint.paramType" lsp-lua-hint-param-type t)
("Lua.hint.paramName" lsp-lua-hint-param-name t)
("Lua.hint.enable" lsp-lua-hint-enable t)
("Lua.diagnostics.workspaceRate" lsp-lua-diagnostics-workspace-rate)
("Lua.diagnostics.workspaceDelay" lsp-lua-diagnostics-workspace-delay)
("Lua.diagnostics.severity" lsp-lua-diagnostics-severity)
("Lua.diagnostics.neededFileStatus" lsp-lua-diagnostics-needed-file-status)
("Lua.diagnostics.globals" lsp-lua-diagnostics-globals)
("Lua.diagnostics.enable" lsp-lua-diagnostics-enable t)
("Lua.diagnostics.disable" lsp-lua-diagnostics-disable)
("Lua.develop.enable" lsp-lua-develop-enable t)
("Lua.develop.debuggerWait" lsp-lua-develop-debugger-wait t)
("Lua.develop.debuggerPort" lsp-lua-develop-debugger-port)
("Lua.completion.workspaceWord" lsp-lua-completion-workspace-word t)
("Lua.completion.keywordSnippet" lsp-lua-completion-keyword-snippet)
("Lua.completion.enable" lsp-lua-completion-enable t)
("Lua.completion.displayContext" lsp-lua-completion-display-context)
("Lua.completion.callSnippet" lsp-lua-completion-call-snippet)
("Lua.color.mode" lsp-lua-color-mode)))
(defun lsp-lua-language-server-install (client callback error-callback update?)
"Download the latest version of lua-language-server and extract it to
`lsp-lua-language-server-install-dir'."
(ignore client update?)
(let ((store-path (expand-file-name "vs-lua" lsp-clients-lua-language-server-install-dir)))
(lsp-download-install
(lambda (&rest _)
(set-file-modes lsp-clients-lua-language-server-bin #o0700)
(funcall callback))
error-callback
:url (lsp-vscode-extension-url "sumneko" "lua" "1.17.4")
:store-path store-path
:decompress :zip)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-lua-language-server-command
`(,lsp-clients-lua-language-server-bin
,@lsp-clients-lua-language-server-args
,lsp-clients-lua-language-server-main-location)))
#'lsp-clients-lua-language-server-test)
:major-modes '(lua-mode)
:priority -2
:server-id 'lua-language-server
:download-server-fn #'lsp-lua-language-server-install))
;;; lua-lsp
(defgroup lsp-lua-lsp nil
"Lua LSP client, provided by the Lua-Lsp."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/Alloyed/lua-lsp"))
(defcustom lsp-clients-luarocks-bin-dir (f-join (getenv "HOME") ".luarocks/bin/")
"LuaRocks bin directory."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-lsp-server-install-dir nil
"Installation directory for Lua-Lsp Language Server."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'file)
(defun lsp-clients-lua-lsp-test ()
"Test Lua-lsp language server files."
(and (f-exists? lsp-clients-lua-lsp-server-install-dir)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda ()
(or lsp-clients-lua-lsp-server-install-dir
(f-join lsp-clients-luarocks-bin-dir "lua-lsp")))
#'lsp-clients-lua-lsp-test)
:major-modes '(lua-mode)
:priority -3
:server-id 'lsp-lua-lsp))
(lsp-consistency-check lsp-lua)
(provide 'lsp-lua)
;;; lsp-lua.el ends here
| 45709 | ;;; lsp-lua.el --- description -*- lexical-binding: t; -*-
;; Copyright (C) 2020 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords:
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; LSP Clients for the Lua Programming Language
;;; Code:
(require 'lsp-mode)
(require 'f)
(require 'files)
(defgroup lsp-emmy-lua nil
"Lua LSP client, provided by the EmmyLua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/EmmyLua/EmmyLua-LanguageServer"))
(defcustom lsp-clients-emmy-lua-java-path "java"
"Java Runtime binary location."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-jar-path (f-join lsp-server-install-dir "EmmyLua-LS-all.jar")
"Emmy Lua language server jar file."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-args '("-jar")
"Arguments to the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-emmy-lua-command nil
"Final command to call the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defun lsp-clients-emmy-lua-test ()
"Test the Emmy Lua binaries and files."
(and (executable-find lsp-clients-emmy-lua-java-path)
(f-exists? lsp-clients-emmy-lua-jar-path)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-emmy-lua-command
`(,lsp-clients-emmy-lua-java-path
,@lsp-clients-emmy-lua-args
,lsp-clients-emmy-lua-jar-path)))
#'lsp-clients-emmy-lua-test)
:major-modes '(lua-mode)
:server-id 'emmy-lua
:priority -1
:notification-handlers (lsp-ht ("emmy/progressReport" #'ignore))))
;;; lua-language-server
(defgroup lsp-lua-language-server nil
"Lua LSP client, provided by the Lua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/sumneko/lua-language-server"))
(defcustom lsp-clients-lua-language-server-install-dir (f-join lsp-server-install-dir "lua-language-server/")
"Installation directory for Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-language-server-bin
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/bin/"
(pcase system-type
('gnu/linux "Linux/lua-language-server")
('darwin "macOS/lua-language-server")
('windows-nt "Windows/lua-language-server.exe")
(_ "Linux/lua-language-server")))
"Location of Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-main-location
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/main.lua")
"Location of Lua Language Server main.lua."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-args '("-E")
"Arguments to run the Lua Language server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-lua-language-server-command nil
"Command to start Lua Language server."
:group 'lsp-lua-language-server
:type '(repeat string))
(defun lsp-clients-lua-language-server-test ()
"Test Lua language server binaries and files."
(and (f-exists? lsp-clients-lua-language-server-main-location)
(f-exists? lsp-clients-lua-language-server-bin)))
(defcustom lsp-lua-color-mode "Semantic"
"Color mode."
:type '(choice (:tag "Grammar" "Semantic"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-call-snippet "Disable"
"Shows function call snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-display-context 6
"Previewing the relevant code snippet of the suggestion may help you
understand the usage of the suggestion.
The number set indicates the number of intercepted lines in the code
fragment. If it is set to `0`, this feature can be disabled."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-enable t
"Enable completion."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-keyword-snippet "Replace"
"Shows keyword syntax snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-workspace-word t
"Show words within the workspace."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-port 11412
"Listen port of debugger."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-wait nil
"Suspend before debugger connects."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-enable nil
"Developer mode. Do not enable, performance will be affected."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-disable nil
"Disabled diagnostic (Use code in hover brackets).
```json
\"Lua.diagnostics.disable\" : [
\"unused-local\",
\"lowercase-global\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-enable t
"Enable diagnostics."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-globals nil
"Defined global variables.
```json
\"Lua.diagnostics.globals\" : [
\"GLOBAL1\",
\"GLOBAL2\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-needed-file-status nil
"If you want to check only opened files, choice Opened; else choice Any.
```json
\"Lua.diagnostics.neededFileStatus\" : {
\"ambiguity-1\" : \"Any\",
\"circle-doc-class\" : \"Opened\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-severity nil
"Modified diagnostic severity.
```json
\"Lua.diagnostics.severity\" : {
\"redefined-local\" : \"Warning\",
\"emmy-lua\" : \"Hint\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-delay 0
"Latency (milliseconds) for workspace diagnostics. When you start the
workspace, or edit any file, the entire workspace will be re-diagnosed in the
background. Set to negative to disable workspace diagnostics."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-rate 100
"Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage,
but also reduces the speed of workspace diagnostics. The diagnosis of the file
you are currently editing is always done at full speed and is not affected by
this setting."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-enable nil
"Enable hint."
:type 'boolean
:package-version '(lsp-mmode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-name t
"Hint parameter name when the parameter called is literal."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-type t
"Show type hints at the parameter of the function."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-set-type nil
"Hint type at assignment operation."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-enable t
"Enable hover."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-field-infer 3000
"When hovering to view a table, type infer will be performed for each field.
When the accumulated time of type infer reaches the set value (MS), the type
infer of subsequent fields will be skipped."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-preview-fields 100
"When hovering to view a table, limits the maximum number of previews for
fields."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-number t
"Hover to view numeric content (only if literal is not decimal)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string t
"Hover to view the contents of a string (only if the literal contains an
escape character)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string-max 1000
"The maximum length of a hover to view the contents of a string."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-intelli-sense-search-depth 0
"Set the search depth for IntelliSense. Increasing this value increases
accuracy, but decreases performance. Different workspace have different
tolerance for this setting. Please adjust it to the appropriate value."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-file-encoding "utf8"
"File encoding. The 'ansi' option is only available under the 'Windows'
platform."
:type '(choice (:tag "utf8" "ansi"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-nonstandard-symbol nil
"Supports non-standard symbols. Make sure that your runtime environment
supports these symbols."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-path
["?.lua" "?/init.lua" "?/?.lua"]
"`package.path`."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-plugin nil
"(Proposed) Plugin path. Default is `.vscode/lua/plugin.lua`"
:type 'file
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-special nil
"The custom global variables are regarded as some special built-in variables,
and the language server will provide special support.
```json
\"Lua.runtime.special\" : {
\"include\" : \"require\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-unicode-name nil
"Allows Unicode characters in name."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-version "Lua 5.4"
"Lua runtime version."
:type '(choice (:tag "Lua 5.1" "Lua 5.2" "Lua 5.3" "Lua 5.4" "LuaJIT"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-signature-help-enable t
"Enable signature help."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-telemetry-enable nil
"Enable telemetry to send your editor information and error logs over the
network."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-progress-bar t
"Show progress bar in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-status-bar t
"Show extension status in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-dir
[".vscode"]
"Ignored directories (Use `.gitignore` grammar).
```json
\"Lua.workspace.ignoreDir\" : [
\"temp/*.*\",
\"!temp/*.lua\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-submodules t
"Ignore submodules."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-library nil
"Load external library.
This feature can load external Lua files, which can be used for definition,
automatic completion and other functions. Note that the language server does
not monitor changes in external files and needs to restart if the external
files are modified. The following example shows loaded files in `C:/lua`
and `../lib` ,exclude `../lib/temp`.
```json
\"Lua.workspace.library\": {
\"C:/lua\": true,
\"../lib\": [
\"temp/*\"
]
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-max-preload 1000
"Max preloaded files."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-preload-file-size 100
"Skip files larger than this value (KB) when preloading."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-use-git-ignore t
"Ignore files list in `.gitignore` ."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-associations nil
"Files.associations."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-exclude nil
"Files.exclude."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(lsp-register-custom-settings
'(("files.associations" lsp-lua-files-associations t)
("files.exclude" lsp-lua-files-exclude t)
("Lua.workspace.useGitIgnore" lsp-lua-workspace-use-git-ignore t)
("Lua.workspace.preloadFileSize" lsp-lua-workspace-preload-file-size)
("Lua.workspace.maxPreload" lsp-lua-workspace-max-preload)
("Lua.workspace.library" lsp-lua-workspace-library)
("Lua.workspace.ignoreSubmodules" lsp-lua-workspace-ignore-submodules t)
("Lua.workspace.ignoreDir" lsp-lua-workspace-ignore-dir)
("Lua.window.statusBar" lsp-lua-window-status-bar t)
("Lua.window.progressBar" lsp-lua-window-progress-bar t)
("Lua.telemetry.enable" lsp-lua-telemetry-enable t)
("Lua.signatureHelp.enable" lsp-lua-signature-help-enable t)
("Lua.runtime.version" lsp-lua-runtime-version)
("Lua.runtime.unicodeName" lsp-lua-runtime-unicode-name nil)
("Lua.runtime.special" lsp-lua-runtime-special)
("Lua.runtime.plugin" lsp-lua-runtime-plugin)
("Lua.runtime.path" lsp-lua-runtime-path)
("Lua.runtime.nonstandardSymbol" lsp-lua-runtime-nonstandard-symbol)
("Lua.runtime.fileEncoding" lsp-lua-runtime-file-encoding)
("Lua.intelliSense.searchDepth" lsp-lua-intelli-sense-search-depth)
("Lua.hover.viewStringMax" lsp-lua-hover-view-string-max)
("Lua.hover.viewString" lsp-lua-hover-view-string t)
("Lua.hover.viewNumber" lsp-lua-hover-view-number t)
("Lua.hover.previewFields" lsp-lua-hover-preview-fields)
("Lua.hover.fieldInfer" lsp-lua-hover-field-infer)
("Lua.hover.enable" lsp-lua-hover-enable t)
("Lua.hint.setType" lsp-lua-hint-set-type nil)
("Lua.hint.paramType" lsp-lua-hint-param-type t)
("Lua.hint.paramName" lsp-lua-hint-param-name t)
("Lua.hint.enable" lsp-lua-hint-enable t)
("Lua.diagnostics.workspaceRate" lsp-lua-diagnostics-workspace-rate)
("Lua.diagnostics.workspaceDelay" lsp-lua-diagnostics-workspace-delay)
("Lua.diagnostics.severity" lsp-lua-diagnostics-severity)
("Lua.diagnostics.neededFileStatus" lsp-lua-diagnostics-needed-file-status)
("Lua.diagnostics.globals" lsp-lua-diagnostics-globals)
("Lua.diagnostics.enable" lsp-lua-diagnostics-enable t)
("Lua.diagnostics.disable" lsp-lua-diagnostics-disable)
("Lua.develop.enable" lsp-lua-develop-enable t)
("Lua.develop.debuggerWait" lsp-lua-develop-debugger-wait t)
("Lua.develop.debuggerPort" lsp-lua-develop-debugger-port)
("Lua.completion.workspaceWord" lsp-lua-completion-workspace-word t)
("Lua.completion.keywordSnippet" lsp-lua-completion-keyword-snippet)
("Lua.completion.enable" lsp-lua-completion-enable t)
("Lua.completion.displayContext" lsp-lua-completion-display-context)
("Lua.completion.callSnippet" lsp-lua-completion-call-snippet)
("Lua.color.mode" lsp-lua-color-mode)))
(defun lsp-lua-language-server-install (client callback error-callback update?)
"Download the latest version of lua-language-server and extract it to
`lsp-lua-language-server-install-dir'."
(ignore client update?)
(let ((store-path (expand-file-name "vs-lua" lsp-clients-lua-language-server-install-dir)))
(lsp-download-install
(lambda (&rest _)
(set-file-modes lsp-clients-lua-language-server-bin #o0700)
(funcall callback))
error-callback
:url (lsp-vscode-extension-url "sumneko" "lua" "1.17.4")
:store-path store-path
:decompress :zip)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-lua-language-server-command
`(,lsp-clients-lua-language-server-bin
,@lsp-clients-lua-language-server-args
,lsp-clients-lua-language-server-main-location)))
#'lsp-clients-lua-language-server-test)
:major-modes '(lua-mode)
:priority -2
:server-id 'lua-language-server
:download-server-fn #'lsp-lua-language-server-install))
;;; lua-lsp
(defgroup lsp-lua-lsp nil
"Lua LSP client, provided by the Lua-Lsp."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/Alloyed/lua-lsp"))
(defcustom lsp-clients-luarocks-bin-dir (f-join (getenv "HOME") ".luarocks/bin/")
"LuaRocks bin directory."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-lsp-server-install-dir nil
"Installation directory for Lua-Lsp Language Server."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'file)
(defun lsp-clients-lua-lsp-test ()
"Test Lua-lsp language server files."
(and (f-exists? lsp-clients-lua-lsp-server-install-dir)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda ()
(or lsp-clients-lua-lsp-server-install-dir
(f-join lsp-clients-luarocks-bin-dir "lua-lsp")))
#'lsp-clients-lua-lsp-test)
:major-modes '(lua-mode)
:priority -3
:server-id 'lsp-lua-lsp))
(lsp-consistency-check lsp-lua)
(provide 'lsp-lua)
;;; lsp-lua.el ends here
| true | ;;; lsp-lua.el --- description -*- lexical-binding: t; -*-
;; Copyright (C) 2020 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords:
;; 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 3 of the License, 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, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; LSP Clients for the Lua Programming Language
;;; Code:
(require 'lsp-mode)
(require 'f)
(require 'files)
(defgroup lsp-emmy-lua nil
"Lua LSP client, provided by the EmmyLua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/EmmyLua/EmmyLua-LanguageServer"))
(defcustom lsp-clients-emmy-lua-java-path "java"
"Java Runtime binary location."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-jar-path (f-join lsp-server-install-dir "EmmyLua-LS-all.jar")
"Emmy Lua language server jar file."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-emmy-lua-args '("-jar")
"Arguments to the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-emmy-lua-command nil
"Final command to call the Lua Language server."
:group 'lsp-emmy-lua
:version "7.1"
:risky t
:type '(repeat string))
(defun lsp-clients-emmy-lua-test ()
"Test the Emmy Lua binaries and files."
(and (executable-find lsp-clients-emmy-lua-java-path)
(f-exists? lsp-clients-emmy-lua-jar-path)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-emmy-lua-command
`(,lsp-clients-emmy-lua-java-path
,@lsp-clients-emmy-lua-args
,lsp-clients-emmy-lua-jar-path)))
#'lsp-clients-emmy-lua-test)
:major-modes '(lua-mode)
:server-id 'emmy-lua
:priority -1
:notification-handlers (lsp-ht ("emmy/progressReport" #'ignore))))
;;; lua-language-server
(defgroup lsp-lua-language-server nil
"Lua LSP client, provided by the Lua Language Server."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/sumneko/lua-language-server"))
(defcustom lsp-clients-lua-language-server-install-dir (f-join lsp-server-install-dir "lua-language-server/")
"Installation directory for Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-language-server-bin
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/bin/"
(pcase system-type
('gnu/linux "Linux/lua-language-server")
('darwin "macOS/lua-language-server")
('windows-nt "Windows/lua-language-server.exe")
(_ "Linux/lua-language-server")))
"Location of Lua Language Server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-main-location
(f-join lsp-clients-lua-language-server-install-dir
"extension/server/main.lua")
"Location of Lua Language Server main.lua."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type 'file)
(defcustom lsp-clients-lua-language-server-args '("-E")
"Arguments to run the Lua Language server."
:group 'lsp-lua-language-server
:version "7.1"
:risky t
:type '(repeat string))
(defcustom lsp-clients-lua-language-server-command nil
"Command to start Lua Language server."
:group 'lsp-lua-language-server
:type '(repeat string))
(defun lsp-clients-lua-language-server-test ()
"Test Lua language server binaries and files."
(and (f-exists? lsp-clients-lua-language-server-main-location)
(f-exists? lsp-clients-lua-language-server-bin)))
(defcustom lsp-lua-color-mode "Semantic"
"Color mode."
:type '(choice (:tag "Grammar" "Semantic"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-call-snippet "Disable"
"Shows function call snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-display-context 6
"Previewing the relevant code snippet of the suggestion may help you
understand the usage of the suggestion.
The number set indicates the number of intercepted lines in the code
fragment. If it is set to `0`, this feature can be disabled."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-enable t
"Enable completion."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-keyword-snippet "Replace"
"Shows keyword syntax snippets."
:type '(choice (:tag "Disable" "Both" "Replace"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-completion-workspace-word t
"Show words within the workspace."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-port 11412
"Listen port of debugger."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-debugger-wait nil
"Suspend before debugger connects."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-develop-enable nil
"Developer mode. Do not enable, performance will be affected."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-disable nil
"Disabled diagnostic (Use code in hover brackets).
```json
\"Lua.diagnostics.disable\" : [
\"unused-local\",
\"lowercase-global\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-enable t
"Enable diagnostics."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-globals nil
"Defined global variables.
```json
\"Lua.diagnostics.globals\" : [
\"GLOBAL1\",
\"GLOBAL2\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-needed-file-status nil
"If you want to check only opened files, choice Opened; else choice Any.
```json
\"Lua.diagnostics.neededFileStatus\" : {
\"ambiguity-1\" : \"Any\",
\"circle-doc-class\" : \"Opened\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-severity nil
"Modified diagnostic severity.
```json
\"Lua.diagnostics.severity\" : {
\"redefined-local\" : \"Warning\",
\"emmy-lua\" : \"Hint\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-delay 0
"Latency (milliseconds) for workspace diagnostics. When you start the
workspace, or edit any file, the entire workspace will be re-diagnosed in the
background. Set to negative to disable workspace diagnostics."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-diagnostics-workspace-rate 100
"Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage,
but also reduces the speed of workspace diagnostics. The diagnosis of the file
you are currently editing is always done at full speed and is not affected by
this setting."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-enable nil
"Enable hint."
:type 'boolean
:package-version '(lsp-mmode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-name t
"Hint parameter name when the parameter called is literal."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-param-type t
"Show type hints at the parameter of the function."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hint-set-type nil
"Hint type at assignment operation."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-enable t
"Enable hover."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-field-infer 3000
"When hovering to view a table, type infer will be performed for each field.
When the accumulated time of type infer reaches the set value (MS), the type
infer of subsequent fields will be skipped."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-preview-fields 100
"When hovering to view a table, limits the maximum number of previews for
fields."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-number t
"Hover to view numeric content (only if literal is not decimal)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string t
"Hover to view the contents of a string (only if the literal contains an
escape character)."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-hover-view-string-max 1000
"The maximum length of a hover to view the contents of a string."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-intelli-sense-search-depth 0
"Set the search depth for IntelliSense. Increasing this value increases
accuracy, but decreases performance. Different workspace have different
tolerance for this setting. Please adjust it to the appropriate value."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-file-encoding "utf8"
"File encoding. The 'ansi' option is only available under the 'Windows'
platform."
:type '(choice (:tag "utf8" "ansi"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-nonstandard-symbol nil
"Supports non-standard symbols. Make sure that your runtime environment
supports these symbols."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-path
["?.lua" "?/init.lua" "?/?.lua"]
"`package.path`."
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-plugin nil
"(Proposed) Plugin path. Default is `.vscode/lua/plugin.lua`"
:type 'file
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-special nil
"The custom global variables are regarded as some special built-in variables,
and the language server will provide special support.
```json
\"Lua.runtime.special\" : {
\"include\" : \"require\"
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-unicode-name nil
"Allows Unicode characters in name."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-runtime-version "Lua 5.4"
"Lua runtime version."
:type '(choice (:tag "Lua 5.1" "Lua 5.2" "Lua 5.3" "Lua 5.4" "LuaJIT"))
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-signature-help-enable t
"Enable signature help."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-telemetry-enable nil
"Enable telemetry to send your editor information and error logs over the
network."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-progress-bar t
"Show progress bar in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-window-status-bar t
"Show extension status in status bar."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-dir
[".vscode"]
"Ignored directories (Use `.gitignore` grammar).
```json
\"Lua.workspace.ignoreDir\" : [
\"temp/*.*\",
\"!temp/*.lua\"
]
```"
:type 'lsp-string-vector
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-ignore-submodules t
"Ignore submodules."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-library nil
"Load external library.
This feature can load external Lua files, which can be used for definition,
automatic completion and other functions. Note that the language server does
not monitor changes in external files and needs to restart if the external
files are modified. The following example shows loaded files in `C:/lua`
and `../lib` ,exclude `../lib/temp`.
```json
\"Lua.workspace.library\": {
\"C:/lua\": true,
\"../lib\": [
\"temp/*\"
]
}
```"
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-max-preload 1000
"Max preloaded files."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-preload-file-size 100
"Skip files larger than this value (KB) when preloading."
:type 'number
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-workspace-use-git-ignore t
"Ignore files list in `.gitignore` ."
:type 'boolean
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-associations nil
"Files.associations."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(defcustom lsp-lua-files-exclude nil
"Files.exclude."
:type 'alist
:package-version '(lsp-mode . "7.1")
:group 'lsp-lua-language-server)
(lsp-register-custom-settings
'(("files.associations" lsp-lua-files-associations t)
("files.exclude" lsp-lua-files-exclude t)
("Lua.workspace.useGitIgnore" lsp-lua-workspace-use-git-ignore t)
("Lua.workspace.preloadFileSize" lsp-lua-workspace-preload-file-size)
("Lua.workspace.maxPreload" lsp-lua-workspace-max-preload)
("Lua.workspace.library" lsp-lua-workspace-library)
("Lua.workspace.ignoreSubmodules" lsp-lua-workspace-ignore-submodules t)
("Lua.workspace.ignoreDir" lsp-lua-workspace-ignore-dir)
("Lua.window.statusBar" lsp-lua-window-status-bar t)
("Lua.window.progressBar" lsp-lua-window-progress-bar t)
("Lua.telemetry.enable" lsp-lua-telemetry-enable t)
("Lua.signatureHelp.enable" lsp-lua-signature-help-enable t)
("Lua.runtime.version" lsp-lua-runtime-version)
("Lua.runtime.unicodeName" lsp-lua-runtime-unicode-name nil)
("Lua.runtime.special" lsp-lua-runtime-special)
("Lua.runtime.plugin" lsp-lua-runtime-plugin)
("Lua.runtime.path" lsp-lua-runtime-path)
("Lua.runtime.nonstandardSymbol" lsp-lua-runtime-nonstandard-symbol)
("Lua.runtime.fileEncoding" lsp-lua-runtime-file-encoding)
("Lua.intelliSense.searchDepth" lsp-lua-intelli-sense-search-depth)
("Lua.hover.viewStringMax" lsp-lua-hover-view-string-max)
("Lua.hover.viewString" lsp-lua-hover-view-string t)
("Lua.hover.viewNumber" lsp-lua-hover-view-number t)
("Lua.hover.previewFields" lsp-lua-hover-preview-fields)
("Lua.hover.fieldInfer" lsp-lua-hover-field-infer)
("Lua.hover.enable" lsp-lua-hover-enable t)
("Lua.hint.setType" lsp-lua-hint-set-type nil)
("Lua.hint.paramType" lsp-lua-hint-param-type t)
("Lua.hint.paramName" lsp-lua-hint-param-name t)
("Lua.hint.enable" lsp-lua-hint-enable t)
("Lua.diagnostics.workspaceRate" lsp-lua-diagnostics-workspace-rate)
("Lua.diagnostics.workspaceDelay" lsp-lua-diagnostics-workspace-delay)
("Lua.diagnostics.severity" lsp-lua-diagnostics-severity)
("Lua.diagnostics.neededFileStatus" lsp-lua-diagnostics-needed-file-status)
("Lua.diagnostics.globals" lsp-lua-diagnostics-globals)
("Lua.diagnostics.enable" lsp-lua-diagnostics-enable t)
("Lua.diagnostics.disable" lsp-lua-diagnostics-disable)
("Lua.develop.enable" lsp-lua-develop-enable t)
("Lua.develop.debuggerWait" lsp-lua-develop-debugger-wait t)
("Lua.develop.debuggerPort" lsp-lua-develop-debugger-port)
("Lua.completion.workspaceWord" lsp-lua-completion-workspace-word t)
("Lua.completion.keywordSnippet" lsp-lua-completion-keyword-snippet)
("Lua.completion.enable" lsp-lua-completion-enable t)
("Lua.completion.displayContext" lsp-lua-completion-display-context)
("Lua.completion.callSnippet" lsp-lua-completion-call-snippet)
("Lua.color.mode" lsp-lua-color-mode)))
(defun lsp-lua-language-server-install (client callback error-callback update?)
"Download the latest version of lua-language-server and extract it to
`lsp-lua-language-server-install-dir'."
(ignore client update?)
(let ((store-path (expand-file-name "vs-lua" lsp-clients-lua-language-server-install-dir)))
(lsp-download-install
(lambda (&rest _)
(set-file-modes lsp-clients-lua-language-server-bin #o0700)
(funcall callback))
error-callback
:url (lsp-vscode-extension-url "sumneko" "lua" "1.17.4")
:store-path store-path
:decompress :zip)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda () (or lsp-clients-lua-language-server-command
`(,lsp-clients-lua-language-server-bin
,@lsp-clients-lua-language-server-args
,lsp-clients-lua-language-server-main-location)))
#'lsp-clients-lua-language-server-test)
:major-modes '(lua-mode)
:priority -2
:server-id 'lua-language-server
:download-server-fn #'lsp-lua-language-server-install))
;;; lua-lsp
(defgroup lsp-lua-lsp nil
"Lua LSP client, provided by the Lua-Lsp."
:group 'lsp-mode
:version "7.1"
:link '(url-link "https://github.com/Alloyed/lua-lsp"))
(defcustom lsp-clients-luarocks-bin-dir (f-join (getenv "HOME") ".luarocks/bin/")
"LuaRocks bin directory."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'directory)
(defcustom lsp-clients-lua-lsp-server-install-dir nil
"Installation directory for Lua-Lsp Language Server."
:group 'lsp-lua-lsp
:version "7.1"
:risky t
:type 'file)
(defun lsp-clients-lua-lsp-test ()
"Test Lua-lsp language server files."
(and (f-exists? lsp-clients-lua-lsp-server-install-dir)))
(lsp-register-client
(make-lsp-client
:new-connection (lsp-stdio-connection (lambda ()
(or lsp-clients-lua-lsp-server-install-dir
(f-join lsp-clients-luarocks-bin-dir "lua-lsp")))
#'lsp-clients-lua-lsp-test)
:major-modes '(lua-mode)
:priority -3
:server-id 'lsp-lua-lsp))
(lsp-consistency-check lsp-lua)
(provide 'lsp-lua)
;;; lsp-lua.el ends here
|
[
{
"context": " -*- lexical-binding: t -*-\n\n;; Copyright (C) 2020 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <mail@ambrevar.xyz>\n",
"end": 130,
"score": 0.9998548626899719,
"start": 114,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": ";; Copyright (C) 2020 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <mail@ambrevar.xyz>\n;; Maintainer: James Nguyen <",
"end": 159,
"score": 0.9998845458030701,
"start": 143,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": "20 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <mail@ambrevar.xyz>\n;; Maintainer: James Nguyen <james@jojojames.com",
"end": 178,
"score": 0.9999309778213501,
"start": 161,
"tag": "EMAIL",
"value": "mail@ambrevar.xyz"
},
{
"context": "ierre Neidhardt <mail@ambrevar.xyz>\n;; Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <mail@a",
"end": 207,
"score": 0.9998971223831177,
"start": 195,
"tag": "NAME",
"value": "James Nguyen"
},
{
"context": " <mail@ambrevar.xyz>\n;; Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <mail@ambrevar.xyz>\n;; URL: ",
"end": 228,
"score": 0.9999300837516785,
"start": 209,
"tag": "EMAIL",
"value": "james@jojojames.com"
},
{
"context": " Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <mail@ambrevar.xyz>\n;; URL: https://github.com/em",
"end": 249,
"score": 0.9998797178268433,
"start": 233,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": "Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <mail@ambrevar.xyz>\n;; URL: https://github.com/emacs-evil/evil-colle",
"end": 268,
"score": 0.999930202960968,
"start": 251,
"tag": "EMAIL",
"value": "mail@ambrevar.xyz"
}
] | gaming/dotfiles/.emacs.d/elpa/evil-collection-20210602.1559/modes/trashed/evil-collection-trashed.el | johannes-qvarford/home-env | 0 | ;;; evil-collection-trashed.el --- Evil bindings for trashed.el -*- lexical-binding: t -*-
;; Copyright (C) 2020 Pierre Neidhardt
;; Author: Pierre Neidhardt <mail@ambrevar.xyz>
;; Maintainer: James Nguyen <james@jojojames.com>
;; Pierre Neidhardt <mail@ambrevar.xyz>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.3
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, files, convenience, tools
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for `trashed'.
;;; Code:
(require 'evil-collection)
(require 'trashed nil t)
(defconst evil-collection-trashed-maps '(trashed-mode-map))
;;;###autoload
(defun evil-collection-trashed-setup ()
"Set up `evil' bindings for `trashed'."
(evil-collection-set-readonly-bindings 'trashed-mode-map)
(evil-collection-define-key 'normal 'trashed-mode-map
;; motion
(kbd "SPC") 'scroll-up-command
(kbd "S-SPC") 'scroll-down-command
(kbd "<tab>") 'trashed-forward-column
(kbd "<backtab>") 'trashed-backward-column
(kbd "RET") 'trashed-find-file
(kbd "S-RET") 'trashed-find-file-other-window
(kbd "go") 'trashed-find-file-other-window
(kbd "gO") 'trashed-display-file
(kbd "gw") 'trashed-browse-url-of-file
(kbd "M-RET") 'trashed-display-file
"S" 'tabulated-list-sort
"m" 'trashed-mark
"M" 'trashed-mark-all
"u" 'trashed-unmark
"U" 'trashed-unmark-all
"~" 'trashed-toggle-marks
"$ m" 'trashed-mark-files-by-date
"$ u" 'trashed-unmark-files-by-date
"$ d" 'trashed-flag-delete-files-by-date
"$ r" 'trashed-flag-restore-files-by-date
"% m" 'trashed-mark-files-regexp
"% u" 'trashed-unmark-files-regexp
"% d" 'trashed-flag-delete-files-regexp
"% r" 'trashed-flag-restore-files-regexp
"d" 'trashed-flag-delete
"r" 'trashed-flag-restore
"zb" 'trashed-flag-backup-files
"za" 'trashed-flag-auto-save-files
"x" 'trashed-do-execute
"D" 'trashed-do-delete
"R" 'trashed-do-restore
"v" 'trashed-view-file
"g?" 'describe-mode
"gr" 'revert-buffer))
(provide 'evil-collection-trashed)
;;; evil-collection-trashed.el ends here
| 44044 | ;;; evil-collection-trashed.el --- Evil bindings for trashed.el -*- lexical-binding: t -*-
;; Copyright (C) 2020 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.3
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, files, convenience, tools
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for `trashed'.
;;; Code:
(require 'evil-collection)
(require 'trashed nil t)
(defconst evil-collection-trashed-maps '(trashed-mode-map))
;;;###autoload
(defun evil-collection-trashed-setup ()
"Set up `evil' bindings for `trashed'."
(evil-collection-set-readonly-bindings 'trashed-mode-map)
(evil-collection-define-key 'normal 'trashed-mode-map
;; motion
(kbd "SPC") 'scroll-up-command
(kbd "S-SPC") 'scroll-down-command
(kbd "<tab>") 'trashed-forward-column
(kbd "<backtab>") 'trashed-backward-column
(kbd "RET") 'trashed-find-file
(kbd "S-RET") 'trashed-find-file-other-window
(kbd "go") 'trashed-find-file-other-window
(kbd "gO") 'trashed-display-file
(kbd "gw") 'trashed-browse-url-of-file
(kbd "M-RET") 'trashed-display-file
"S" 'tabulated-list-sort
"m" 'trashed-mark
"M" 'trashed-mark-all
"u" 'trashed-unmark
"U" 'trashed-unmark-all
"~" 'trashed-toggle-marks
"$ m" 'trashed-mark-files-by-date
"$ u" 'trashed-unmark-files-by-date
"$ d" 'trashed-flag-delete-files-by-date
"$ r" 'trashed-flag-restore-files-by-date
"% m" 'trashed-mark-files-regexp
"% u" 'trashed-unmark-files-regexp
"% d" 'trashed-flag-delete-files-regexp
"% r" 'trashed-flag-restore-files-regexp
"d" 'trashed-flag-delete
"r" 'trashed-flag-restore
"zb" 'trashed-flag-backup-files
"za" 'trashed-flag-auto-save-files
"x" 'trashed-do-execute
"D" 'trashed-do-delete
"R" 'trashed-do-restore
"v" 'trashed-view-file
"g?" 'describe-mode
"gr" 'revert-buffer))
(provide 'evil-collection-trashed)
;;; evil-collection-trashed.el ends here
| true | ;;; evil-collection-trashed.el --- Evil bindings for trashed.el -*- lexical-binding: t -*-
;; Copyright (C) 2020 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.3
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, files, convenience, tools
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for `trashed'.
;;; Code:
(require 'evil-collection)
(require 'trashed nil t)
(defconst evil-collection-trashed-maps '(trashed-mode-map))
;;;###autoload
(defun evil-collection-trashed-setup ()
"Set up `evil' bindings for `trashed'."
(evil-collection-set-readonly-bindings 'trashed-mode-map)
(evil-collection-define-key 'normal 'trashed-mode-map
;; motion
(kbd "SPC") 'scroll-up-command
(kbd "S-SPC") 'scroll-down-command
(kbd "<tab>") 'trashed-forward-column
(kbd "<backtab>") 'trashed-backward-column
(kbd "RET") 'trashed-find-file
(kbd "S-RET") 'trashed-find-file-other-window
(kbd "go") 'trashed-find-file-other-window
(kbd "gO") 'trashed-display-file
(kbd "gw") 'trashed-browse-url-of-file
(kbd "M-RET") 'trashed-display-file
"S" 'tabulated-list-sort
"m" 'trashed-mark
"M" 'trashed-mark-all
"u" 'trashed-unmark
"U" 'trashed-unmark-all
"~" 'trashed-toggle-marks
"$ m" 'trashed-mark-files-by-date
"$ u" 'trashed-unmark-files-by-date
"$ d" 'trashed-flag-delete-files-by-date
"$ r" 'trashed-flag-restore-files-by-date
"% m" 'trashed-mark-files-regexp
"% u" 'trashed-unmark-files-regexp
"% d" 'trashed-flag-delete-files-regexp
"% r" 'trashed-flag-restore-files-regexp
"d" 'trashed-flag-delete
"r" 'trashed-flag-restore
"zb" 'trashed-flag-backup-files
"za" 'trashed-flag-auto-save-files
"x" 'trashed-do-execute
"D" 'trashed-do-delete
"R" 'trashed-do-restore
"v" 'trashed-view-file
"g?" 'describe-mode
"gr" 'revert-buffer))
(provide 'evil-collection-trashed)
;;; evil-collection-trashed.el ends here
|
[
{
"context": "s File for Spacemacs\n;;\n;; Copyright (c) 2012-2016 Sylvain Benner & Contributors\n;;\n;; Author: Muneeb Shaikh <munee",
"end": 107,
"score": 0.9998873472213745,
"start": 93,
"tag": "NAME",
"value": "Sylvain Benner"
},
{
"context": "2-2016 Sylvain Benner & Contributors\n;;\n;; Author: Muneeb Shaikh <muneeb@reversehack.in>\n;; URL: https://github.co",
"end": 150,
"score": 0.9999001622200012,
"start": 137,
"tag": "NAME",
"value": "Muneeb Shaikh"
},
{
"context": "enner & Contributors\n;;\n;; Author: Muneeb Shaikh <muneeb@reversehack.in>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;",
"end": 173,
"score": 0.999930739402771,
"start": 152,
"tag": "EMAIL",
"value": "muneeb@reversehack.in"
},
{
"context": "muneeb@reversehack.in>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;\n;; This file is not part of GNU Emac",
"end": 210,
"score": 0.9815692901611328,
"start": 202,
"tag": "USERNAME",
"value": "syl20bnr"
}
] | layers/+lang/javascript/funcs.el | lh83mail/emacs | 0 | ;;; funcs.el --- Javascript Layer functions File for Spacemacs
;;
;; Copyright (c) 2012-2016 Sylvain Benner & Contributors
;;
;; Author: Muneeb Shaikh <muneeb@reversehack.in>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;; tern
(defun spacemacs//set-tern-key-bindings (mode)
"Set the key bindings for tern and the given MODE."
(add-to-list (intern (format "spacemacs-jump-handlers-%S" mode))
'tern-find-definition)
(spacemacs/set-leader-keys-for-major-mode mode
"rrV" 'tern-rename-variable
"hd" 'tern-get-docs
"gG" 'tern-find-definition-by-name
(kbd "C-g") 'tern-pop-find-definition
"ht" 'tern-get-type))
(defun spacemacs//tern-detect ()
"Detect tern binary and warn if not found."
(let ((found (executable-find "tern")))
(unless found
(spacemacs-buffer/warning "tern binary not found!"))
found))
| 9877 | ;;; funcs.el --- Javascript Layer functions File for Spacemacs
;;
;; Copyright (c) 2012-2016 <NAME> & Contributors
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;; tern
(defun spacemacs//set-tern-key-bindings (mode)
"Set the key bindings for tern and the given MODE."
(add-to-list (intern (format "spacemacs-jump-handlers-%S" mode))
'tern-find-definition)
(spacemacs/set-leader-keys-for-major-mode mode
"rrV" 'tern-rename-variable
"hd" 'tern-get-docs
"gG" 'tern-find-definition-by-name
(kbd "C-g") 'tern-pop-find-definition
"ht" 'tern-get-type))
(defun spacemacs//tern-detect ()
"Detect tern binary and warn if not found."
(let ((found (executable-find "tern")))
(unless found
(spacemacs-buffer/warning "tern binary not found!"))
found))
| true | ;;; funcs.el --- Javascript Layer functions File for Spacemacs
;;
;; Copyright (c) 2012-2016 PI:NAME:<NAME>END_PI & Contributors
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
;; tern
(defun spacemacs//set-tern-key-bindings (mode)
"Set the key bindings for tern and the given MODE."
(add-to-list (intern (format "spacemacs-jump-handlers-%S" mode))
'tern-find-definition)
(spacemacs/set-leader-keys-for-major-mode mode
"rrV" 'tern-rename-variable
"hd" 'tern-get-docs
"gG" 'tern-find-definition-by-name
(kbd "C-g") 'tern-pop-find-definition
"ht" 'tern-get-type))
(defun spacemacs//tern-detect ()
"Detect tern binary and warn if not found."
(let ((found (executable-find "tern")))
(unless found
(spacemacs-buffer/warning "tern binary not found!"))
found))
|
[
{
"context": ";;;; Copyright (c) 2000, MITSUISHI Yutaka\n;;;; You may distribute this file under the terms",
"end": 41,
"score": 0.9994487166404724,
"start": 25,
"tag": "NAME",
"value": "MITSUISHI Yutaka"
},
{
"context": " Name: hilit19-for-lilfes-mode.el\n;;;; Author: MITSUISHI Yutaka (mitsuisi@is.s.u-tokyo.ac.jp)\n;;;; Date: 2000.",
"end": 193,
"score": 0.9998513460159302,
"start": 177,
"tag": "NAME",
"value": "MITSUISHI Yutaka"
},
{
"context": "or-lilfes-mode.el\n;;;; Author: MITSUISHI Yutaka (mitsuisi@is.s.u-tokyo.ac.jp)\n;;;; Date: 2000.08.30\n;;;; Purpose: hilit19 s",
"end": 222,
"score": 0.999933123588562,
"start": 195,
"tag": "EMAIL",
"value": "mitsuisi@is.s.u-tokyo.ac.jp"
}
] | ll/elisp/hilit19-for-lilfes-mode.el | mynlp/enju | 48 | ;;;; Copyright (c) 2000, MITSUISHI Yutaka
;;;; You may distribute this file under the terms of the Artistic License.
;;;;
;;;; Name: hilit19-for-lilfes-mode.el
;;;; Author: MITSUISHI Yutaka (mitsuisi@is.s.u-tokyo.ac.jp)
;;;; Date: 2000.08.30
;;;; Purpose: hilit19 setting for lilfes-mode
;;;;
(hilit-set-mode-patterns
'lilfes-mode
'(("/\\*" "\\*/" comment)
;;; ("\"[^\\\"]*\\(\\\\\\(.\\|\n\\)[^\\\"]*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\n\\)*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\\\\\n\\)*\\)*\"" nil string) ; Modified
("\"\\([^\"]\\|\n\\)*\"" nil string) ; Modified
("%.*$" nil comment)
("!" nil label)
("\\(:-\\|<-\\)" nil defun) ;; Modified
;;; ("[A-Z0-9_]+:" nil define) ;; Added
("[A-Za-z0-9_]+\\\\" nil define) ;; Added
("+ [A-Z0-9_,() ]*" nil define) ;; Added
("'[A-Z][A-Z0-9_]*'" nil define) ;; Added
("\\$[A-Za-z0-9_]+" nil crossref) ;; Added
;;; ("\\([A-Z]\\|[A-Z][A-Z0-9_]+\\)" nil crossref) ;; Added
("\\b\\(is\\|mod\\)\\b" nil keyword)
("\\(&\\|->\\|-->\\|;\\|==\\|\\\\==\\|=<\\|>=\\|<\\|>\\|=\\|\\\\=\\|=:=\\|=\\\.\\\.\\|\\\\\\\+\\)" nil decl)
("\\(\\\[\\||\\|\\\]\\)" nil include)))
| 26949 | ;;;; Copyright (c) 2000, <NAME>
;;;; You may distribute this file under the terms of the Artistic License.
;;;;
;;;; Name: hilit19-for-lilfes-mode.el
;;;; Author: <NAME> (<EMAIL>)
;;;; Date: 2000.08.30
;;;; Purpose: hilit19 setting for lilfes-mode
;;;;
(hilit-set-mode-patterns
'lilfes-mode
'(("/\\*" "\\*/" comment)
;;; ("\"[^\\\"]*\\(\\\\\\(.\\|\n\\)[^\\\"]*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\n\\)*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\\\\\n\\)*\\)*\"" nil string) ; Modified
("\"\\([^\"]\\|\n\\)*\"" nil string) ; Modified
("%.*$" nil comment)
("!" nil label)
("\\(:-\\|<-\\)" nil defun) ;; Modified
;;; ("[A-Z0-9_]+:" nil define) ;; Added
("[A-Za-z0-9_]+\\\\" nil define) ;; Added
("+ [A-Z0-9_,() ]*" nil define) ;; Added
("'[A-Z][A-Z0-9_]*'" nil define) ;; Added
("\\$[A-Za-z0-9_]+" nil crossref) ;; Added
;;; ("\\([A-Z]\\|[A-Z][A-Z0-9_]+\\)" nil crossref) ;; Added
("\\b\\(is\\|mod\\)\\b" nil keyword)
("\\(&\\|->\\|-->\\|;\\|==\\|\\\\==\\|=<\\|>=\\|<\\|>\\|=\\|\\\\=\\|=:=\\|=\\\.\\\.\\|\\\\\\\+\\)" nil decl)
("\\(\\\[\\||\\|\\\]\\)" nil include)))
| true | ;;;; Copyright (c) 2000, PI:NAME:<NAME>END_PI
;;;; You may distribute this file under the terms of the Artistic License.
;;;;
;;;; Name: hilit19-for-lilfes-mode.el
;;;; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;; Date: 2000.08.30
;;;; Purpose: hilit19 setting for lilfes-mode
;;;;
(hilit-set-mode-patterns
'lilfes-mode
'(("/\\*" "\\*/" comment)
;;; ("\"[^\\\"]*\\(\\\\\\(.\\|\n\\)[^\\\"]*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\n\\)*\\)*\"" nil string)
;;; ("\"\\(\\\\\\(.\\|\\\\\n\\)*\\)*\"" nil string) ; Modified
("\"\\([^\"]\\|\n\\)*\"" nil string) ; Modified
("%.*$" nil comment)
("!" nil label)
("\\(:-\\|<-\\)" nil defun) ;; Modified
;;; ("[A-Z0-9_]+:" nil define) ;; Added
("[A-Za-z0-9_]+\\\\" nil define) ;; Added
("+ [A-Z0-9_,() ]*" nil define) ;; Added
("'[A-Z][A-Z0-9_]*'" nil define) ;; Added
("\\$[A-Za-z0-9_]+" nil crossref) ;; Added
;;; ("\\([A-Z]\\|[A-Z][A-Z0-9_]+\\)" nil crossref) ;; Added
("\\b\\(is\\|mod\\)\\b" nil keyword)
("\\(&\\|->\\|-->\\|;\\|==\\|\\\\==\\|=<\\|>=\\|<\\|>\\|=\\|\\\\=\\|=:=\\|=\\\.\\\.\\|\\\\\\\+\\)" nil decl)
("\\(\\\[\\||\\|\\\]\\)" nil include)))
|
[
{
"context": "ttings module entrypoint\n;;\n;; Copyright (C) 2016, Skyler.\n;; MIT License.\n\n(defvar varan-active-settings\n ",
"end": 75,
"score": 0.9579439163208008,
"start": 69,
"tag": "NAME",
"value": "Skyler"
}
] | settings/index.el | skylerlee/emacs.d | 1 | ;;; index.el -- settings module entrypoint
;;
;; Copyright (C) 2016, Skyler.
;; MIT License.
(defvar varan-active-settings
'(keybinding
completion
interaction
snippet
enclosure
linter
filetree
modeline
vcs
misc))
(varan/load-code varan-active-settings)
| 49574 | ;;; index.el -- settings module entrypoint
;;
;; Copyright (C) 2016, <NAME>.
;; MIT License.
(defvar varan-active-settings
'(keybinding
completion
interaction
snippet
enclosure
linter
filetree
modeline
vcs
misc))
(varan/load-code varan-active-settings)
| true | ;;; index.el -- settings module entrypoint
;;
;; Copyright (C) 2016, PI:NAME:<NAME>END_PI.
;; MIT License.
(defvar varan-active-settings
'(keybinding
completion
interaction
snippet
enclosure
linter
filetree
modeline
vcs
misc))
(varan/load-code varan-active-settings)
|
[
{
"context": "70720.1802\" \"Memoization functions\" 'nil :commit \"636defefa9168f90bce6fc27431352ac7d01a890\" :url \"https://github.com/skeeto/emacs-memoize\")\n",
"end": 151,
"score": 0.6318969130516052,
"start": 111,
"tag": "PASSWORD",
"value": "636defefa9168f90bce6fc27431352ac7d01a890"
},
{
"context": "ce6fc27431352ac7d01a890\" :url \"https://github.com/skeeto/emacs-memoize\")\n",
"end": 184,
"score": 0.9982892870903015,
"start": 178,
"tag": "USERNAME",
"value": "skeeto"
}
] | _archive/.emacs.d.old/elpa/memoize-20170720.1802/memoize-pkg.el | ahmedalsudani/config | 11 | ;;; -*- no-byte-compile: t -*-
(define-package "memoize" "20170720.1802" "Memoization functions" 'nil :commit "636defefa9168f90bce6fc27431352ac7d01a890" :url "https://github.com/skeeto/emacs-memoize")
| 26056 | ;;; -*- no-byte-compile: t -*-
(define-package "memoize" "20170720.1802" "Memoization functions" 'nil :commit "<PASSWORD>" :url "https://github.com/skeeto/emacs-memoize")
| true | ;;; -*- no-byte-compile: t -*-
(define-package "memoize" "20170720.1802" "Memoization functions" 'nil :commit "PI:PASSWORD:<PASSWORD>END_PI" :url "https://github.com/skeeto/emacs-memoize")
|
[
{
"context": "s File for Spacemacs\n;;\n;; Copyright (c) 2012-2017 Sylvain Benner & Contributors\n;;\n;; Author: Ryan L. Bell\n;; URL:",
"end": 109,
"score": 0.9998844265937805,
"start": 95,
"tag": "NAME",
"value": "Sylvain Benner"
},
{
"context": "2-2017 Sylvain Benner & Contributors\n;;\n;; Author: Ryan L. Bell\n;; URL: https://github.com/syl20bnr/spacemacs\n;;\n",
"end": 151,
"score": 0.9998869299888611,
"start": 139,
"tag": "NAME",
"value": "Ryan L. Bell"
},
{
"context": "; Author: Ryan L. Bell\n;; URL: https://github.com/syl20bnr/spacemacs\n;;\n;; This file is not part of GNU Emac",
"end": 187,
"score": 0.9774524569511414,
"start": 179,
"tag": "USERNAME",
"value": "syl20bnr"
}
] | emacs.d/layers/+lang/purescript/packages.el | JonnyWalker81/dotfiles | 0 | ;;; packages.el --- Purescript Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2017 Sylvain Benner & Contributors
;;
;; Author: Ryan L. Bell
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq purescript-packages
'(company
flycheck
purescript-mode
psci
psc-ide
popwin))
(defun purescript/post-init-company ()
(when (configuration-layer/package-used-p 'psc-ide)
(spacemacs|add-company-backends
:backends company-psc-ide-backend
:modes purescript-mode)))
(defun purescript/post-init-flycheck ()
(spacemacs/enable-flycheck 'purescript-mode))
(defun purescript/init-purescript-mode ()
(use-package purescript-mode
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'turn-on-purescript-indentation)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"i=" 'purescript-mode-format-imports
"i`" 'purescript-navigate-imports-return
"ia" 'purescript-align-imports
"in" 'purescript-navigate-imports))))
(defun purescript/init-psci ()
(use-package psci
:defer t
:init
(progn
(spacemacs/register-repl 'psci 'psci "purescript")
(add-hook 'purescript-mode-hook 'inferior-psci-mode)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"'" 'psci
"sb" 'psci/load-current-file!
"si" 'psci
"sm" 'psci/load-module!
"sp" 'psci/load-project-modules!))))
(defun purescript/init-psc-ide ()
(use-package psc-ide
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'psc-ide-mode)
(spacemacs/declare-prefix-for-mode 'purescript-mode "mm" "purescript/psc-ide")
(customize-set-variable 'psc-ide-add-import-on-completion purescript-add-import-on-completion)
(customize-set-variable 'psc-ide-rebuild-on-save purescript-enable-rebuild-on-save)
(add-to-list 'spacemacs-jump-handlers-purescript-mode 'psc-ide-goto-definition)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"mt" 'psc-ide-add-clause
"mcs" 'psc-ide-case-split
"ms" 'psc-ide-server-start
"mb" 'psc-ide-rebuild
"mq" 'psc-ide-server-quit
"ml" 'psc-ide-load-all
"mL" 'psc-ide-load-module
"mia" 'psc-ide-add-import
"mis" 'psc-ide-flycheck-insert-suggestion
"ht" 'psc-ide-show-type))))
(defun purescript/pre-init-popwin ()
(spacemacs|use-package-add-hook popwin
:post-config
(push '("*psc-ide-rebuild*" :tail t :noselect t) popwin:special-display-config)))
| 11275 | ;;; packages.el --- Purescript Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2017 <NAME> & Contributors
;;
;; Author: <NAME>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq purescript-packages
'(company
flycheck
purescript-mode
psci
psc-ide
popwin))
(defun purescript/post-init-company ()
(when (configuration-layer/package-used-p 'psc-ide)
(spacemacs|add-company-backends
:backends company-psc-ide-backend
:modes purescript-mode)))
(defun purescript/post-init-flycheck ()
(spacemacs/enable-flycheck 'purescript-mode))
(defun purescript/init-purescript-mode ()
(use-package purescript-mode
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'turn-on-purescript-indentation)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"i=" 'purescript-mode-format-imports
"i`" 'purescript-navigate-imports-return
"ia" 'purescript-align-imports
"in" 'purescript-navigate-imports))))
(defun purescript/init-psci ()
(use-package psci
:defer t
:init
(progn
(spacemacs/register-repl 'psci 'psci "purescript")
(add-hook 'purescript-mode-hook 'inferior-psci-mode)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"'" 'psci
"sb" 'psci/load-current-file!
"si" 'psci
"sm" 'psci/load-module!
"sp" 'psci/load-project-modules!))))
(defun purescript/init-psc-ide ()
(use-package psc-ide
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'psc-ide-mode)
(spacemacs/declare-prefix-for-mode 'purescript-mode "mm" "purescript/psc-ide")
(customize-set-variable 'psc-ide-add-import-on-completion purescript-add-import-on-completion)
(customize-set-variable 'psc-ide-rebuild-on-save purescript-enable-rebuild-on-save)
(add-to-list 'spacemacs-jump-handlers-purescript-mode 'psc-ide-goto-definition)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"mt" 'psc-ide-add-clause
"mcs" 'psc-ide-case-split
"ms" 'psc-ide-server-start
"mb" 'psc-ide-rebuild
"mq" 'psc-ide-server-quit
"ml" 'psc-ide-load-all
"mL" 'psc-ide-load-module
"mia" 'psc-ide-add-import
"mis" 'psc-ide-flycheck-insert-suggestion
"ht" 'psc-ide-show-type))))
(defun purescript/pre-init-popwin ()
(spacemacs|use-package-add-hook popwin
:post-config
(push '("*psc-ide-rebuild*" :tail t :noselect t) popwin:special-display-config)))
| true | ;;; packages.el --- Purescript Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2017 PI:NAME:<NAME>END_PI & Contributors
;;
;; Author: PI:NAME:<NAME>END_PI
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq purescript-packages
'(company
flycheck
purescript-mode
psci
psc-ide
popwin))
(defun purescript/post-init-company ()
(when (configuration-layer/package-used-p 'psc-ide)
(spacemacs|add-company-backends
:backends company-psc-ide-backend
:modes purescript-mode)))
(defun purescript/post-init-flycheck ()
(spacemacs/enable-flycheck 'purescript-mode))
(defun purescript/init-purescript-mode ()
(use-package purescript-mode
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'turn-on-purescript-indentation)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"i=" 'purescript-mode-format-imports
"i`" 'purescript-navigate-imports-return
"ia" 'purescript-align-imports
"in" 'purescript-navigate-imports))))
(defun purescript/init-psci ()
(use-package psci
:defer t
:init
(progn
(spacemacs/register-repl 'psci 'psci "purescript")
(add-hook 'purescript-mode-hook 'inferior-psci-mode)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"'" 'psci
"sb" 'psci/load-current-file!
"si" 'psci
"sm" 'psci/load-module!
"sp" 'psci/load-project-modules!))))
(defun purescript/init-psc-ide ()
(use-package psc-ide
:defer t
:init
(progn
(add-hook 'purescript-mode-hook 'psc-ide-mode)
(spacemacs/declare-prefix-for-mode 'purescript-mode "mm" "purescript/psc-ide")
(customize-set-variable 'psc-ide-add-import-on-completion purescript-add-import-on-completion)
(customize-set-variable 'psc-ide-rebuild-on-save purescript-enable-rebuild-on-save)
(add-to-list 'spacemacs-jump-handlers-purescript-mode 'psc-ide-goto-definition)
(spacemacs/set-leader-keys-for-major-mode 'purescript-mode
"mt" 'psc-ide-add-clause
"mcs" 'psc-ide-case-split
"ms" 'psc-ide-server-start
"mb" 'psc-ide-rebuild
"mq" 'psc-ide-server-quit
"ml" 'psc-ide-load-all
"mL" 'psc-ide-load-module
"mia" 'psc-ide-add-import
"mis" 'psc-ide-flycheck-insert-suggestion
"ht" 'psc-ide-show-type))))
(defun purescript/pre-init-popwin ()
(spacemacs|use-package-add-hook popwin
:post-config
(push '("*psc-ide-rebuild*" :tail t :noselect t) popwin:special-display-config)))
|
[
{
"context": "-style tabs for Evil mode users.\n;; Copyright 2013 Kris Jenkins\n;;\n;; Author: Kris Jenkins <krisajenkins@gmail.co",
"end": 99,
"score": 0.9998769164085388,
"start": 87,
"tag": "NAME",
"value": "Kris Jenkins"
},
{
"context": "sers.\n;; Copyright 2013 Kris Jenkins\n;;\n;; Author: Kris Jenkins <krisajenkins@gmail.com>\n;; Maintainer: Kris Jenk",
"end": 126,
"score": 0.9998793601989746,
"start": 114,
"tag": "NAME",
"value": "Kris Jenkins"
},
{
"context": "ght 2013 Kris Jenkins\n;;\n;; Author: Kris Jenkins <krisajenkins@gmail.com>\n;; Maintainer: Kris Jenkins <krisajenkins@gmail.",
"end": 150,
"score": 0.9999271035194397,
"start": 128,
"tag": "EMAIL",
"value": "krisajenkins@gmail.com"
},
{
"context": "is Jenkins <krisajenkins@gmail.com>\n;; Maintainer: Kris Jenkins <krisajenkins@gmail.com>\n;; Keywords: evil tab ta",
"end": 179,
"score": 0.9998807907104492,
"start": 167,
"tag": "NAME",
"value": "Kris Jenkins"
},
{
"context": "sajenkins@gmail.com>\n;; Maintainer: Kris Jenkins <krisajenkins@gmail.com>\n;; Keywords: evil tab tabs vim\n;; Package-Versio",
"end": 203,
"score": 0.9999288320541382,
"start": 181,
"tag": "EMAIL",
"value": "krisajenkins@gmail.com"
},
{
"context": "-Version: 20160217.720\n;; URL: https://github.com/krisajenkins/evil-tabs\n;; Created: 30th September 2013\n;; Vers",
"end": 308,
"score": 0.9992527961730957,
"start": 296,
"tag": "USERNAME",
"value": "krisajenkins"
}
] | elpa-25.2/evil-tabs-20160217.720/evil-tabs.el | taoyr/emacs | 1 | ;;; evil-tabs.el --- Integrating Vim-style tabs for Evil mode users.
;; Copyright 2013 Kris Jenkins
;;
;; Author: Kris Jenkins <krisajenkins@gmail.com>
;; Maintainer: Kris Jenkins <krisajenkins@gmail.com>
;; Keywords: evil tab tabs vim
;; Package-Version: 20160217.720
;; URL: https://github.com/krisajenkins/evil-tabs
;; Created: 30th September 2013
;; Version: 0.1.0
;; Package-Requires: ((evil "0.0.0") (elscreen "0.0.0"))
;;; Commentary:
;;
;; Integrating Vim-style tabs for Evil mode users.
;;; Code:
(require 'evil)
(require 'elscreen)
(defvar evil-tabs-mode-map (make-sparse-keymap)
"Evil-tabs-mode's keymap.")
(evil-define-command evil-tabs-tabedit (file)
(interactive "<f>")
(elscreen-find-file file))
(evil-define-command evil-tab-sensitive-quit (&optional bang)
:repeat nil
(interactive "<!>")
(if (> (length (elscreen-get-screen-list)) 1)
(elscreen-kill)
(evil-quit bang)))
(evil-define-command evil-tabs-current-buffer-to-tab ()
(let ((nwindows (length (window-list)))
(cb (current-buffer)))
(when (> nwindows 1)
(delete-window)
(elscreen-create)
(switch-to-buffer cb))))
(evil-define-motion evil-tabs-goto-tab (&optional count)
(if count
(elscreen-goto (- count 1))
(elscreen-next)))
(evil-ex-define-cmd "tabe[dit]" 'evil-tabs-tabedit)
(evil-ex-define-cmd "tabclone" 'elscreen-clone)
(evil-ex-define-cmd "tabc[lose]" 'elscreen-kill)
(evil-ex-define-cmd "tabd[isplay]" 'elscreen-toggle-display-tab)
(evil-ex-define-cmd "tabg[oto]" 'elscreen-goto)
(evil-ex-define-cmd "tabo[nly]" 'elscreen-kill-others)
(evil-ex-define-cmd "tabnew" 'elscreen-create)
(evil-ex-define-cmd "tabn[ext]" 'elscreen-next)
(evil-ex-define-cmd "tabp[rev]" 'elscreen-previous)
(evil-ex-define-cmd "tabr[ename]" 'elscreen-screen-nickname)
(evil-ex-define-cmd "tabs[elect]" 'elscreen-select-and-goto)
(evil-ex-define-cmd "tabw[ith]" 'elscreen-find-and-goto-by-buffer)
(evil-ex-define-cmd "q[uit]" 'evil-tab-sensitive-quit)
(evil-define-key 'normal evil-tabs-mode-map
"gt" 'elscreen-next
"gT" 'elscreen-previous
"gt" 'evil-tabs-goto-tab
"T" 'evil-tabs-current-buffer-to-tab)
;;;###autoload
(define-minor-mode evil-tabs-mode
"Integrating Vim-style tabs for Evil mode users."
:global t
:keymap evil-tabs-mode-map
(let ((prev-state evil-state))
(evil-normal-state)
(evil-change-state prev-state)
(elscreen-start)))
;;;###autoload
(defun turn-on-evil-tabs-mode ()
"Enable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode 1))
;;;###autoload
(defun turn-off-evil-tabs-mode ()
"Disable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode -1))
;;;###autoload
(define-globalized-minor-mode global-evil-tabs-mode evil-tabs-mode turn-on-evil-tabs-mode)
(provide 'evil-tabs)
;;; evil-tabs.el ends here
| 49277 | ;;; evil-tabs.el --- Integrating Vim-style tabs for Evil mode users.
;; Copyright 2013 <NAME>
;;
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; Keywords: evil tab tabs vim
;; Package-Version: 20160217.720
;; URL: https://github.com/krisajenkins/evil-tabs
;; Created: 30th September 2013
;; Version: 0.1.0
;; Package-Requires: ((evil "0.0.0") (elscreen "0.0.0"))
;;; Commentary:
;;
;; Integrating Vim-style tabs for Evil mode users.
;;; Code:
(require 'evil)
(require 'elscreen)
(defvar evil-tabs-mode-map (make-sparse-keymap)
"Evil-tabs-mode's keymap.")
(evil-define-command evil-tabs-tabedit (file)
(interactive "<f>")
(elscreen-find-file file))
(evil-define-command evil-tab-sensitive-quit (&optional bang)
:repeat nil
(interactive "<!>")
(if (> (length (elscreen-get-screen-list)) 1)
(elscreen-kill)
(evil-quit bang)))
(evil-define-command evil-tabs-current-buffer-to-tab ()
(let ((nwindows (length (window-list)))
(cb (current-buffer)))
(when (> nwindows 1)
(delete-window)
(elscreen-create)
(switch-to-buffer cb))))
(evil-define-motion evil-tabs-goto-tab (&optional count)
(if count
(elscreen-goto (- count 1))
(elscreen-next)))
(evil-ex-define-cmd "tabe[dit]" 'evil-tabs-tabedit)
(evil-ex-define-cmd "tabclone" 'elscreen-clone)
(evil-ex-define-cmd "tabc[lose]" 'elscreen-kill)
(evil-ex-define-cmd "tabd[isplay]" 'elscreen-toggle-display-tab)
(evil-ex-define-cmd "tabg[oto]" 'elscreen-goto)
(evil-ex-define-cmd "tabo[nly]" 'elscreen-kill-others)
(evil-ex-define-cmd "tabnew" 'elscreen-create)
(evil-ex-define-cmd "tabn[ext]" 'elscreen-next)
(evil-ex-define-cmd "tabp[rev]" 'elscreen-previous)
(evil-ex-define-cmd "tabr[ename]" 'elscreen-screen-nickname)
(evil-ex-define-cmd "tabs[elect]" 'elscreen-select-and-goto)
(evil-ex-define-cmd "tabw[ith]" 'elscreen-find-and-goto-by-buffer)
(evil-ex-define-cmd "q[uit]" 'evil-tab-sensitive-quit)
(evil-define-key 'normal evil-tabs-mode-map
"gt" 'elscreen-next
"gT" 'elscreen-previous
"gt" 'evil-tabs-goto-tab
"T" 'evil-tabs-current-buffer-to-tab)
;;;###autoload
(define-minor-mode evil-tabs-mode
"Integrating Vim-style tabs for Evil mode users."
:global t
:keymap evil-tabs-mode-map
(let ((prev-state evil-state))
(evil-normal-state)
(evil-change-state prev-state)
(elscreen-start)))
;;;###autoload
(defun turn-on-evil-tabs-mode ()
"Enable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode 1))
;;;###autoload
(defun turn-off-evil-tabs-mode ()
"Disable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode -1))
;;;###autoload
(define-globalized-minor-mode global-evil-tabs-mode evil-tabs-mode turn-on-evil-tabs-mode)
(provide 'evil-tabs)
;;; evil-tabs.el ends here
| true | ;;; evil-tabs.el --- Integrating Vim-style tabs for Evil mode users.
;; Copyright 2013 PI:NAME:<NAME>END_PI
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: evil tab tabs vim
;; Package-Version: 20160217.720
;; URL: https://github.com/krisajenkins/evil-tabs
;; Created: 30th September 2013
;; Version: 0.1.0
;; Package-Requires: ((evil "0.0.0") (elscreen "0.0.0"))
;;; Commentary:
;;
;; Integrating Vim-style tabs for Evil mode users.
;;; Code:
(require 'evil)
(require 'elscreen)
(defvar evil-tabs-mode-map (make-sparse-keymap)
"Evil-tabs-mode's keymap.")
(evil-define-command evil-tabs-tabedit (file)
(interactive "<f>")
(elscreen-find-file file))
(evil-define-command evil-tab-sensitive-quit (&optional bang)
:repeat nil
(interactive "<!>")
(if (> (length (elscreen-get-screen-list)) 1)
(elscreen-kill)
(evil-quit bang)))
(evil-define-command evil-tabs-current-buffer-to-tab ()
(let ((nwindows (length (window-list)))
(cb (current-buffer)))
(when (> nwindows 1)
(delete-window)
(elscreen-create)
(switch-to-buffer cb))))
(evil-define-motion evil-tabs-goto-tab (&optional count)
(if count
(elscreen-goto (- count 1))
(elscreen-next)))
(evil-ex-define-cmd "tabe[dit]" 'evil-tabs-tabedit)
(evil-ex-define-cmd "tabclone" 'elscreen-clone)
(evil-ex-define-cmd "tabc[lose]" 'elscreen-kill)
(evil-ex-define-cmd "tabd[isplay]" 'elscreen-toggle-display-tab)
(evil-ex-define-cmd "tabg[oto]" 'elscreen-goto)
(evil-ex-define-cmd "tabo[nly]" 'elscreen-kill-others)
(evil-ex-define-cmd "tabnew" 'elscreen-create)
(evil-ex-define-cmd "tabn[ext]" 'elscreen-next)
(evil-ex-define-cmd "tabp[rev]" 'elscreen-previous)
(evil-ex-define-cmd "tabr[ename]" 'elscreen-screen-nickname)
(evil-ex-define-cmd "tabs[elect]" 'elscreen-select-and-goto)
(evil-ex-define-cmd "tabw[ith]" 'elscreen-find-and-goto-by-buffer)
(evil-ex-define-cmd "q[uit]" 'evil-tab-sensitive-quit)
(evil-define-key 'normal evil-tabs-mode-map
"gt" 'elscreen-next
"gT" 'elscreen-previous
"gt" 'evil-tabs-goto-tab
"T" 'evil-tabs-current-buffer-to-tab)
;;;###autoload
(define-minor-mode evil-tabs-mode
"Integrating Vim-style tabs for Evil mode users."
:global t
:keymap evil-tabs-mode-map
(let ((prev-state evil-state))
(evil-normal-state)
(evil-change-state prev-state)
(elscreen-start)))
;;;###autoload
(defun turn-on-evil-tabs-mode ()
"Enable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode 1))
;;;###autoload
(defun turn-off-evil-tabs-mode ()
"Disable `evil-tabs-mode' in the current buffer."
(evil-tabs-mode -1))
;;;###autoload
(define-globalized-minor-mode global-evil-tabs-mode evil-tabs-mode turn-on-evil-tabs-mode)
(provide 'evil-tabs)
;;; evil-tabs.el ends here
|
[
{
"context": "e\n\n;;; Commentary:\n;; Base16: (https://github.com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: Carlo Abelli\n;; ",
"end": 120,
"score": 0.9996715784072876,
"start": 108,
"tag": "USERNAME",
"value": "chriskempson"
},
{
"context": ".com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: Carlo Abelli\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; C",
"end": 166,
"score": 0.9999021887779236,
"start": 154,
"tag": "NAME",
"value": "Carlo Abelli"
},
{
"context": "\n;;; Authors:\n;; Scheme: Carlo Abelli\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-the",
"end": 192,
"score": 0.9999000430107117,
"start": 180,
"tag": "NAME",
"value": "Kaleb Elwert"
},
{
"context": "; Scheme: Carlo Abelli\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-theme)\n\n(defvar bas",
"end": 208,
"score": 0.9999307990074158,
"start": 194,
"tag": "EMAIL",
"value": "belak@coded.io"
}
] | elpa/base16-theme-20210805.1401/base16-equilibrium-dark-theme.el | ik314/.emacs.d | 257 | ;; base16-equilibrium-dark-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: Carlo Abelli
;; Template: Kaleb Elwert <belak@coded.io>
;;; Code:
(require 'base16-theme)
(defvar base16-equilibrium-dark-colors
'(:base00 "#0c1118"
:base01 "#181c22"
:base02 "#22262d"
:base03 "#7b776e"
:base04 "#949088"
:base05 "#afaba2"
:base06 "#cac6bd"
:base07 "#e7e2d9"
:base08 "#f04339"
:base09 "#df5923"
:base0A "#bb8801"
:base0B "#7f8b00"
:base0C "#00948b"
:base0D "#008dd1"
:base0E "#6a7fd2"
:base0F "#e3488e")
"All colors for Base16 Equilibrium Dark are defined here.")
;; Define the theme
(deftheme base16-equilibrium-dark)
;; Add all the faces to the theme
(base16-theme-define 'base16-equilibrium-dark base16-equilibrium-dark-colors)
;; Mark the theme as provided
(provide-theme 'base16-equilibrium-dark)
(provide 'base16-equilibrium-dark-theme)
;;; base16-equilibrium-dark-theme.el ends here
| 29840 | ;; base16-equilibrium-dark-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: <NAME>
;; Template: <NAME> <<EMAIL>>
;;; Code:
(require 'base16-theme)
(defvar base16-equilibrium-dark-colors
'(:base00 "#0c1118"
:base01 "#181c22"
:base02 "#22262d"
:base03 "#7b776e"
:base04 "#949088"
:base05 "#afaba2"
:base06 "#cac6bd"
:base07 "#e7e2d9"
:base08 "#f04339"
:base09 "#df5923"
:base0A "#bb8801"
:base0B "#7f8b00"
:base0C "#00948b"
:base0D "#008dd1"
:base0E "#6a7fd2"
:base0F "#e3488e")
"All colors for Base16 Equilibrium Dark are defined here.")
;; Define the theme
(deftheme base16-equilibrium-dark)
;; Add all the faces to the theme
(base16-theme-define 'base16-equilibrium-dark base16-equilibrium-dark-colors)
;; Mark the theme as provided
(provide-theme 'base16-equilibrium-dark)
(provide 'base16-equilibrium-dark-theme)
;;; base16-equilibrium-dark-theme.el ends here
| true | ;; base16-equilibrium-dark-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: PI:NAME:<NAME>END_PI
;; Template: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;; Code:
(require 'base16-theme)
(defvar base16-equilibrium-dark-colors
'(:base00 "#0c1118"
:base01 "#181c22"
:base02 "#22262d"
:base03 "#7b776e"
:base04 "#949088"
:base05 "#afaba2"
:base06 "#cac6bd"
:base07 "#e7e2d9"
:base08 "#f04339"
:base09 "#df5923"
:base0A "#bb8801"
:base0B "#7f8b00"
:base0C "#00948b"
:base0D "#008dd1"
:base0E "#6a7fd2"
:base0F "#e3488e")
"All colors for Base16 Equilibrium Dark are defined here.")
;; Define the theme
(deftheme base16-equilibrium-dark)
;; Add all the faces to the theme
(base16-theme-define 'base16-equilibrium-dark base16-equilibrium-dark-colors)
;; Mark the theme as provided
(provide-theme 'base16-equilibrium-dark)
(provide 'base16-equilibrium-dark-theme)
;;; base16-equilibrium-dark-theme.el ends here
|
[
{
"context": "*- lexical-binding: t; -*-\n\n;; Copyright (C) 2021 Mohsin Kaleem\n\n;; Author: Mohsin Kaleem <mohkale@kisara.moe>\n;;",
"end": 126,
"score": 0.9999001622200012,
"start": 113,
"tag": "NAME",
"value": "Mohsin Kaleem"
},
{
"context": "\n\n;; Copyright (C) 2021 Mohsin Kaleem\n\n;; Author: Mohsin Kaleem <mohkale@kisara.moe>\n;; Keywords: tools, lsp\n;; P",
"end": 152,
"score": 0.9998984336853027,
"start": 139,
"tag": "NAME",
"value": "Mohsin Kaleem"
},
{
"context": "C) 2021 Mohsin Kaleem\n\n;; Author: Mohsin Kaleem <mohkale@kisara.moe>\n;; Keywords: tools, lsp\n;; Package-Requires: ((e",
"end": 172,
"score": 0.9999325275421143,
"start": 154,
"tag": "EMAIL",
"value": "mohkale@kisara.moe"
},
{
"context": "ia \"25.2\"))\n;; Version: 0.1\n\n;; Copyright (C) 2021 Mohsin Kaleem\n\n;; Permission is hereby granted, free of charge,",
"end": 320,
"score": 0.9998981952667236,
"start": 307,
"tag": "NAME",
"value": "Mohsin Kaleem"
}
] | apheleia-eglot.el | mohkale/apheleia-lsp | 1 | ;;; apheleia-eglot.el --- Format buffers on save using eglot -*- lexical-binding: t; -*-
;; Copyright (C) 2021 Mohsin Kaleem
;; Author: Mohsin Kaleem <mohkale@kisara.moe>
;; Keywords: tools, lsp
;; Package-Requires: ((emacs "29.0") (eglot "1.7") (apheleia "25.2"))
;; Version: 0.1
;; Copyright (C) 2021 Mohsin Kaleem
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Commentary:
;; This package provides a formatter for apheleia that asynchronously queries
;; a language server, managed by eglot, to edit the current buffer. This works
;; pretty much exactly the same way as `eglot-format-buffer' except this is
;; asynchronous and can be chained for use with other formatters alongside
;; your language server.
;;
;; WARN this formatter must be the first in a formatter pipeline. At the moment
;; there's no performant way to detect this is the case, but if you run this
;; formatter second, or third in a series, then it will most likely corrupt
;; the original buffer.
;;; Code:
(require 'cl-lib)
(require 'apheleia)
(require 'eglot)
;;;###autoload
(defun apheleia-eglot (orig-buffer scratch-buffer callback)
"Apheleia formatter using a running eglot language server.
This calls textDocument/formatting on SCRATCH-BUFFER using the
server associated with ORIG-BUFFER before calling CALLBACK.
Warn: This formatter cannot be run in a pipeline, or if it is
then it must be the first in that pipeline. The contents of
SCRATCH-BUFFER must match ORIG-BUFFER otherwise you'll get a
broken output buffer."
;; TOOD: When formatting a sub-region use textDocument/rangeFormatting.
(with-current-buffer orig-buffer
(unless (eglot--server-capable :documentFormattingProvider)
(error "[eglot-apheleia] Server can't format!"))
(jsonrpc-async-request
(eglot--current-server-or-lose)
:textDocument/formatting
(list
:textDocument (eglot--TextDocumentIdentifier)
:options (list :tabSize tab-width
:insertSpaces (if indent-tabs-mode :json-false t)))
:deferred :textDocument/formatting
:success-fn
(lambda (edits)
(with-current-buffer scratch-buffer
(let ((inhibit-message t))
(eglot--apply-text-edits edits)))
(funcall callback scratch-buffer))
:error-fn
(eglot--lambda ((ResponseError) code message)
(error "[eglot-apheleia] %s: %s" code message)))))
;; Automatically add apheleia-eglot to apheleias formatter repository.
;;;###autoload (with-eval-after-load 'apheleia (push '(eglot . apheleia-eglot) apheleia-formatters))
;;;###autoload
(define-minor-mode apheleia-eglot-mode
"Minor mode for formatting buffers with apheleia and eglot.
All this mode does is ensure eglot is the first choice formatter
for the current `major-mode', to enable format on save you should
also enable `apheleia-mode'."
:lighter nil
(if apheleia-eglot-mode
(progn
(make-variable-buffer-local 'apheleia-mode-alist)
(push (cons major-mode 'eglot)
apheleia-mode-alist))
(cl-delete (cons major-mode 'eglot) apheleia-mode-alist)))
(provide 'apheleia-eglot)
;;; apheleia-eglot.el ends here
| 48611 | ;;; apheleia-eglot.el --- Format buffers on save using eglot -*- lexical-binding: t; -*-
;; Copyright (C) 2021 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords: tools, lsp
;; Package-Requires: ((emacs "29.0") (eglot "1.7") (apheleia "25.2"))
;; Version: 0.1
;; Copyright (C) 2021 <NAME>
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Commentary:
;; This package provides a formatter for apheleia that asynchronously queries
;; a language server, managed by eglot, to edit the current buffer. This works
;; pretty much exactly the same way as `eglot-format-buffer' except this is
;; asynchronous and can be chained for use with other formatters alongside
;; your language server.
;;
;; WARN this formatter must be the first in a formatter pipeline. At the moment
;; there's no performant way to detect this is the case, but if you run this
;; formatter second, or third in a series, then it will most likely corrupt
;; the original buffer.
;;; Code:
(require 'cl-lib)
(require 'apheleia)
(require 'eglot)
;;;###autoload
(defun apheleia-eglot (orig-buffer scratch-buffer callback)
"Apheleia formatter using a running eglot language server.
This calls textDocument/formatting on SCRATCH-BUFFER using the
server associated with ORIG-BUFFER before calling CALLBACK.
Warn: This formatter cannot be run in a pipeline, or if it is
then it must be the first in that pipeline. The contents of
SCRATCH-BUFFER must match ORIG-BUFFER otherwise you'll get a
broken output buffer."
;; TOOD: When formatting a sub-region use textDocument/rangeFormatting.
(with-current-buffer orig-buffer
(unless (eglot--server-capable :documentFormattingProvider)
(error "[eglot-apheleia] Server can't format!"))
(jsonrpc-async-request
(eglot--current-server-or-lose)
:textDocument/formatting
(list
:textDocument (eglot--TextDocumentIdentifier)
:options (list :tabSize tab-width
:insertSpaces (if indent-tabs-mode :json-false t)))
:deferred :textDocument/formatting
:success-fn
(lambda (edits)
(with-current-buffer scratch-buffer
(let ((inhibit-message t))
(eglot--apply-text-edits edits)))
(funcall callback scratch-buffer))
:error-fn
(eglot--lambda ((ResponseError) code message)
(error "[eglot-apheleia] %s: %s" code message)))))
;; Automatically add apheleia-eglot to apheleias formatter repository.
;;;###autoload (with-eval-after-load 'apheleia (push '(eglot . apheleia-eglot) apheleia-formatters))
;;;###autoload
(define-minor-mode apheleia-eglot-mode
"Minor mode for formatting buffers with apheleia and eglot.
All this mode does is ensure eglot is the first choice formatter
for the current `major-mode', to enable format on save you should
also enable `apheleia-mode'."
:lighter nil
(if apheleia-eglot-mode
(progn
(make-variable-buffer-local 'apheleia-mode-alist)
(push (cons major-mode 'eglot)
apheleia-mode-alist))
(cl-delete (cons major-mode 'eglot) apheleia-mode-alist)))
(provide 'apheleia-eglot)
;;; apheleia-eglot.el ends here
| true | ;;; apheleia-eglot.el --- Format buffers on save using eglot -*- lexical-binding: t; -*-
;; Copyright (C) 2021 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: tools, lsp
;; Package-Requires: ((emacs "29.0") (eglot "1.7") (apheleia "25.2"))
;; Version: 0.1
;; Copyright (C) 2021 PI:NAME:<NAME>END_PI
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Commentary:
;; This package provides a formatter for apheleia that asynchronously queries
;; a language server, managed by eglot, to edit the current buffer. This works
;; pretty much exactly the same way as `eglot-format-buffer' except this is
;; asynchronous and can be chained for use with other formatters alongside
;; your language server.
;;
;; WARN this formatter must be the first in a formatter pipeline. At the moment
;; there's no performant way to detect this is the case, but if you run this
;; formatter second, or third in a series, then it will most likely corrupt
;; the original buffer.
;;; Code:
(require 'cl-lib)
(require 'apheleia)
(require 'eglot)
;;;###autoload
(defun apheleia-eglot (orig-buffer scratch-buffer callback)
"Apheleia formatter using a running eglot language server.
This calls textDocument/formatting on SCRATCH-BUFFER using the
server associated with ORIG-BUFFER before calling CALLBACK.
Warn: This formatter cannot be run in a pipeline, or if it is
then it must be the first in that pipeline. The contents of
SCRATCH-BUFFER must match ORIG-BUFFER otherwise you'll get a
broken output buffer."
;; TOOD: When formatting a sub-region use textDocument/rangeFormatting.
(with-current-buffer orig-buffer
(unless (eglot--server-capable :documentFormattingProvider)
(error "[eglot-apheleia] Server can't format!"))
(jsonrpc-async-request
(eglot--current-server-or-lose)
:textDocument/formatting
(list
:textDocument (eglot--TextDocumentIdentifier)
:options (list :tabSize tab-width
:insertSpaces (if indent-tabs-mode :json-false t)))
:deferred :textDocument/formatting
:success-fn
(lambda (edits)
(with-current-buffer scratch-buffer
(let ((inhibit-message t))
(eglot--apply-text-edits edits)))
(funcall callback scratch-buffer))
:error-fn
(eglot--lambda ((ResponseError) code message)
(error "[eglot-apheleia] %s: %s" code message)))))
;; Automatically add apheleia-eglot to apheleias formatter repository.
;;;###autoload (with-eval-after-load 'apheleia (push '(eglot . apheleia-eglot) apheleia-formatters))
;;;###autoload
(define-minor-mode apheleia-eglot-mode
"Minor mode for formatting buffers with apheleia and eglot.
All this mode does is ensure eglot is the first choice formatter
for the current `major-mode', to enable format on save you should
also enable `apheleia-mode'."
:lighter nil
(if apheleia-eglot-mode
(progn
(make-variable-buffer-local 'apheleia-mode-alist)
(push (cons major-mode 'eglot)
apheleia-mode-alist))
(cl-delete (cons major-mode 'eglot) apheleia-mode-alist)))
(provide 'apheleia-eglot)
;;; apheleia-eglot.el ends here
|
[
{
"context": "tex plugin of evil-matchit\n\n;; Copyright (C) 2014 Chen Bin <chenbin.sh@gmail.com>\n\n;; Author: Chen Bin <chen",
"end": 90,
"score": 0.9997131824493408,
"start": 82,
"tag": "NAME",
"value": "Chen Bin"
},
{
"context": "of evil-matchit\n\n;; Copyright (C) 2014 Chen Bin <chenbin.sh@gmail.com>\n\n;; Author: Chen Bin <chenbin.sh@gmail.com>\n\n;; ",
"end": 112,
"score": 0.9999310970306396,
"start": 92,
"tag": "EMAIL",
"value": "chenbin.sh@gmail.com"
},
{
"context": " 2014 Chen Bin <chenbin.sh@gmail.com>\n\n;; Author: Chen Bin <chenbin.sh@gmail.com>\n\n;; This file is not part ",
"end": 134,
"score": 0.9996846318244934,
"start": 126,
"tag": "NAME",
"value": "Chen Bin"
},
{
"context": " Bin <chenbin.sh@gmail.com>\n\n;; Author: Chen Bin <chenbin.sh@gmail.com>\n\n;; This file is not part of GNU Emacs.\n\n;;; Lic",
"end": 156,
"score": 0.9999303817749023,
"start": 136,
"tag": "EMAIL",
"value": "chenbin.sh@gmail.com"
}
] | .emacs.d/elpa/evil-matchit-20140714.450/evil-matchit-latex.el | divyekapoor/vim-dotfiles | 3 | ;;; evil-matchit-latex.el ---latex plugin of evil-matchit
;; Copyright (C) 2014 Chen Bin <chenbin.sh@gmail.com>
;; Author: Chen Bin <chenbin.sh@gmail.com>
;; This file is not part of GNU Emacs.
;;; License:
;; This file is part of evil-matchit
;;
;; evil-matchit is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; evil-matchit 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'evil-matchit-sdk)
(defvar evilmi-latex-regexp "\\\\\\([a-zA-Z]+\\(\{[a-zA-Z]+\}\\)?\\)")
(defvar evilmi-latex-match-tags
'((("if[a-zA-Z]+" "if") "else" "fi")
("left" nil "right")
("begin[a-z]+" nil "end[a-z]+")
("begin\{[a-z]+\}" nil "end\{[a-z]+\}"))
"The table we look up match tags. This is a three column table.
The first column contains the open tag(s).
The second column contains the middle tag(s).
The third column contains the closed tags(s).")
;;;###autoload
(defun evilmi-latex-get-tag ()
(let (rlt
keyword
tag-info
cursor-pos)
(save-excursion
(skip-chars-backward "a-zA-Z \t{}")
;; move cursor to the beginning of tag
(unless (bolp)
(
backward-char 1)
)
;; extract keyword, several keyword could be in one line
(re-search-forward evilmi-latex-regexp (line-end-position) t)
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cursor-pos (point))
(setq tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq rlt (list
(if (= 2 (nth 1 tag-info))
(point)
(save-excursion
(backward-char (1+ (length keyword)))
(point)
)
)
tag-info
))))
(if rlt (goto-char cursor-pos))
rlt
))
;;;###autoload
(defun evilmi-latex-jump (rlt NUM)
(let ((orig-tag-type (nth 1 (nth 1 rlt)))
(orig-tag-info (nth 1 rlt))
cur-tag-type
cur-tag-info
level
keyword
found
where-to-jump-in-theory
fn-reg-search
)
(setq level (if (= orig-tag-type 2) 0 1))
(setq fn-reg-search (if (= orig-tag-type 2) 're-search-backward 're-search-forward))
(while (not found)
(if (not (funcall fn-reg-search evilmi-latex-regexp
(if (= orig-tag-type 2) (point-min) (point-max))
t))
(setq found t)
;; nothing found
(progn
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cur-tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq cur-tag-type (nth 1 cur-tag-info))
;; we need more strict tag match strategy because tex is really wierd
(when (= (car cur-tag-info) (car orig-tag-info))
(cond
;; handle open tag
;; open (0) -> mid (1) found when level is one else ignore
((and (= orig-tag-type 0) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> closed (2) found when level is zero, level--
((and (= orig-tag-type 0) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> open (0) level++
((and (= orig-tag-type 0) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle mid tag
;; mid (1) -> mid (1) found when level is zero else ignore
((and (= orig-tag-type 1) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> closed (2) found when level is zero, level --
((and (= orig-tag-type 1) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> open (0) level++
((and (= orig-tag-type 1) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle closed tag
;; closed (2) -> mid (1) ignore,impossible
((and (= orig-tag-type 2) (= cur-tag-type 1))
(message "impossible to be here (latex-mode)")
)
;; closed (2) -> closed (2) level++
((and (= orig-tag-type 2) (= cur-tag-type 2))
(setq level (1+ level))
)
;; closed (2) -> open (0) found when level is zero, level--
((and (= orig-tag-type 2) (= cur-tag-type 0))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
(t (message "why here?"))
)
)))))))
(provide 'evil-matchit-latex)
| 18259 | ;;; evil-matchit-latex.el ---latex plugin of evil-matchit
;; Copyright (C) 2014 <NAME> <<EMAIL>>
;; Author: <NAME> <<EMAIL>>
;; This file is not part of GNU Emacs.
;;; License:
;; This file is part of evil-matchit
;;
;; evil-matchit is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; evil-matchit 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'evil-matchit-sdk)
(defvar evilmi-latex-regexp "\\\\\\([a-zA-Z]+\\(\{[a-zA-Z]+\}\\)?\\)")
(defvar evilmi-latex-match-tags
'((("if[a-zA-Z]+" "if") "else" "fi")
("left" nil "right")
("begin[a-z]+" nil "end[a-z]+")
("begin\{[a-z]+\}" nil "end\{[a-z]+\}"))
"The table we look up match tags. This is a three column table.
The first column contains the open tag(s).
The second column contains the middle tag(s).
The third column contains the closed tags(s).")
;;;###autoload
(defun evilmi-latex-get-tag ()
(let (rlt
keyword
tag-info
cursor-pos)
(save-excursion
(skip-chars-backward "a-zA-Z \t{}")
;; move cursor to the beginning of tag
(unless (bolp)
(
backward-char 1)
)
;; extract keyword, several keyword could be in one line
(re-search-forward evilmi-latex-regexp (line-end-position) t)
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cursor-pos (point))
(setq tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq rlt (list
(if (= 2 (nth 1 tag-info))
(point)
(save-excursion
(backward-char (1+ (length keyword)))
(point)
)
)
tag-info
))))
(if rlt (goto-char cursor-pos))
rlt
))
;;;###autoload
(defun evilmi-latex-jump (rlt NUM)
(let ((orig-tag-type (nth 1 (nth 1 rlt)))
(orig-tag-info (nth 1 rlt))
cur-tag-type
cur-tag-info
level
keyword
found
where-to-jump-in-theory
fn-reg-search
)
(setq level (if (= orig-tag-type 2) 0 1))
(setq fn-reg-search (if (= orig-tag-type 2) 're-search-backward 're-search-forward))
(while (not found)
(if (not (funcall fn-reg-search evilmi-latex-regexp
(if (= orig-tag-type 2) (point-min) (point-max))
t))
(setq found t)
;; nothing found
(progn
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cur-tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq cur-tag-type (nth 1 cur-tag-info))
;; we need more strict tag match strategy because tex is really wierd
(when (= (car cur-tag-info) (car orig-tag-info))
(cond
;; handle open tag
;; open (0) -> mid (1) found when level is one else ignore
((and (= orig-tag-type 0) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> closed (2) found when level is zero, level--
((and (= orig-tag-type 0) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> open (0) level++
((and (= orig-tag-type 0) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle mid tag
;; mid (1) -> mid (1) found when level is zero else ignore
((and (= orig-tag-type 1) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> closed (2) found when level is zero, level --
((and (= orig-tag-type 1) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> open (0) level++
((and (= orig-tag-type 1) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle closed tag
;; closed (2) -> mid (1) ignore,impossible
((and (= orig-tag-type 2) (= cur-tag-type 1))
(message "impossible to be here (latex-mode)")
)
;; closed (2) -> closed (2) level++
((and (= orig-tag-type 2) (= cur-tag-type 2))
(setq level (1+ level))
)
;; closed (2) -> open (0) found when level is zero, level--
((and (= orig-tag-type 2) (= cur-tag-type 0))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
(t (message "why here?"))
)
)))))))
(provide 'evil-matchit-latex)
| true | ;;; evil-matchit-latex.el ---latex plugin of evil-matchit
;; Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; This file is not part of GNU Emacs.
;;; License:
;; This file is part of evil-matchit
;;
;; evil-matchit is free software: you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as published
;; by the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; evil-matchit 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(require 'evil-matchit-sdk)
(defvar evilmi-latex-regexp "\\\\\\([a-zA-Z]+\\(\{[a-zA-Z]+\}\\)?\\)")
(defvar evilmi-latex-match-tags
'((("if[a-zA-Z]+" "if") "else" "fi")
("left" nil "right")
("begin[a-z]+" nil "end[a-z]+")
("begin\{[a-z]+\}" nil "end\{[a-z]+\}"))
"The table we look up match tags. This is a three column table.
The first column contains the open tag(s).
The second column contains the middle tag(s).
The third column contains the closed tags(s).")
;;;###autoload
(defun evilmi-latex-get-tag ()
(let (rlt
keyword
tag-info
cursor-pos)
(save-excursion
(skip-chars-backward "a-zA-Z \t{}")
;; move cursor to the beginning of tag
(unless (bolp)
(
backward-char 1)
)
;; extract keyword, several keyword could be in one line
(re-search-forward evilmi-latex-regexp (line-end-position) t)
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cursor-pos (point))
(setq tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq rlt (list
(if (= 2 (nth 1 tag-info))
(point)
(save-excursion
(backward-char (1+ (length keyword)))
(point)
)
)
tag-info
))))
(if rlt (goto-char cursor-pos))
rlt
))
;;;###autoload
(defun evilmi-latex-jump (rlt NUM)
(let ((orig-tag-type (nth 1 (nth 1 rlt)))
(orig-tag-info (nth 1 rlt))
cur-tag-type
cur-tag-info
level
keyword
found
where-to-jump-in-theory
fn-reg-search
)
(setq level (if (= orig-tag-type 2) 0 1))
(setq fn-reg-search (if (= orig-tag-type 2) 're-search-backward 're-search-forward))
(while (not found)
(if (not (funcall fn-reg-search evilmi-latex-regexp
(if (= orig-tag-type 2) (point-min) (point-max))
t))
(setq found t)
;; nothing found
(progn
(setq keyword (match-string 1))
(when (evilmi-sdk-member keyword evilmi-latex-match-tags)
(setq cur-tag-info (evilmi-sdk-get-tag-info keyword evilmi-latex-match-tags))
(setq cur-tag-type (nth 1 cur-tag-info))
;; we need more strict tag match strategy because tex is really wierd
(when (= (car cur-tag-info) (car orig-tag-info))
(cond
;; handle open tag
;; open (0) -> mid (1) found when level is one else ignore
((and (= orig-tag-type 0) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> closed (2) found when level is zero, level--
((and (= orig-tag-type 0) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; open (0) -> open (0) level++
((and (= orig-tag-type 0) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle mid tag
;; mid (1) -> mid (1) found when level is zero else ignore
((and (= orig-tag-type 1) (= cur-tag-type 1))
(when (= 1 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> closed (2) found when level is zero, level --
((and (= orig-tag-type 1) (= cur-tag-type 2))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
;; mid (1) -> open (0) level++
((and (= orig-tag-type 1) (= cur-tag-type 0))
(setq level (1+ level))
)
;; now handle closed tag
;; closed (2) -> mid (1) ignore,impossible
((and (= orig-tag-type 2) (= cur-tag-type 1))
(message "impossible to be here (latex-mode)")
)
;; closed (2) -> closed (2) level++
((and (= orig-tag-type 2) (= cur-tag-type 2))
(setq level (1+ level))
)
;; closed (2) -> open (0) found when level is zero, level--
((and (= orig-tag-type 2) (= cur-tag-type 0))
(setq level (1- level))
(when (= 0 level)
(setq where-to-jump-in-theory (point))
(setq found t)
)
)
(t (message "why here?"))
)
)))))))
(provide 'evil-matchit-latex)
|
[
{
"context": "w\n;; they are implemented.\n\n(setq user-full-name \"Thanawat Techaumnuaiwit\")\n(after! mu4e\n (setq! mu4e-get-mail-command \"m",
"end": 874,
"score": 0.9998266696929932,
"start": 851,
"tag": "NAME",
"value": "Thanawat Techaumnuaiwit"
},
{
"context": "\n '((user-mail-address . \"thanawat@ucsb.edu\")\n (smtpmail-smtp-user .",
"end": 1106,
"score": 0.9999209642410278,
"start": 1089,
"tag": "EMAIL",
"value": "thanawat@ucsb.edu"
},
{
"context": "\n (smtpmail-smtp-user . \"thanawat@ucsb.edu\")\n (mu4e-drafts-folder .",
"end": 1175,
"score": 0.9999169111251831,
"start": 1158,
"tag": "EMAIL",
"value": "thanawat@ucsb.edu"
},
{
"context": " (mu4e-compose-signature . \"Best,\\n Thanawat Techaumnuaiwit\"))\n t)\n\n(set-email",
"end": 1810,
"score": 0.8673223257064819,
"start": 1801,
"tag": "NAME",
"value": "anawat Te"
},
{
"context": " \"smtp.gmail.com\")\n (smtpmail-smtp-user . \"thanatechaumnuaiwit@gmail.com\")\n (user-mail-address . \"thanatechaumnuai",
"end": 2373,
"score": 0.9999225735664368,
"start": 2344,
"tag": "EMAIL",
"value": "thanatechaumnuaiwit@gmail.com"
},
{
"context": "uaiwit@gmail.com\")\n (user-mail-address . \"thanatechaumnuaiwit@gmail.com\") ;; only needed for mu < 1.4\n (mu4e-compos",
"end": 2436,
"score": 0.9999235272407532,
"start": 2407,
"tag": "EMAIL",
"value": "thanatechaumnuaiwit@gmail.com"
},
{
"context": " :map org-mode-map\n;; (:prefix (\"k\" . \"Anki\")\n;; :desc \"Push\" \"p\" 'anki-editor-push-n",
"end": 12818,
"score": 0.8610510230064392,
"start": 12814,
"tag": "NAME",
"value": "Anki"
},
{
"context": "e t\n;; :config\n;; (setq org-roam-server-host \"127.0.0.1\"\n;; org-roam-server-port 8080\n;; ",
"end": 13508,
"score": 0.9981303811073303,
"start": 13499,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "a.chat\"\n `(\n :tls t\n :port 6697\n :nick \"thiskappaisgrey\"\n :nickserv-nick \"thiskappaisgrey\"\n",
"end": 20379,
"score": 0.7632158994674683,
"start": 20375,
"tag": "USERNAME",
"value": "this"
},
{
"context": " `(\n :tls t\n :port 6697\n :nick \"thiskappaisgrey\"\n :nickserv-nick \"thiskappaisgrey\"\n :channe",
"end": 20390,
"score": 0.9961223602294922,
"start": 20383,
"tag": "USERNAME",
"value": "aisgrey"
},
{
"context": "7\n :nick \"thiskappaisgrey\"\n :nickserv-nick \"thiskappaisgrey\"\n :channels (\"#haskell-language-server\" \"#emac",
"end": 20427,
"score": 0.998806357383728,
"start": 20412,
"tag": "USERNAME",
"value": "thiskappaisgrey"
}
] | .config/doom/config.el | ThisKappaIsGrey/dotfiles | 0 | ;;; $DOOMDIR/config.el -*- lexical-binding: t; -*-
;; Here are some additional functions/macros that could help you configure Doom:
;;
;; - `load!' for loading external *.el files relative to this one
;; - `use-package' for configuring packages
;; - `after!' for running code after a package has loaded
;; - `add-load-path!' for adding directories to the `load-path', where Emacs
;; looks when you load packages with `require' or `use-package'.
;; - `map!' for binding new keys
;;
;; To get information about any of these functions/macros, move the cursor over
;; the highlighted symbol at press 'K' (non-evil users must press 'C-c g k').
;; This will open documentation for it, including demos of how they are used.
;;
;; You can also try 'gd' (or 'C-c g d') to jump to their definition and see how
;; they are implemented.
(setq user-full-name "Thanawat Techaumnuaiwit")
(after! mu4e
(setq! mu4e-get-mail-command "mbsync -c ~/.config/mbsync/mbsyncrc -a")
(setq mu4e-change-filenames-when-moving t)
)
(set-email-account! "ucsb"
'((user-mail-address . "thanawat@ucsb.edu")
(smtpmail-smtp-user . "thanawat@ucsb.edu")
(mu4e-drafts-folder . "/ucsb/[acc1].Drafts")
(mu4e-refile-folder . "/ucsb/[acc1].Archive")
(mu4e-sent-folder . "/ucsb/[acc1].Sent Mail")
(mu4e-trash-folder . "/ucsb/[acc1].Trash")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-service . 587)
(mu4e-compose-signature . "Best,\n Thanawat Techaumnuaiwit"))
t)
(set-email-account! "personal-gmail"
'((mu4e-sent-folder . "/personal-gmail/[acc2].Sent Mail")
(mu4e-drafts-folder . "/personal-gmail/[acc2].Drafts")
(mu4e-trash-folder . "/personal-gmail/[acc2].Trash")
(mu4e-refile-folder . "/personal-gmail/[acc2].Archive")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-user . "thanatechaumnuaiwit@gmail.com")
(user-mail-address . "thanatechaumnuaiwit@gmail.com") ;; only needed for mu < 1.4
(mu4e-compose-signature . "You can find me at https://thanawat.xyz\n---\nThanawat Techaumnuaiwit"))
nil)
(add-to-list 'load-path "/run/current-system/sw/share/emacs/site-lisp/mu4e/")
(setq enable-local-variables t)
(setq doom-font (font-spec :family "Hasklug Nerd Font Mono" :size 18))
(after! ispell
(setq ispell-dictionary "en"))
;; If you want to change the style of line numbers, change this to `relative' or
;; `nil' to disable it:
(setq display-line-numbers-type 'relative)
;; Makes visual-lines work better
(setq visual-fill-column-center-text t)
(add-to-list 'default-frame-alist '(fullscreen . maximized))
(setq doom-theme 'doom-oceanic-next)
;; explcitly set the frametitle because otherwise the frame title would show weird characters
;; https://www.emacswiki.org/emacs/FrameTitle
(setq frame-title-format "%b - Doom Emacs")
(set-popup-rules!
'(("^\\*info\\*" :slot 2 :side left :width 85 :quit nil)))
(display-battery-mode)
;; (use-package dashboard
;; :init ;; tweak dashboard config before loading it
;; (setq dashboard-set-heading-icons t)
;; (setq dashboard-set-file-icons t)
;; (setq dashboard-banner-logo-title "Emacs Is More Than A Text Editor!")
;; (setq dashboard-startup-banner 'logo) ;; use standard emacs logo as banner
;; (setq dashboard-center-content nil) ;; set to 't' for centered content
;; (setq dashboard-items '((recents . 5)
;; (agenda . 5 )
;; (bookmarks . 5)
;; (projects . 5)
;; (registers . 5)))
;; :config
;; (dashboard-setup-startup-hook)
;; (dashboard-modify-heading-icons '((recents . "file-text")
;; (bookmarks . "book")))
;; )
(setq evil-escape-key-sequence "fd")
(map! :leader
:desc "rss" "o s" #'=rss)
;;Make evil-mode up/down operate in screen lines instead of logical lines
;; (define-key evil-motion-state-map "j" 'evil-next-visual-line)
;; (define-key evil-motion-state-map "k" 'evil-previous-visual-line)
;;Also in visual mode
;; (define-key evil-visual-state-map "j" 'evil-next-visual-line)
;; (define-key evil-visual-state-map "k" 'evil-previous-visual-line)
(setq avy-keys '(?a ?s ?e ?t ?g ?y ?n ?i ?o ?h))
(map!
:map smartparens-mode-map
;; smartparens maps (navigation ops)
:nvie "C-M-f" #'sp-forward-sexp
:nvie "C-M-b" #'sp-backward-sexp
:nvie "C-M-u" #'sp-backward-up-sexp
:nvie "C-M-d" #'sp-down-sexp
;; smartparens maps (split join slurp barf)
:nie "M-s" #'sp-split-sexp
:nie "M-j" #'sp-join-sexp
:nvie "C->" #'sp-forward-slurp-sexp
:nvie "C-<" #'sp-forward-barf-sexp
:nvie "C-{" #'sp-backward-slurp-sexp
:nvie "C-}" #'sp-backward-barf-sexp)
(after! org
(setq org-directory "~/org/"
org-agenda-files '("~/org/gtd/inbox.org" "~/org/gtd/tickler.org" "~/org/gtd/gtd.org" "~/org/gtd/habits.org")
org-re-reveal-root "/home/thanawat/reveal.js/"
org-export-with-toc nil
org-hide-emphasis-markers t
org-log-into-drawer t
org-log-done 'time
org-export-with-section-numbers nil)
(add-to-list 'org-modules 'org-habit t)
(setcar (nthcdr 4 org-emphasis-regexp-components) 10)
(org-set-emph-re 'org-emphasis-regexp-components org-emphasis-regexp-components)
)
(after! org
(setq org-capture-templates
'(("t" "Todos" entry (file+headline "gtd/inbox.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("T" "Tickler" entry (file+headline "gtd/tickler.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("r" "Resources" entry (file+headline "gtd/resources.org" "Inbox") "* TODO %?" :prepend t)
("e" "Emacs + Vim tricks" entry (file+headline "emacs-tips.org" "Inbox") "* TODO %?" :prepend t)
;; copied from doom source code
("p" "Templates for projects")
("pt" "Project-local todo" entry ; {project-root}/todo.org
(file+headline +org-capture-project-todo-file "Inbox")
"* TODO %?\n%i\n%a" :prepend t)
("pn" "Project-local notes" entry ; {project-root}/notes.org
(file+headline +org-capture-project-notes-file "Inbox")
"* %U %?\n%i\n%a" :prepend t)
("pc" "Project-local changelog" entry ; {project-root}/changelog.org
(file+headline +org-capture-project-changelog-file "Unreleased")
"* %U %?\n%i\n%a" :prepend t)
)
)
(use-package! ox-extra
:config
(ox-extras-activate '(ignore-headlines latex-header-blocks))
)
(use-package! ox-latex
:init
;; code here will run immediately
:config
;; code here will run after the package is loaded
(setq org-latex-pdf-process
'("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"bibtex %b"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
(setq org-latex-with-hyperref nil) ;; stop org adding hypersetup{author..} to latex export
;; (setq org-latex-prefer-user-labels t)
;; deleted unwanted file extensions after latexMK
(setq org-latex-logfiles-extensions
(quote ("lof" "lot" "tex~" "aux" "idx" "log" "out" "toc" "nav" "snm" "vrb" "dvi" "fdb_latexmk" "blg" "brf" "fls" "entoc" "ps" "spl" "bbl" "xmpi" "run.xml" "bcf" "acn" "acr" "alg" "glg" "gls" "ist")))
(unless (boundp 'org-latex-classes)
(setq org-latex-classes nil)))
;;(setq org-latex-packages-alist '(("margin=0.5in" "geometry")))
;; (setq org-latex-packages-alist '(("" "booktabs")))
(setq org-latex-listings 'minted
org-latex-packages-alist '(("" "minted")))
;; org-latex-pdf-process
;; '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
;; "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
)
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups
'(;; Each group has an implicit boolean OR operator between its selectors.
(:name "Today" ; Optionally specify section name
:time-grid t ; Items that appear on the time grid
:todo "TODAY") ; Items that have this TODO keyword
(:name "Important"
:priority "A")
;; Set order of multiple groups at once
(:name "Shopping"
:tag "shopping")
(:name "Recipes"
;; Multiple args given in list with implicit OR
:tag ("food"))
(:name "Habits"
:habit t)
(:name "School"
:tag "school")
(:name "coding"
:tag "coding")
(:name "next"
:tag "next"
:scheduled nil)
;; Groups supply their own section names when none are given
(:todo "WAITING" :order 8) ; Set order of this section
(:todo ("SOMEDAY" "TO-READ" "CHECK" "TO-WATCH" "WATCHING")
;; Show this group at the end of the agenda (since it has the
;; highest number). If you specified this group last, items
;; with these todo keywords that e.g. have priority A would be
;; displayed in that group instead, because items are grouped
;; out in the order the groups are listed.
:order 9)
(:priority<= "B"
;; Show this section after "Today" and "Important", because
;; their order is unspecified, defaulting to 0. Sections
;; are displayed lowest-number-first.
:order 1)
;; After the last group, the agenda will display items that didn't
;; match any of these groups, with the default order position of 99
))
:config (org-super-agenda-mode))
(after! (org-agenda org-super-agenda)
(setq! org-super-agenda-header-map (make-sparse-keymap))
(setq! org-agenda-custom-commands '(("h" "my custom agenda view"
((alltodo "" ((org-agenda-overriding-header "")
(org-super-agenda-groups
'(
(:name "Important"
:priority "A")
(:name "Projects"
:todo "PROJ"
:children t
:order 1)
(:name "To Process"
:file-path "inbox\\.org"
:order 2)
(:name "School"
:tag "school"
:order 3)
(:order-multi (2 (:name "Shopping for Food items"
;; Boolean AND group matches items that match all subgroups
:and (:tag "shopping"))
(:name "Food and cooking"
;; Multiple args given in list with implicit OR
:tag ("food" "cooking"))))
(:discard (:anything t))
)))))
)))
)
(map! :leader "a" #'org-agenda)
(after! org-agenda
(org-super-agenda-mode))
(setq org-agenda-skip-scheduled-if-done t
org-agenda-skip-deadline-if-done t
org-agenda-include-deadlines t
org-agenda-block-separator nil
org-agenda-tags-column 100 ;; from testing this seems to be a good value
org-agenda-compact-blocks t)
(use-package! anki-editor
:config
(setq anki-editor-create-decks t))
;; (map! :localleader
;; :map org-mode-map
;; (:prefix ("k" . "Anki")
;; :desc "Push" "p" 'anki-editor-push-notes
;; :desc "Retry" "r" 'anki-editor-retry-failure-notes
;; :desc "Insert" "n" 'anki-editor-insert-note
;; (:prefix ("c" . "Cloze")
;; :desc "Dwim" "d" 'anki-editor-cloze-dwim
;; :desc "Region" "r" 'anki-editor-cloze-region
;; )
;; )
;; )
;; (use-package! ob-mermaid
;; :config
;; (setq ob-mermaid-cli-path "~/node_modules/.bin/mmdc"))
(use-package! mermaid-mode
:mode "\\.mmd\\'"
:config
(setq mermaid-mmdc-location "~/custom_packages/node_modules/.bin/mmdc"))
;; (use-package! org-roam-server
;; :ensure t
;; :config
;; (setq org-roam-server-host "127.0.0.1"
;; org-roam-server-port 8080
;; org-roam-server-export-inline-images t
;; org-roam-server-authenticate nil
;; org-roam-server-label-truncate t
;; org-roam-server-label-truncate-length 60
;; org-roam-server-label-wrap-length 20))
(use-package! org-roam
:init
;; (map! :leader
;; :prefix "r"
;; :desc "org-roam" "l" #'org-roam-buffer-toggle
;; :desc "org-roam-node-insert" "i" #'org-roam-node-insert
;; :desc "org-roam-node-find" "f" #'org-roam-node-find
;; :desc "org-roam-ref-find" "r" #'org-roam-ref-find
;; :desc "org-roam-show-graph" "g" #'org-roam-show-graph
;; :desc "org-roam-capture" "c" #'org-roam-capture
;; :desc "org-roam-dailies-capture-today" "j" #'org-roam-dailies-capture-today)
;; (setq org-roam-directory (concat org-directory "roam")
;; org-roam-db-gc-threshold most-positive-fixnum
;; org-id-link-to-org-use-id t)
;; (add-to-list 'display-buffer-alist
;; '(("\\*org-roam\\*"
;; (display-buffer-in-direction)
;; (direction . right)
;; (window-width . 0.33)
;; (window-height . fit-window-to-buffer))))
:config
(setq org-roam-capture-templates
'(("d" "default" plain
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)
("l" "lit" entry
"* %?"
:if-new (file+head "lit/${slug}.org"
"#+title: ${title}\n")
:clock-in
:clock-keep
:immediate-finish t
:unnarrowed t)
("p" "private" plain (function org-roam-capture--get-point)
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)))
(setq org-roam-dailies-directory "daily/")
(setq org-roam-db-location (expand-file-name "roam/org-roam.db" org-directory))
(setq org-roam-dailies-capture-templates
'(("d" "default" entry
"* %?"
:if-new (file+head "%<%Y-%m-%d>.org"
"#+title: %<%Y-%m-%d>\n"))))
;; (set-company-backend! 'org-mode '(company-capf))
)
(after! org
(require 'appt)
(require 'notifications)
(setq appt-time-msg-list nil) ;; clear existing appt list
(setq appt-display-interval '5) ;; warn every 5 minutes from t - appt-message-warning-time
(setq
appt-message-warning-time '15 ;; send first warning 15 minutes before appointment
appt-display-mode-line nil ;; don't show in the modeline
appt-display-format 'window) ;; pass warnings to the designated window function
(setq appt-disp-window-function (function ct/appt-display-native))
(appt-activate 1) ;; activate appointment notification
; (display-time) ;; Clock in modeline
(defun ct/appt-display-native (min-to-app new-time msg)
(notifications-notify
:title (format "Event in %s minutes" min-to-app) ; Title
:body (format "%s" msg)
:urgency 'normal
))
;; Agenda-to-appointent hooks
(org-agenda-to-appt) ;; generate the appt list from org agenda files on emacs launch
(run-at-time "24:01" 3600 'org-agenda-to-appt) ;; update appt list hourly
(add-hook 'org-finalize-agenda-hook 'org-agenda-to-appt) ;; update appt list on agenda view
)
(setq org-cite-csl-styles-dir "~/Zotero/styles"
citar-bibliography "~/org/roam/biblio.bib"
citar-notes-paths '("~/org/roam/lit")
org-cite-global-bibliography '("~/org/roam/biblio.bib")
)
(use-package org-recur
:hook ((org-mode . org-recur-mode)
(org-agenda-mode . org-recur-agenda-mode))
:config
(setq org-recur-finish-done t
org-recur-finish-archive t))
(map! :map org-recur-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
(map! :map org-recur-agenda-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
;; Sets the languagetool java class path to the correct place
;;(setq langtool-java-classpath (concat (shell-command-to-string "nix eval --raw nixos.languagetool") "/share/*"))
(let ((server (executable-find "languagetool-commandline")))
(if server (setq langtool-bin server)))
(use-package! nov
:mode ("\\.epub\\'" . nov-mode)
:hook (nov-mode . mixed-pitch-mode)
:hook (nov-mode . visual-line-mode)
:hook (nov-mode . visual-fill-column-mode)
:config
(setq nov-text-width t)
(setq nov-variable-pitch nil))
(after! elfeed
(setq elfeed-search-filter "@1-week-ago +unread +daily")
(add-hook! 'elfeed-search-mode-hook 'elfeed-update)
)
(defun elfeed-v-mpv (url)
"Watch a video from URL in MPV"
(async-shell-command (format "mpv \"%s\"" url)))
(defun my/elfeed-view-mpv (&optional use-generic-p)
"Youtube-feed link"
(interactive "P")
(let ((entries (elfeed-search-selected)))
(cl-loop for entry in entries
do (elfeed-untag entry 'unread)
when (elfeed-entry-link entry)
do (elfeed-v-mpv it))
(mapc #'elfeed-search-update-entry entries)
(unless (use-region-p) (forward-line))))
(map! :map elfeed-search-mode-map
:after elfeed
:g "M-v" #'my/elfeed-view-mpv
)
;;(use-package! lsp-ui
;; :config
;;(setq lsp-ui-sideline-show-hover t))
;; (use-package! lsp
;; :config
;; (setq lsp-enable-symbol-highlighting 'nil))
(after! cc-mode
(setq c-basic-offset 2)
(setq tab-width 2))
(setq python-shell-interpreter "python3"
flycheck-python-pycompile-executable "python3")
;;(use-package! lsp-python-ms
;;:init
;;(setq lsp-python-ms-executable (executable-find "python-language-server")))
(add-hook! 'rainbow-mode-hook
(hl-line-mode (if rainbow-mode -1 +1)))
;; (after! dante
;; (add-to-list 'flycheck-disabled-checkers 'haskell-hlint))
(after! lsp-haskell
(setq lsp-haskell-server-path "haskell-language-server"))
(use-package! scad-mode
:mode "\\.scad$")
(use-package! kbd-mode
:mode ("\\.kbd\\'" . kbd-mode))
(use-package! graphviz-dot-mode
:config
(setq graphviz-dot-indent-width 4))
(map! :map org-present-mode-keymap
:g [C-right] #'org-present-next
:g [C-left] #'org-present-prev
)
(after! org-tree-slide (setq org-tree-slide-never-touch-face t))
;; Opens video file in mpv
;; using openwith for this is a kind of bloated solution, however it works
(use-package! openwith
:after-call pre-command-hook
:config
(openwith-mode t)
(setq openwith-associations '(("\\.mp4\\'" "mpv" (file)) ("\\.webm\\'" "mpv" (file)) ("\\.mkv\\'" "mpv" (file))))
)
(after! circe
(set-irc-server! "irc.libera.chat"
`(
:tls t
:port 6697
:nick "thiskappaisgrey"
:nickserv-nick "thiskappaisgrey"
:channels ("#haskell-language-server" "#emacs")
:nickserv-password (lambda (&rest _) (+pass-get-secret "irc/libera.chat"))
)))
| 49256 | ;;; $DOOMDIR/config.el -*- lexical-binding: t; -*-
;; Here are some additional functions/macros that could help you configure Doom:
;;
;; - `load!' for loading external *.el files relative to this one
;; - `use-package' for configuring packages
;; - `after!' for running code after a package has loaded
;; - `add-load-path!' for adding directories to the `load-path', where Emacs
;; looks when you load packages with `require' or `use-package'.
;; - `map!' for binding new keys
;;
;; To get information about any of these functions/macros, move the cursor over
;; the highlighted symbol at press 'K' (non-evil users must press 'C-c g k').
;; This will open documentation for it, including demos of how they are used.
;;
;; You can also try 'gd' (or 'C-c g d') to jump to their definition and see how
;; they are implemented.
(setq user-full-name "<NAME>")
(after! mu4e
(setq! mu4e-get-mail-command "mbsync -c ~/.config/mbsync/mbsyncrc -a")
(setq mu4e-change-filenames-when-moving t)
)
(set-email-account! "ucsb"
'((user-mail-address . "<EMAIL>")
(smtpmail-smtp-user . "<EMAIL>")
(mu4e-drafts-folder . "/ucsb/[acc1].Drafts")
(mu4e-refile-folder . "/ucsb/[acc1].Archive")
(mu4e-sent-folder . "/ucsb/[acc1].Sent Mail")
(mu4e-trash-folder . "/ucsb/[acc1].Trash")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-service . 587)
(mu4e-compose-signature . "Best,\n Th<NAME>chaumnuaiwit"))
t)
(set-email-account! "personal-gmail"
'((mu4e-sent-folder . "/personal-gmail/[acc2].Sent Mail")
(mu4e-drafts-folder . "/personal-gmail/[acc2].Drafts")
(mu4e-trash-folder . "/personal-gmail/[acc2].Trash")
(mu4e-refile-folder . "/personal-gmail/[acc2].Archive")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-user . "<EMAIL>")
(user-mail-address . "<EMAIL>") ;; only needed for mu < 1.4
(mu4e-compose-signature . "You can find me at https://thanawat.xyz\n---\nThanawat Techaumnuaiwit"))
nil)
(add-to-list 'load-path "/run/current-system/sw/share/emacs/site-lisp/mu4e/")
(setq enable-local-variables t)
(setq doom-font (font-spec :family "Hasklug Nerd Font Mono" :size 18))
(after! ispell
(setq ispell-dictionary "en"))
;; If you want to change the style of line numbers, change this to `relative' or
;; `nil' to disable it:
(setq display-line-numbers-type 'relative)
;; Makes visual-lines work better
(setq visual-fill-column-center-text t)
(add-to-list 'default-frame-alist '(fullscreen . maximized))
(setq doom-theme 'doom-oceanic-next)
;; explcitly set the frametitle because otherwise the frame title would show weird characters
;; https://www.emacswiki.org/emacs/FrameTitle
(setq frame-title-format "%b - Doom Emacs")
(set-popup-rules!
'(("^\\*info\\*" :slot 2 :side left :width 85 :quit nil)))
(display-battery-mode)
;; (use-package dashboard
;; :init ;; tweak dashboard config before loading it
;; (setq dashboard-set-heading-icons t)
;; (setq dashboard-set-file-icons t)
;; (setq dashboard-banner-logo-title "Emacs Is More Than A Text Editor!")
;; (setq dashboard-startup-banner 'logo) ;; use standard emacs logo as banner
;; (setq dashboard-center-content nil) ;; set to 't' for centered content
;; (setq dashboard-items '((recents . 5)
;; (agenda . 5 )
;; (bookmarks . 5)
;; (projects . 5)
;; (registers . 5)))
;; :config
;; (dashboard-setup-startup-hook)
;; (dashboard-modify-heading-icons '((recents . "file-text")
;; (bookmarks . "book")))
;; )
(setq evil-escape-key-sequence "fd")
(map! :leader
:desc "rss" "o s" #'=rss)
;;Make evil-mode up/down operate in screen lines instead of logical lines
;; (define-key evil-motion-state-map "j" 'evil-next-visual-line)
;; (define-key evil-motion-state-map "k" 'evil-previous-visual-line)
;;Also in visual mode
;; (define-key evil-visual-state-map "j" 'evil-next-visual-line)
;; (define-key evil-visual-state-map "k" 'evil-previous-visual-line)
(setq avy-keys '(?a ?s ?e ?t ?g ?y ?n ?i ?o ?h))
(map!
:map smartparens-mode-map
;; smartparens maps (navigation ops)
:nvie "C-M-f" #'sp-forward-sexp
:nvie "C-M-b" #'sp-backward-sexp
:nvie "C-M-u" #'sp-backward-up-sexp
:nvie "C-M-d" #'sp-down-sexp
;; smartparens maps (split join slurp barf)
:nie "M-s" #'sp-split-sexp
:nie "M-j" #'sp-join-sexp
:nvie "C->" #'sp-forward-slurp-sexp
:nvie "C-<" #'sp-forward-barf-sexp
:nvie "C-{" #'sp-backward-slurp-sexp
:nvie "C-}" #'sp-backward-barf-sexp)
(after! org
(setq org-directory "~/org/"
org-agenda-files '("~/org/gtd/inbox.org" "~/org/gtd/tickler.org" "~/org/gtd/gtd.org" "~/org/gtd/habits.org")
org-re-reveal-root "/home/thanawat/reveal.js/"
org-export-with-toc nil
org-hide-emphasis-markers t
org-log-into-drawer t
org-log-done 'time
org-export-with-section-numbers nil)
(add-to-list 'org-modules 'org-habit t)
(setcar (nthcdr 4 org-emphasis-regexp-components) 10)
(org-set-emph-re 'org-emphasis-regexp-components org-emphasis-regexp-components)
)
(after! org
(setq org-capture-templates
'(("t" "Todos" entry (file+headline "gtd/inbox.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("T" "Tickler" entry (file+headline "gtd/tickler.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("r" "Resources" entry (file+headline "gtd/resources.org" "Inbox") "* TODO %?" :prepend t)
("e" "Emacs + Vim tricks" entry (file+headline "emacs-tips.org" "Inbox") "* TODO %?" :prepend t)
;; copied from doom source code
("p" "Templates for projects")
("pt" "Project-local todo" entry ; {project-root}/todo.org
(file+headline +org-capture-project-todo-file "Inbox")
"* TODO %?\n%i\n%a" :prepend t)
("pn" "Project-local notes" entry ; {project-root}/notes.org
(file+headline +org-capture-project-notes-file "Inbox")
"* %U %?\n%i\n%a" :prepend t)
("pc" "Project-local changelog" entry ; {project-root}/changelog.org
(file+headline +org-capture-project-changelog-file "Unreleased")
"* %U %?\n%i\n%a" :prepend t)
)
)
(use-package! ox-extra
:config
(ox-extras-activate '(ignore-headlines latex-header-blocks))
)
(use-package! ox-latex
:init
;; code here will run immediately
:config
;; code here will run after the package is loaded
(setq org-latex-pdf-process
'("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"bibtex %b"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
(setq org-latex-with-hyperref nil) ;; stop org adding hypersetup{author..} to latex export
;; (setq org-latex-prefer-user-labels t)
;; deleted unwanted file extensions after latexMK
(setq org-latex-logfiles-extensions
(quote ("lof" "lot" "tex~" "aux" "idx" "log" "out" "toc" "nav" "snm" "vrb" "dvi" "fdb_latexmk" "blg" "brf" "fls" "entoc" "ps" "spl" "bbl" "xmpi" "run.xml" "bcf" "acn" "acr" "alg" "glg" "gls" "ist")))
(unless (boundp 'org-latex-classes)
(setq org-latex-classes nil)))
;;(setq org-latex-packages-alist '(("margin=0.5in" "geometry")))
;; (setq org-latex-packages-alist '(("" "booktabs")))
(setq org-latex-listings 'minted
org-latex-packages-alist '(("" "minted")))
;; org-latex-pdf-process
;; '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
;; "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
)
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups
'(;; Each group has an implicit boolean OR operator between its selectors.
(:name "Today" ; Optionally specify section name
:time-grid t ; Items that appear on the time grid
:todo "TODAY") ; Items that have this TODO keyword
(:name "Important"
:priority "A")
;; Set order of multiple groups at once
(:name "Shopping"
:tag "shopping")
(:name "Recipes"
;; Multiple args given in list with implicit OR
:tag ("food"))
(:name "Habits"
:habit t)
(:name "School"
:tag "school")
(:name "coding"
:tag "coding")
(:name "next"
:tag "next"
:scheduled nil)
;; Groups supply their own section names when none are given
(:todo "WAITING" :order 8) ; Set order of this section
(:todo ("SOMEDAY" "TO-READ" "CHECK" "TO-WATCH" "WATCHING")
;; Show this group at the end of the agenda (since it has the
;; highest number). If you specified this group last, items
;; with these todo keywords that e.g. have priority A would be
;; displayed in that group instead, because items are grouped
;; out in the order the groups are listed.
:order 9)
(:priority<= "B"
;; Show this section after "Today" and "Important", because
;; their order is unspecified, defaulting to 0. Sections
;; are displayed lowest-number-first.
:order 1)
;; After the last group, the agenda will display items that didn't
;; match any of these groups, with the default order position of 99
))
:config (org-super-agenda-mode))
(after! (org-agenda org-super-agenda)
(setq! org-super-agenda-header-map (make-sparse-keymap))
(setq! org-agenda-custom-commands '(("h" "my custom agenda view"
((alltodo "" ((org-agenda-overriding-header "")
(org-super-agenda-groups
'(
(:name "Important"
:priority "A")
(:name "Projects"
:todo "PROJ"
:children t
:order 1)
(:name "To Process"
:file-path "inbox\\.org"
:order 2)
(:name "School"
:tag "school"
:order 3)
(:order-multi (2 (:name "Shopping for Food items"
;; Boolean AND group matches items that match all subgroups
:and (:tag "shopping"))
(:name "Food and cooking"
;; Multiple args given in list with implicit OR
:tag ("food" "cooking"))))
(:discard (:anything t))
)))))
)))
)
(map! :leader "a" #'org-agenda)
(after! org-agenda
(org-super-agenda-mode))
(setq org-agenda-skip-scheduled-if-done t
org-agenda-skip-deadline-if-done t
org-agenda-include-deadlines t
org-agenda-block-separator nil
org-agenda-tags-column 100 ;; from testing this seems to be a good value
org-agenda-compact-blocks t)
(use-package! anki-editor
:config
(setq anki-editor-create-decks t))
;; (map! :localleader
;; :map org-mode-map
;; (:prefix ("k" . "<NAME>")
;; :desc "Push" "p" 'anki-editor-push-notes
;; :desc "Retry" "r" 'anki-editor-retry-failure-notes
;; :desc "Insert" "n" 'anki-editor-insert-note
;; (:prefix ("c" . "Cloze")
;; :desc "Dwim" "d" 'anki-editor-cloze-dwim
;; :desc "Region" "r" 'anki-editor-cloze-region
;; )
;; )
;; )
;; (use-package! ob-mermaid
;; :config
;; (setq ob-mermaid-cli-path "~/node_modules/.bin/mmdc"))
(use-package! mermaid-mode
:mode "\\.mmd\\'"
:config
(setq mermaid-mmdc-location "~/custom_packages/node_modules/.bin/mmdc"))
;; (use-package! org-roam-server
;; :ensure t
;; :config
;; (setq org-roam-server-host "127.0.0.1"
;; org-roam-server-port 8080
;; org-roam-server-export-inline-images t
;; org-roam-server-authenticate nil
;; org-roam-server-label-truncate t
;; org-roam-server-label-truncate-length 60
;; org-roam-server-label-wrap-length 20))
(use-package! org-roam
:init
;; (map! :leader
;; :prefix "r"
;; :desc "org-roam" "l" #'org-roam-buffer-toggle
;; :desc "org-roam-node-insert" "i" #'org-roam-node-insert
;; :desc "org-roam-node-find" "f" #'org-roam-node-find
;; :desc "org-roam-ref-find" "r" #'org-roam-ref-find
;; :desc "org-roam-show-graph" "g" #'org-roam-show-graph
;; :desc "org-roam-capture" "c" #'org-roam-capture
;; :desc "org-roam-dailies-capture-today" "j" #'org-roam-dailies-capture-today)
;; (setq org-roam-directory (concat org-directory "roam")
;; org-roam-db-gc-threshold most-positive-fixnum
;; org-id-link-to-org-use-id t)
;; (add-to-list 'display-buffer-alist
;; '(("\\*org-roam\\*"
;; (display-buffer-in-direction)
;; (direction . right)
;; (window-width . 0.33)
;; (window-height . fit-window-to-buffer))))
:config
(setq org-roam-capture-templates
'(("d" "default" plain
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)
("l" "lit" entry
"* %?"
:if-new (file+head "lit/${slug}.org"
"#+title: ${title}\n")
:clock-in
:clock-keep
:immediate-finish t
:unnarrowed t)
("p" "private" plain (function org-roam-capture--get-point)
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)))
(setq org-roam-dailies-directory "daily/")
(setq org-roam-db-location (expand-file-name "roam/org-roam.db" org-directory))
(setq org-roam-dailies-capture-templates
'(("d" "default" entry
"* %?"
:if-new (file+head "%<%Y-%m-%d>.org"
"#+title: %<%Y-%m-%d>\n"))))
;; (set-company-backend! 'org-mode '(company-capf))
)
(after! org
(require 'appt)
(require 'notifications)
(setq appt-time-msg-list nil) ;; clear existing appt list
(setq appt-display-interval '5) ;; warn every 5 minutes from t - appt-message-warning-time
(setq
appt-message-warning-time '15 ;; send first warning 15 minutes before appointment
appt-display-mode-line nil ;; don't show in the modeline
appt-display-format 'window) ;; pass warnings to the designated window function
(setq appt-disp-window-function (function ct/appt-display-native))
(appt-activate 1) ;; activate appointment notification
; (display-time) ;; Clock in modeline
(defun ct/appt-display-native (min-to-app new-time msg)
(notifications-notify
:title (format "Event in %s minutes" min-to-app) ; Title
:body (format "%s" msg)
:urgency 'normal
))
;; Agenda-to-appointent hooks
(org-agenda-to-appt) ;; generate the appt list from org agenda files on emacs launch
(run-at-time "24:01" 3600 'org-agenda-to-appt) ;; update appt list hourly
(add-hook 'org-finalize-agenda-hook 'org-agenda-to-appt) ;; update appt list on agenda view
)
(setq org-cite-csl-styles-dir "~/Zotero/styles"
citar-bibliography "~/org/roam/biblio.bib"
citar-notes-paths '("~/org/roam/lit")
org-cite-global-bibliography '("~/org/roam/biblio.bib")
)
(use-package org-recur
:hook ((org-mode . org-recur-mode)
(org-agenda-mode . org-recur-agenda-mode))
:config
(setq org-recur-finish-done t
org-recur-finish-archive t))
(map! :map org-recur-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
(map! :map org-recur-agenda-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
;; Sets the languagetool java class path to the correct place
;;(setq langtool-java-classpath (concat (shell-command-to-string "nix eval --raw nixos.languagetool") "/share/*"))
(let ((server (executable-find "languagetool-commandline")))
(if server (setq langtool-bin server)))
(use-package! nov
:mode ("\\.epub\\'" . nov-mode)
:hook (nov-mode . mixed-pitch-mode)
:hook (nov-mode . visual-line-mode)
:hook (nov-mode . visual-fill-column-mode)
:config
(setq nov-text-width t)
(setq nov-variable-pitch nil))
(after! elfeed
(setq elfeed-search-filter "@1-week-ago +unread +daily")
(add-hook! 'elfeed-search-mode-hook 'elfeed-update)
)
(defun elfeed-v-mpv (url)
"Watch a video from URL in MPV"
(async-shell-command (format "mpv \"%s\"" url)))
(defun my/elfeed-view-mpv (&optional use-generic-p)
"Youtube-feed link"
(interactive "P")
(let ((entries (elfeed-search-selected)))
(cl-loop for entry in entries
do (elfeed-untag entry 'unread)
when (elfeed-entry-link entry)
do (elfeed-v-mpv it))
(mapc #'elfeed-search-update-entry entries)
(unless (use-region-p) (forward-line))))
(map! :map elfeed-search-mode-map
:after elfeed
:g "M-v" #'my/elfeed-view-mpv
)
;;(use-package! lsp-ui
;; :config
;;(setq lsp-ui-sideline-show-hover t))
;; (use-package! lsp
;; :config
;; (setq lsp-enable-symbol-highlighting 'nil))
(after! cc-mode
(setq c-basic-offset 2)
(setq tab-width 2))
(setq python-shell-interpreter "python3"
flycheck-python-pycompile-executable "python3")
;;(use-package! lsp-python-ms
;;:init
;;(setq lsp-python-ms-executable (executable-find "python-language-server")))
(add-hook! 'rainbow-mode-hook
(hl-line-mode (if rainbow-mode -1 +1)))
;; (after! dante
;; (add-to-list 'flycheck-disabled-checkers 'haskell-hlint))
(after! lsp-haskell
(setq lsp-haskell-server-path "haskell-language-server"))
(use-package! scad-mode
:mode "\\.scad$")
(use-package! kbd-mode
:mode ("\\.kbd\\'" . kbd-mode))
(use-package! graphviz-dot-mode
:config
(setq graphviz-dot-indent-width 4))
(map! :map org-present-mode-keymap
:g [C-right] #'org-present-next
:g [C-left] #'org-present-prev
)
(after! org-tree-slide (setq org-tree-slide-never-touch-face t))
;; Opens video file in mpv
;; using openwith for this is a kind of bloated solution, however it works
(use-package! openwith
:after-call pre-command-hook
:config
(openwith-mode t)
(setq openwith-associations '(("\\.mp4\\'" "mpv" (file)) ("\\.webm\\'" "mpv" (file)) ("\\.mkv\\'" "mpv" (file))))
)
(after! circe
(set-irc-server! "irc.libera.chat"
`(
:tls t
:port 6697
:nick "thiskappaisgrey"
:nickserv-nick "thiskappaisgrey"
:channels ("#haskell-language-server" "#emacs")
:nickserv-password (lambda (&rest _) (+pass-get-secret "irc/libera.chat"))
)))
| true | ;;; $DOOMDIR/config.el -*- lexical-binding: t; -*-
;; Here are some additional functions/macros that could help you configure Doom:
;;
;; - `load!' for loading external *.el files relative to this one
;; - `use-package' for configuring packages
;; - `after!' for running code after a package has loaded
;; - `add-load-path!' for adding directories to the `load-path', where Emacs
;; looks when you load packages with `require' or `use-package'.
;; - `map!' for binding new keys
;;
;; To get information about any of these functions/macros, move the cursor over
;; the highlighted symbol at press 'K' (non-evil users must press 'C-c g k').
;; This will open documentation for it, including demos of how they are used.
;;
;; You can also try 'gd' (or 'C-c g d') to jump to their definition and see how
;; they are implemented.
(setq user-full-name "PI:NAME:<NAME>END_PI")
(after! mu4e
(setq! mu4e-get-mail-command "mbsync -c ~/.config/mbsync/mbsyncrc -a")
(setq mu4e-change-filenames-when-moving t)
)
(set-email-account! "ucsb"
'((user-mail-address . "PI:EMAIL:<EMAIL>END_PI")
(smtpmail-smtp-user . "PI:EMAIL:<EMAIL>END_PI")
(mu4e-drafts-folder . "/ucsb/[acc1].Drafts")
(mu4e-refile-folder . "/ucsb/[acc1].Archive")
(mu4e-sent-folder . "/ucsb/[acc1].Sent Mail")
(mu4e-trash-folder . "/ucsb/[acc1].Trash")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-service . 587)
(mu4e-compose-signature . "Best,\n ThPI:NAME:<NAME>END_PIchaumnuaiwit"))
t)
(set-email-account! "personal-gmail"
'((mu4e-sent-folder . "/personal-gmail/[acc2].Sent Mail")
(mu4e-drafts-folder . "/personal-gmail/[acc2].Drafts")
(mu4e-trash-folder . "/personal-gmail/[acc2].Trash")
(mu4e-refile-folder . "/personal-gmail/[acc2].Archive")
(smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil)))
(smtpmail-default-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-server . "smtp.gmail.com")
(smtpmail-smtp-user . "PI:EMAIL:<EMAIL>END_PI")
(user-mail-address . "PI:EMAIL:<EMAIL>END_PI") ;; only needed for mu < 1.4
(mu4e-compose-signature . "You can find me at https://thanawat.xyz\n---\nThanawat Techaumnuaiwit"))
nil)
(add-to-list 'load-path "/run/current-system/sw/share/emacs/site-lisp/mu4e/")
(setq enable-local-variables t)
(setq doom-font (font-spec :family "Hasklug Nerd Font Mono" :size 18))
(after! ispell
(setq ispell-dictionary "en"))
;; If you want to change the style of line numbers, change this to `relative' or
;; `nil' to disable it:
(setq display-line-numbers-type 'relative)
;; Makes visual-lines work better
(setq visual-fill-column-center-text t)
(add-to-list 'default-frame-alist '(fullscreen . maximized))
(setq doom-theme 'doom-oceanic-next)
;; explcitly set the frametitle because otherwise the frame title would show weird characters
;; https://www.emacswiki.org/emacs/FrameTitle
(setq frame-title-format "%b - Doom Emacs")
(set-popup-rules!
'(("^\\*info\\*" :slot 2 :side left :width 85 :quit nil)))
(display-battery-mode)
;; (use-package dashboard
;; :init ;; tweak dashboard config before loading it
;; (setq dashboard-set-heading-icons t)
;; (setq dashboard-set-file-icons t)
;; (setq dashboard-banner-logo-title "Emacs Is More Than A Text Editor!")
;; (setq dashboard-startup-banner 'logo) ;; use standard emacs logo as banner
;; (setq dashboard-center-content nil) ;; set to 't' for centered content
;; (setq dashboard-items '((recents . 5)
;; (agenda . 5 )
;; (bookmarks . 5)
;; (projects . 5)
;; (registers . 5)))
;; :config
;; (dashboard-setup-startup-hook)
;; (dashboard-modify-heading-icons '((recents . "file-text")
;; (bookmarks . "book")))
;; )
(setq evil-escape-key-sequence "fd")
(map! :leader
:desc "rss" "o s" #'=rss)
;;Make evil-mode up/down operate in screen lines instead of logical lines
;; (define-key evil-motion-state-map "j" 'evil-next-visual-line)
;; (define-key evil-motion-state-map "k" 'evil-previous-visual-line)
;;Also in visual mode
;; (define-key evil-visual-state-map "j" 'evil-next-visual-line)
;; (define-key evil-visual-state-map "k" 'evil-previous-visual-line)
(setq avy-keys '(?a ?s ?e ?t ?g ?y ?n ?i ?o ?h))
(map!
:map smartparens-mode-map
;; smartparens maps (navigation ops)
:nvie "C-M-f" #'sp-forward-sexp
:nvie "C-M-b" #'sp-backward-sexp
:nvie "C-M-u" #'sp-backward-up-sexp
:nvie "C-M-d" #'sp-down-sexp
;; smartparens maps (split join slurp barf)
:nie "M-s" #'sp-split-sexp
:nie "M-j" #'sp-join-sexp
:nvie "C->" #'sp-forward-slurp-sexp
:nvie "C-<" #'sp-forward-barf-sexp
:nvie "C-{" #'sp-backward-slurp-sexp
:nvie "C-}" #'sp-backward-barf-sexp)
(after! org
(setq org-directory "~/org/"
org-agenda-files '("~/org/gtd/inbox.org" "~/org/gtd/tickler.org" "~/org/gtd/gtd.org" "~/org/gtd/habits.org")
org-re-reveal-root "/home/thanawat/reveal.js/"
org-export-with-toc nil
org-hide-emphasis-markers t
org-log-into-drawer t
org-log-done 'time
org-export-with-section-numbers nil)
(add-to-list 'org-modules 'org-habit t)
(setcar (nthcdr 4 org-emphasis-regexp-components) 10)
(org-set-emph-re 'org-emphasis-regexp-components org-emphasis-regexp-components)
)
(after! org
(setq org-capture-templates
'(("t" "Todos" entry (file+headline "gtd/inbox.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("T" "Tickler" entry (file+headline "gtd/tickler.org" "Inbox") "* TODO %?\n%i\n%a" :prepend t)
("r" "Resources" entry (file+headline "gtd/resources.org" "Inbox") "* TODO %?" :prepend t)
("e" "Emacs + Vim tricks" entry (file+headline "emacs-tips.org" "Inbox") "* TODO %?" :prepend t)
;; copied from doom source code
("p" "Templates for projects")
("pt" "Project-local todo" entry ; {project-root}/todo.org
(file+headline +org-capture-project-todo-file "Inbox")
"* TODO %?\n%i\n%a" :prepend t)
("pn" "Project-local notes" entry ; {project-root}/notes.org
(file+headline +org-capture-project-notes-file "Inbox")
"* %U %?\n%i\n%a" :prepend t)
("pc" "Project-local changelog" entry ; {project-root}/changelog.org
(file+headline +org-capture-project-changelog-file "Unreleased")
"* %U %?\n%i\n%a" :prepend t)
)
)
(use-package! ox-extra
:config
(ox-extras-activate '(ignore-headlines latex-header-blocks))
)
(use-package! ox-latex
:init
;; code here will run immediately
:config
;; code here will run after the package is loaded
(setq org-latex-pdf-process
'("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"bibtex %b"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
"pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
(setq org-latex-with-hyperref nil) ;; stop org adding hypersetup{author..} to latex export
;; (setq org-latex-prefer-user-labels t)
;; deleted unwanted file extensions after latexMK
(setq org-latex-logfiles-extensions
(quote ("lof" "lot" "tex~" "aux" "idx" "log" "out" "toc" "nav" "snm" "vrb" "dvi" "fdb_latexmk" "blg" "brf" "fls" "entoc" "ps" "spl" "bbl" "xmpi" "run.xml" "bcf" "acn" "acr" "alg" "glg" "gls" "ist")))
(unless (boundp 'org-latex-classes)
(setq org-latex-classes nil)))
;;(setq org-latex-packages-alist '(("margin=0.5in" "geometry")))
;; (setq org-latex-packages-alist '(("" "booktabs")))
(setq org-latex-listings 'minted
org-latex-packages-alist '(("" "minted")))
;; org-latex-pdf-process
;; '("pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"
;; "pdflatex -shell-escape -interaction nonstopmode -output-directory %o %f"))
)
(use-package! org-super-agenda
:after org-agenda
:init
(setq org-super-agenda-groups
'(;; Each group has an implicit boolean OR operator between its selectors.
(:name "Today" ; Optionally specify section name
:time-grid t ; Items that appear on the time grid
:todo "TODAY") ; Items that have this TODO keyword
(:name "Important"
:priority "A")
;; Set order of multiple groups at once
(:name "Shopping"
:tag "shopping")
(:name "Recipes"
;; Multiple args given in list with implicit OR
:tag ("food"))
(:name "Habits"
:habit t)
(:name "School"
:tag "school")
(:name "coding"
:tag "coding")
(:name "next"
:tag "next"
:scheduled nil)
;; Groups supply their own section names when none are given
(:todo "WAITING" :order 8) ; Set order of this section
(:todo ("SOMEDAY" "TO-READ" "CHECK" "TO-WATCH" "WATCHING")
;; Show this group at the end of the agenda (since it has the
;; highest number). If you specified this group last, items
;; with these todo keywords that e.g. have priority A would be
;; displayed in that group instead, because items are grouped
;; out in the order the groups are listed.
:order 9)
(:priority<= "B"
;; Show this section after "Today" and "Important", because
;; their order is unspecified, defaulting to 0. Sections
;; are displayed lowest-number-first.
:order 1)
;; After the last group, the agenda will display items that didn't
;; match any of these groups, with the default order position of 99
))
:config (org-super-agenda-mode))
(after! (org-agenda org-super-agenda)
(setq! org-super-agenda-header-map (make-sparse-keymap))
(setq! org-agenda-custom-commands '(("h" "my custom agenda view"
((alltodo "" ((org-agenda-overriding-header "")
(org-super-agenda-groups
'(
(:name "Important"
:priority "A")
(:name "Projects"
:todo "PROJ"
:children t
:order 1)
(:name "To Process"
:file-path "inbox\\.org"
:order 2)
(:name "School"
:tag "school"
:order 3)
(:order-multi (2 (:name "Shopping for Food items"
;; Boolean AND group matches items that match all subgroups
:and (:tag "shopping"))
(:name "Food and cooking"
;; Multiple args given in list with implicit OR
:tag ("food" "cooking"))))
(:discard (:anything t))
)))))
)))
)
(map! :leader "a" #'org-agenda)
(after! org-agenda
(org-super-agenda-mode))
(setq org-agenda-skip-scheduled-if-done t
org-agenda-skip-deadline-if-done t
org-agenda-include-deadlines t
org-agenda-block-separator nil
org-agenda-tags-column 100 ;; from testing this seems to be a good value
org-agenda-compact-blocks t)
(use-package! anki-editor
:config
(setq anki-editor-create-decks t))
;; (map! :localleader
;; :map org-mode-map
;; (:prefix ("k" . "PI:NAME:<NAME>END_PI")
;; :desc "Push" "p" 'anki-editor-push-notes
;; :desc "Retry" "r" 'anki-editor-retry-failure-notes
;; :desc "Insert" "n" 'anki-editor-insert-note
;; (:prefix ("c" . "Cloze")
;; :desc "Dwim" "d" 'anki-editor-cloze-dwim
;; :desc "Region" "r" 'anki-editor-cloze-region
;; )
;; )
;; )
;; (use-package! ob-mermaid
;; :config
;; (setq ob-mermaid-cli-path "~/node_modules/.bin/mmdc"))
(use-package! mermaid-mode
:mode "\\.mmd\\'"
:config
(setq mermaid-mmdc-location "~/custom_packages/node_modules/.bin/mmdc"))
;; (use-package! org-roam-server
;; :ensure t
;; :config
;; (setq org-roam-server-host "127.0.0.1"
;; org-roam-server-port 8080
;; org-roam-server-export-inline-images t
;; org-roam-server-authenticate nil
;; org-roam-server-label-truncate t
;; org-roam-server-label-truncate-length 60
;; org-roam-server-label-wrap-length 20))
(use-package! org-roam
:init
;; (map! :leader
;; :prefix "r"
;; :desc "org-roam" "l" #'org-roam-buffer-toggle
;; :desc "org-roam-node-insert" "i" #'org-roam-node-insert
;; :desc "org-roam-node-find" "f" #'org-roam-node-find
;; :desc "org-roam-ref-find" "r" #'org-roam-ref-find
;; :desc "org-roam-show-graph" "g" #'org-roam-show-graph
;; :desc "org-roam-capture" "c" #'org-roam-capture
;; :desc "org-roam-dailies-capture-today" "j" #'org-roam-dailies-capture-today)
;; (setq org-roam-directory (concat org-directory "roam")
;; org-roam-db-gc-threshold most-positive-fixnum
;; org-id-link-to-org-use-id t)
;; (add-to-list 'display-buffer-alist
;; '(("\\*org-roam\\*"
;; (display-buffer-in-direction)
;; (direction . right)
;; (window-width . 0.33)
;; (window-height . fit-window-to-buffer))))
:config
(setq org-roam-capture-templates
'(("d" "default" plain
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)
("l" "lit" entry
"* %?"
:if-new (file+head "lit/${slug}.org"
"#+title: ${title}\n")
:clock-in
:clock-keep
:immediate-finish t
:unnarrowed t)
("p" "private" plain (function org-roam-capture--get-point)
"%?"
:if-new (file+head "${slug}.org"
"#+title: ${title}\n")
:immediate-finish t
:unnarrowed t)))
(setq org-roam-dailies-directory "daily/")
(setq org-roam-db-location (expand-file-name "roam/org-roam.db" org-directory))
(setq org-roam-dailies-capture-templates
'(("d" "default" entry
"* %?"
:if-new (file+head "%<%Y-%m-%d>.org"
"#+title: %<%Y-%m-%d>\n"))))
;; (set-company-backend! 'org-mode '(company-capf))
)
(after! org
(require 'appt)
(require 'notifications)
(setq appt-time-msg-list nil) ;; clear existing appt list
(setq appt-display-interval '5) ;; warn every 5 minutes from t - appt-message-warning-time
(setq
appt-message-warning-time '15 ;; send first warning 15 minutes before appointment
appt-display-mode-line nil ;; don't show in the modeline
appt-display-format 'window) ;; pass warnings to the designated window function
(setq appt-disp-window-function (function ct/appt-display-native))
(appt-activate 1) ;; activate appointment notification
; (display-time) ;; Clock in modeline
(defun ct/appt-display-native (min-to-app new-time msg)
(notifications-notify
:title (format "Event in %s minutes" min-to-app) ; Title
:body (format "%s" msg)
:urgency 'normal
))
;; Agenda-to-appointent hooks
(org-agenda-to-appt) ;; generate the appt list from org agenda files on emacs launch
(run-at-time "24:01" 3600 'org-agenda-to-appt) ;; update appt list hourly
(add-hook 'org-finalize-agenda-hook 'org-agenda-to-appt) ;; update appt list on agenda view
)
(setq org-cite-csl-styles-dir "~/Zotero/styles"
citar-bibliography "~/org/roam/biblio.bib"
citar-notes-paths '("~/org/roam/lit")
org-cite-global-bibliography '("~/org/roam/biblio.bib")
)
(use-package org-recur
:hook ((org-mode . org-recur-mode)
(org-agenda-mode . org-recur-agenda-mode))
:config
(setq org-recur-finish-done t
org-recur-finish-archive t))
(map! :map org-recur-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
(map! :map org-recur-agenda-mode-map
:after org-recur
:g "C-c d" #'org-recur-finish)
;; Sets the languagetool java class path to the correct place
;;(setq langtool-java-classpath (concat (shell-command-to-string "nix eval --raw nixos.languagetool") "/share/*"))
(let ((server (executable-find "languagetool-commandline")))
(if server (setq langtool-bin server)))
(use-package! nov
:mode ("\\.epub\\'" . nov-mode)
:hook (nov-mode . mixed-pitch-mode)
:hook (nov-mode . visual-line-mode)
:hook (nov-mode . visual-fill-column-mode)
:config
(setq nov-text-width t)
(setq nov-variable-pitch nil))
(after! elfeed
(setq elfeed-search-filter "@1-week-ago +unread +daily")
(add-hook! 'elfeed-search-mode-hook 'elfeed-update)
)
(defun elfeed-v-mpv (url)
"Watch a video from URL in MPV"
(async-shell-command (format "mpv \"%s\"" url)))
(defun my/elfeed-view-mpv (&optional use-generic-p)
"Youtube-feed link"
(interactive "P")
(let ((entries (elfeed-search-selected)))
(cl-loop for entry in entries
do (elfeed-untag entry 'unread)
when (elfeed-entry-link entry)
do (elfeed-v-mpv it))
(mapc #'elfeed-search-update-entry entries)
(unless (use-region-p) (forward-line))))
(map! :map elfeed-search-mode-map
:after elfeed
:g "M-v" #'my/elfeed-view-mpv
)
;;(use-package! lsp-ui
;; :config
;;(setq lsp-ui-sideline-show-hover t))
;; (use-package! lsp
;; :config
;; (setq lsp-enable-symbol-highlighting 'nil))
(after! cc-mode
(setq c-basic-offset 2)
(setq tab-width 2))
(setq python-shell-interpreter "python3"
flycheck-python-pycompile-executable "python3")
;;(use-package! lsp-python-ms
;;:init
;;(setq lsp-python-ms-executable (executable-find "python-language-server")))
(add-hook! 'rainbow-mode-hook
(hl-line-mode (if rainbow-mode -1 +1)))
;; (after! dante
;; (add-to-list 'flycheck-disabled-checkers 'haskell-hlint))
(after! lsp-haskell
(setq lsp-haskell-server-path "haskell-language-server"))
(use-package! scad-mode
:mode "\\.scad$")
(use-package! kbd-mode
:mode ("\\.kbd\\'" . kbd-mode))
(use-package! graphviz-dot-mode
:config
(setq graphviz-dot-indent-width 4))
(map! :map org-present-mode-keymap
:g [C-right] #'org-present-next
:g [C-left] #'org-present-prev
)
(after! org-tree-slide (setq org-tree-slide-never-touch-face t))
;; Opens video file in mpv
;; using openwith for this is a kind of bloated solution, however it works
(use-package! openwith
:after-call pre-command-hook
:config
(openwith-mode t)
(setq openwith-associations '(("\\.mp4\\'" "mpv" (file)) ("\\.webm\\'" "mpv" (file)) ("\\.mkv\\'" "mpv" (file))))
)
(after! circe
(set-irc-server! "irc.libera.chat"
`(
:tls t
:port 6697
:nick "thiskappaisgrey"
:nickserv-nick "thiskappaisgrey"
:channels ("#haskell-language-server" "#emacs")
:nickserv-password (lambda (&rest _) (+pass-get-secret "irc/libera.chat"))
)))
|
[
{
"context": "*- lexical-binding: t; -*-\n\n;; Copyright (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu",
"end": 120,
"score": 0.9998704195022583,
"start": 108,
"tag": "NAME",
"value": "John Kitchin"
},
{
"context": "-\n\n;; Copyright (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu>\n;; Keywords:\n\n;; This p",
"end": 145,
"score": 0.9998776912689209,
"start": 133,
"tag": "NAME",
"value": "John Kitchin"
},
{
"context": " (C) 2016 John Kitchin\n\n;; Author: John Kitchin <jkitchin@andrew.cmu.edu>\n;; Keywords:\n\n;; This program is free software; ",
"end": 170,
"score": 0.9999306201934814,
"start": 147,
"tag": "EMAIL",
"value": "jkitchin@andrew.cmu.edu"
},
{
"context": "ort an issue in org-ref.\nOpens https://github.com/jkitchin/org-ref/issues/new.\"\n (save-window-excursion\n ",
"end": 3235,
"score": 0.999405562877655,
"start": 3227,
"tag": "USERNAME",
"value": "jkitchin"
},
{
"context": " if you like.\")\n (browse-url \"https://github.com/jkitchin/org-ref/issues/new\"))\n\n\n;;* Debug(require 'org-re",
"end": 3478,
"score": 0.9997329711914062,
"start": 3470,
"tag": "USERNAME",
"value": "jkitchin"
},
{
"context": "does not exist.\nContributed by https://github.com/autosquid.\nArgument KEY is the bibtex key.\"\n (let* ((resul",
"end": 16833,
"score": 0.999411940574646,
"start": 16824,
"tag": "USERNAME",
"value": "autosquid"
},
{
"context": " t) to your init files\n- using https://github.com/emacscollective/auto-compile.\\n\" org-ref-elc org-ref-elc))\n\n\t\t ",
"end": 37612,
"score": 0.9265770316123962,
"start": 37597,
"tag": "USERNAME",
"value": "emacscollective"
}
] | elpa/org-ref-20210726.1533/org-ref-utils.el | ik314/.emacs.d | 0 | ;;; org-ref-utils.el --- Utility functions for org-ref -*- lexical-binding: t; -*-
;; Copyright (C) 2016 John Kitchin
;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
(eval-when-compile
(require 'cl-lib))
(require 'org)
(require 'org-ref-pdf) ; for pdftotext-executable
(defcustom org-ref-bib-html "<h1 class='org-ref-bib-h1'>Bibliography</h1>\n"
"HTML header to use for bibliography in HTML export."
:type 'string
:group 'org-ref)
(defcustom org-ref-bib-html-sorted nil
"Determine whether the HTML bibliography should be sorted."
:type 'boolean
:group 'org-ref)
(defcustom org-ref-search-whitespace-regexp "\\s-+"
"A whitespace regexp for use in `org-ref-strip-string."
:group 'org-ref)
(defvar org-ref-cite-types)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-notes-function)
(defvar org-ref-bibliography-entry-format)
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-key-in-file-p "org-ref-core.el")
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-under-cursor "org-ref-core.el")
;;; Code:
;;;###autoload
(defun org-ref-version ()
"Provide a version string for org-ref.
Copies the string to the clipboard."
(interactive)
;; version in the el file.
(let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(org-ref-dir (file-name-directory org-ref-el))
org-version
git-commit
version-string)
(setq org-version (with-temp-buffer
(insert-file-contents org-ref-el)
(goto-char (point-min))
(re-search-forward ";; Version:")
(s-trim (buffer-substring (point)
(line-end-position)))))
(setq git-commit
;; If in git, get current commit
(let ((default-directory org-ref-dir))
(when (and
;; this is tricky, as a submodule, .git is a file
(or (file-directory-p ".git") (file-exists-p ".git"))
(= 0 (shell-command "git rev-parse --git-dir")))
(format "%s in %s"
(s-trim (shell-command-to-string "git rev-parse HEAD"))
(s-trim (shell-command-to-string "git rev-parse --show-toplevel"))))))
(setq version-string (format "org-ref: Version %s%s"
org-version
(if git-commit
(format " (git-commit %s)" git-commit)
"")))
(kill-new version-string)
(message version-string)))
(defun org-ref-report-issue ()
"Report an issue in org-ref.
Opens https://github.com/jkitchin/org-ref/issues/new."
(save-window-excursion
(org-ref-debug)
(kill-new (buffer-string)))
(message "org-ref-debug has been run. You can paste the results in the issue website if you like.")
(browse-url "https://github.com/jkitchin/org-ref/issues/new"))
;;* Debug(require 'org-ref-pdf)
(defmacro ords (&rest body)
"Evaluate BODY and return a string."
`(format "%s" (progn ,@body)))
;;;###autoload
(defun org-ref-debug ()
"Print some debug information to a buffer."
(interactive)
(switch-to-buffer "*org-ref-debug*")
(erase-buffer)
(org-mode)
(insert
(s-format "#+TITLE: org-ref debug
${org-ref-version}
* Variables
1. org-ref-completion-library: ${org-ref-completion-library}
2. org-ref-bibliography-notes: ${org-ref-bibliography-notes} (exists ${orbn-p})
3. org-ref-default-bibliography: ${org-ref-default-bibliography} (exists ${ordb-p}) (listp ${ordb-listp})
4. org-ref-pdf-directory: ${org-ref-pdf-directory} (exists ${orpd-p})
* System
system-type: ${system}
system-configuration: ${system-configuration}
window system: ${window-system}
Emacs: ${emacs-version}
org-version: ${org-version}
* about org-ref
org-ref installed in ${org-ref-location}.
** Dependencies
helm-bibtex ${helm-bibtex-path}
* org-ref-pdf (loaded: ${org-ref-pdf-p})
system pdftotext: ${pdftotext}
You set pdftotext-executable to ${pdftotext-executable} (exists: ${pdftotext-executable-p})
* org-ref-url-utils (loaded: ${org-ref-url-p})
* export variables
org-latex-pdf-process:
${org-latex-pdf-process}
"
'aget
`(("org-ref-completion-library" . ,(format "%s" org-ref-completion-library))
("org-ref-bibliography-notes" . ,(format "%s" org-ref-bibliography-notes))
("org-ref-bibliography-notes exists" . ,(format "%s" (when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes))))
("org-ref-version" . ,(org-ref-version))
("org-latex-pdf-process" . ,(format "%S" org-latex-pdf-process))
("org-ref-default-bibliography" . ,(format "%s" org-ref-default-bibliography))
("ordb-p" . ,(format "%s" (mapcar 'file-exists-p org-ref-default-bibliography)))
("ordb-listp" . ,(ords (listp org-ref-default-bibliography)))
("orbn-p" . ,(when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes)))
("org-ref-pdf-directory" . ,(format "%s" org-ref-pdf-directory))
("orpd-p" . ,(format "%s" (file-exists-p org-ref-pdf-directory)))
("org-ref-location" . ,(format "%s" (locate-library "org-ref")))
("system" . ,(format "System: %s" system-type))
("system-configuration" . ,(ords system-configuration))
("window-system" . ,(format "Window system: %s" window-system))
("emacs-version" . ,(ords (emacs-version)))
("org-version" . ,(org-version))
("helm-bibtex-path" . ,(ords (locate-library "helm-bibtex")))
("org-ref-pdf-p" . ,(ords (featurep 'org-ref-pdf)))
("pdftotext" . ,(ords (if (featurep 'org-ref-pdf)
(executable-find "pdftotext")
"org-ref-pdf not loaded")))
("pdftotext-executable" . ,(ords (if (featurep 'org-ref-pdf)
pdftotext-executable
"org-ref-pdf not loaded")))
("pdftotext-executable-p" . ,(ords (if (featurep 'org-ref-pdf)
(or
(executable-find pdftotext-executable)
(file-exists-p pdftotext-executable))
"org-ref-pdf not loaded")))
("org-ref-url-p" . ,(ords (featurep 'org-ref-url)))))))
(defun org-ref-reftex-get-bib-field (field entry &optional format)
"Get FIELD from a bibtex ENTRY in optional FORMAT.
Similar to `reftex-get-bib-field', but removes enclosing braces
and quotes in FIELD in the bibtex ENTRY."
(let ((result))
(setq result (reftex-get-bib-field field entry format))
(when (and (not (string= result "")) (string= "{" (substring result 0 1)))
(setq result (substring result 1 -1)))
(when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
(setq result (substring result 1 -1)))
result))
(defun org-ref-reftex-format-citation (entry format)
"Format the bibtex ENTRY according to the FORMAT argument.
ENTRY is from `bibtex-parse-entry'
The FORMAT is a string with these percent escapes.
In the format, the following percent escapes will be expanded.
%l The BibTeX label of the citation.
%a List of author names, see also `reftex-cite-punctuation'.
%2a Like %a, but abbreviate more than 2 authors like Jones et al.
%A First author name only.
%e Works like %a, but on list of editor names. (%2e and %E work as well)
It is also possible to access all other BibTeX database fields:
%b booktitle %c chapter %d edition %h howpublished
%i institution %j journal %k key %m month
%n number %o organization %p pages %P first page
%r address %s school %u publisher %t title
%v volume %y year
%B booktitle, abbreviated %T title, abbreviated
%U url
%D doi
%S series %N note
%f pdf filename (key.pdf)
%F absolute pdf filename (returned from `org-ref-get-pdf-filename-function')
Usually, only %l is needed. The other stuff is mainly for the echo area
display, and for (setq reftex-comment-citations t).
%< as a special operator kills punctuation and space around it after the
string has been formatted.
A pair of square brackets indicates an optional argument, and RefTeX
will prompt for the values of these arguments.
Beware that all this only works with BibTeX database files. When
citations are made from the \bibitems in an explicit thebibliography
environment, only %l is available."
;; Format a citation from the info in the BibTeX ENTRY
(unless (stringp format) (setq format "\\cite{%l}"))
(if (and reftex-comment-citations
(string-match "%l" reftex-cite-comment-format))
(error "Reftex-cite-comment-format contains invalid %%l"))
(while (string-match
"\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
format)
(let ((n (string-to-number (match-string 4 format)))
(l (string-to-char (match-string 5 format)))
rpl b e)
(save-match-data
(setq rpl
(cond
((= l ?l) (concat
(org-ref-reftex-get-bib-field "&key" entry)
(if reftex-comment-citations
reftex-cite-comment-format
"")))
((= l ?a) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(reftex-format-names
(reftex-get-bib-names "author" entry)
(or n 2))))
((= l ?A) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(car (reftex-get-bib-names "author" entry))))
((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
((= l ?B) (reftex-abbreviate-title
(org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
((= l ?e) (reftex-format-names
(reftex-get-bib-names "editor" entry)
(or n 2)))
((= l ?E) (car (reftex-get-bib-names "editor" entry)))
((= l ?f) (concat (org-ref-reftex-get-bib-field "=key=" entry) ".pdf"))
((= l ?F) (funcall org-ref-get-pdf-filename-function
(org-ref-reftex-get-bib-field "=key=" entry)))
((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
(if (string= "" jt)
(reftex-get-bib-field "journaltitle" entry)
jt)))
((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
((= l ?N) (org-ref-reftex-get-bib-field "note" entry))
((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
((= l ?P) (car (split-string
(org-ref-reftex-get-bib-field "pages" entry)
"[- .]+")))
((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
;; strip enclosing brackets from title if they are there
((= l ?t) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry)))
((= l ?T) (reftex-abbreviate-title
(replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry))))
((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
(if (string= rpl "")
(setq b (match-beginning 2) e (match-end 2))
(setq b (match-beginning 3) e (match-end 3)))
(setq format (concat (substring format 0 b) rpl (substring format e)))))
(while (string-match "%%" format)
(setq format (replace-match "%" t t format)))
(while (string-match "[ ,.;:]*%<" format)
(setq format (replace-match "" t t format)))
format)
(defun org-ref-get-bibtex-entry-citation (key)
"Return a string for the bibliography entry corresponding to KEY.
Format according to the type in `org-ref-bibliography-entry-format'."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry) (bibtex-entry) (entry-type) (format))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq bibtex-entry (bibtex-parse-entry))
;; downcase field names so they work in the format-citation code
(dolist (cons-cell bibtex-entry)
(setf (car cons-cell) (downcase (car cons-cell))))
(setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
(setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
(if format
(setq entry (org-ref-reftex-format-citation bibtex-entry format))
;; if no format, we use the bibtex entry itself as a fallback
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))))
entry))
(defun org-ref-get-bibtex-entry (key)
"Return the bibtex entry as a string."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))
entry)))
;;*** key at point functions
(defun org-ref-get-pdf-filename (key)
"Return the pdf filename associated with a bibtex KEY.
This searches for the pattern KEY*.pdf. If one result is found it
is returned, but if multiple results are found, e.g. there are
related files to the KEY you are prompted for which one you want."
(if org-ref-pdf-directory
(let* ((pdf-dirs (if (listp org-ref-pdf-directory)
org-ref-pdf-directory
(list org-ref-pdf-directory)))
(pdfs (-flatten (--map (file-expand-wildcards
(f-join it (format "%s*.pdf" key)))
(-flatten pdf-dirs)))))
(cond
((= 0 (length pdfs))
(expand-file-name (format "%s.pdf" key) org-ref-pdf-directory))
((= 1 (length pdfs))
(car pdfs))
((> (length pdfs) 1)
(completing-read "Choose: " pdfs))))
;; No org-ref-pdf-directory defined so return just a file name.
(format "%s.pdf" key)))
(defun org-ref-get-mendeley-filename (key)
"Return the pdf filename indicated by mendeley file field.
Falls back to `org-ref-get-pdf-filename' if file field does not exist.
Contributed by https://github.com/autosquid.
Argument KEY is the bibtex key."
(let* ((results (org-ref-get-bibtex-key-and-file key))
(bibfile (cdr results))
entry)
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(let ((e (org-ref-reftex-get-bib-field "file" entry)))
(if (> (length e) 4)
(let ((clean-field (replace-regexp-in-string "{\\|}\\|\\\\" "" e)))
(let ((first-file (car (split-string clean-field ";" t))))
(format "/%s" (substring first-file 1
(- (length first-file) 4)))))
(format (concat
(file-name-as-directory org-ref-pdf-directory)
"%s.pdf")
key))))))
(defun org-ref-get-pdf-filename-helm-bibtex (key)
"Use helm-bibtex to retrieve a PDF filename for KEY.
helm-bibtex looks in both the configured directory
`bibtex-completion-library-path' and in the fields of the bibtex
item for a filename. It understands file fields exported by
Jabref, Mendeley and Zotero. See `bibtex-completion-find-pdf'."
(let ((bibtex-completion-bibliography (org-ref-find-bibliography)))
(or (car (bibtex-completion-find-pdf key)) "")))
;;;###autoload
(defun org-ref-open-pdf-at-point ()
"Open the pdf for bibtex key under point if it exists."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key)))
(if (file-exists-p pdf-file)
(org-open-file pdf-file)
(message "no pdf found for %s" key))))
;;;###autoload
(defun org-ref-open-url-at-point ()
"Open the url for bibtex key under point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(catch 'done
(let ((url (s-trim (bibtex-autokey-get-field "url"))))
(unless (s-blank? url)
(browse-url url)
(throw 'done nil)))
(let ((doi (s-trim (bibtex-autokey-get-field "doi"))))
(unless (s-blank? doi)
(if (string-match "^http" doi)
(browse-url doi)
(browse-url (format "http://dx.doi.org/%s" doi)))
(throw 'done nil))))))))
;;;###autoload
(defun org-ref-open-notes-at-point (&optional thekey)
"Open the notes for bibtex key under point in a cite link in a buffer.
Can also be called with THEKEY in a program."
(interactive)
(when (null thekey)
(setq thekey (org-ref-get-bibtex-key-under-cursor)))
(funcall org-ref-notes-function thekey))
;;;###autoload
(defun org-ref-citation-at-point ()
"Give message of current citation at point."
(interactive)
(org-ref-format-entry (org-ref-get-bibtex-key-under-cursor)))
;;;###autoload
(defun org-ref-open-citation-at-point ()
"Open bibtex file to key at point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(find-file bibfile)
(bibtex-search-entry key)))
;;*** cite menu
(defvar org-ref-cite-menu-funcs '()
"Functions to run on cite click menu.
Each entry is a list of (key menu-name function). The function
must take no arguments and work on the key at point. Do not
modify this variable, it is set to empty in the menu click
function, and functions are conditionally added to it.")
(defvar org-ref-user-cite-menu-funcs
'(("C" "rossref" org-ref-crossref-at-point)
("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
("s" "Copy summary" org-ref-copy-entry-as-summary))
"User-defined functions to run on bibtex key at point.")
;;;###autoload
(defun org-ref-copy-entry-as-summary ()
"Copy the bibtex entry for the citation at point as a summary."
(interactive)
(kill-new (org-ref-bib-citation)))
;;;###autoload
(defun org-ref-copy-cite-as-summary ()
"Copy a summary for the citation at point to the clipboard."
(interactive)
(kill-new (org-ref-link-message)))
;;;###autoload
(defun org-ref-copy-entry-at-point-to-file ()
"Copy the bibtex entry for the citation at point to NEW-FILE.
Prompt for NEW-FILE includes bib files in
`org-ref-default-bibliography', and bib files in current working
directory. You can also specify a new file."
(interactive)
(let ((new-file (completing-read
"Copy to bibfile: "
(append org-ref-default-bibliography
(f-entries "." (lambda (f) (f-ext? f "bib"))))))
(key (org-ref-get-bibtex-key-under-cursor)))
(save-window-excursion
(org-ref-open-citation-at-point)
(bibtex-copy-entry-as-kill))
(let ((bibtex-files (list (file-truename new-file))))
(if (assoc key (bibtex-global-key-alist))
(message "That key already exists in %s" new-file)
;; add to file
(save-window-excursion
(find-file new-file)
(goto-char (point-max))
;; make sure we are at the beginning of a line.
(unless (looking-at "^") (insert "\n\n"))
(bibtex-yank)
(save-buffer))))))
(defun org-ref-get-doi-at-point ()
"Get doi for key at point."
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results))
doi)
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(setq doi (bibtex-autokey-get-field "doi"))
;; in case doi is a url, remove the url part.
(replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
;;**** functions that operate on key at point for click menu
;;;###autoload
(defun org-ref-ads-at-point ()
"Open the doi in ADS for bibtex key under point."
(interactive)
(doi-utils-ads (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-at-point ()
"Open the doi in wos for bibtex key under point."
(interactive)
(doi-utils-wos (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-citing-at-point ()
"Open the doi in wos citing articles for bibtex key under point."
(interactive)
(doi-utils-wos-citing (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-related-at-point ()
"Open the doi in wos related articles for bibtex key under point."
(interactive)
(doi-utils-wos-related (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-google-scholar-at-point ()
"Search google scholar for bibtex key under point using the title."
(interactive)
(browse-url
(url-encode-url
(format
"http://scholar.google.com/scholar?q=%s"
(let* ((key-file (org-ref-get-bibtex-key-and-file))
(key (car key-file))
(file (cdr key-file))
entry)
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(org-ref-reftex-get-bib-field "title" entry)))))))
;;;###autoload
(defun org-ref-pubmed-at-point ()
"Open the doi in pubmed for bibtex key under point."
(interactive)
(doi-utils-pubmed (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-crossref-at-point ()
"Open the doi in crossref for bibtex key under point."
(interactive)
(doi-utils-crossref (org-ref-get-doi-at-point)))
;;* General org-ref utilities
(defun org-ref-strip-string (string)
"Strip leading and trailing whitespace from the STRING."
(replace-regexp-in-string
(concat org-ref-search-whitespace-regexp "$" ) ""
(replace-regexp-in-string
(concat "^" org-ref-search-whitespace-regexp ) "" string)))
(defun org-ref-split-and-strip-string (string)
"Split key-string and strip keys in STRING.
Assumes the key-string is comma delimited."
(mapcar 'org-ref-strip-string (split-string string ",")))
(defun org-ref-get-bibtex-keys (&optional sort)
"Return a list of unique keys in the buffer.
Use SORT to specify alphabetical order by key."
(let ((keys '()))
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(let ((plist (nth 1 link)))
(when (-contains? org-ref-cite-types (plist-get plist ':type))
(dolist
(key
(org-ref-split-and-strip-string (plist-get plist ':path)))
(when (not (-contains? keys key))
(setq keys (append keys (list key))))))))
;; set with-affiliated to get keys in captions
nil nil nil t)
(when sort
;; Sort keys alphabetically
(setq keys (cl-sort keys 'string-lessp :key 'downcase)))
keys))
;;;###autoload
(defun org-ref-bibliography (&optional sort)
"Create a new buffer with a bibliography.
If SORT is non-nil it is alphabetically sorted by key
This is mostly for convenience to see what has been cited.
Entries are formatted according to the bibtex entry type in
`org-ref-bibliography-entry-format', and the actual entries are
generated by `org-ref-reftex-format-citation'."
(interactive)
(let ((bib (mapconcat
'identity
(cl-loop for i from 1
for citation in
(mapcar
(lambda (key)
(let* ((results (org-ref-get-bibtex-key-and-file key))
(key (car results))
(bibfile (cdr results)))
(format "cite:%s %s" key
(if bibfile
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-format-entry key)))
"!!! No entry found !!!"))))
(org-ref-get-bibtex-keys sort))
collect (format "%3s. %s" i citation))
"\n\n")))
(switch-to-buffer-other-window (format "%s-bibliography" (buffer-file-name)))
(erase-buffer)
(insert bib)
(org-mode)))
(defun org-ref-get-bibtex-entry-html (key)
"Return an html string for the bibliography entry corresponding to KEY."
(let ((output))
(setq output (concat (format "<a name=\"%s\"></a>" key)
(org-ref-get-bibtex-entry-citation key)))
(setq output (org-ref-clean-unused-entry-html output))
(format "<li><a id=\"%s\">[%s]</a> %s</li>"
key key output)))
(defun org-ref-clean-unused-entry-html (entry-html)
"Return from the html string ENTRY-HTML a cleaner version"
;; unescape the &
(setq entry-html (replace-regexp-in-string "\\\\&" "&" entry-html))
;; hack to replace {} around text
(setq entry-html (replace-regexp-in-string "{" "" entry-html))
(setq entry-html (replace-regexp-in-string "}" "" entry-html))
;; get rid of empty parens
(setq entry-html (replace-regexp-in-string "()" "" entry-html))
;; Remove empty volume, number field if empty
(setq entry-html (replace-regexp-in-string "<b></b>," "" entry-html))
;; get rid of empty link and doi
(setq entry-html (replace-regexp-in-string " <a href=\"\">\\(link\\)?</a>\\.?" "" entry-html))
;; change double dash to single dash
(setq entry-html (replace-regexp-in-string "--" "-" entry-html))
(setq entry-html (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" entry-html))
entry-html)
(defun org-ref-get-html-bibliography (&optional sort)
"Create an html bibliography when there are keys.
If one of SORT and `org-ref-bib-html-sorted' is non-nil,
the bibliography is alphabetically sorted."
(let ((keys (org-ref-get-bibtex-keys (or sort org-ref-bib-html-sorted))))
(when keys
(concat org-ref-bib-html "<ul class='org-ref-bib'>"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
"\n</ul>"))))
(defun org-ref-get-bibtex-entry-org (key)
"Return an org string for the bibliography entry corresponding to KEY."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
file entry)
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s" key
(file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(format "** %s - %s
:PROPERTIES:
%s
:END:
" (org-ref-reftex-get-bib-field "author" entry)
(org-ref-reftex-get-bib-field "title" entry)
(concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
(mapconcat
(lambda (element) (format " :%s: %s"
(upcase (car element))
(cdr element)))
entry
"\n"))))))
(defun org-ref-get-org-bibliography (&optional sort)
"Create an org bibliography when there are keys.
If SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat "* Bibliography\n"
(mapconcat (lambda (x)
(org-ref-get-bibtex-entry-org x)) keys "\n")
"\n"))))
(defun org-ref-get-bibtex-entry-ascii (key)
"Return an ascii string for the bibliography entry corresponding to KEY."
(format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
(defun org-ref-get-bibtex-entry-md (key)
"Return a md string for the bibliography entry corresponding to KEY."
;; We create an anchor to the key that we can jump to, and provide a jump back
;; link with the md5 of the key.
(format "<a id=\"%s\"></a>[%s] %s%s [↩](#%s)"
key key
(org-ref-clean-unused-entry-html (org-ref-get-bibtex-entry-citation key))
""
;; Note: This is to temporarily resolve issue #558. This worked fine
;; for me earlier, so I don't know why it doesn't work in this issue.
;; (if (plist-get info :md-publish-bibtex)
;; (format
;; " <a href=\"data:text/plain;charset=US-ASCII;base64,%s\" title=\"%s\">[bib]</a>"
;; (base64-encode-string (org-ref-get-bibtex-entry key))
;; (concat "Right-click to open\n" (xml-escape-string
;; (org-ref-get-bibtex-entry key))))
;; "")
(md5 key)))
(defun org-ref-get-ascii-bibliography (&optional sort)
"Create an ascii bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"\n\nBibliography\n=============\n\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
"\n"))))
(defun org-ref-get-md-bibliography (&optional sort)
"Create an md bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"# Bibliography\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-md x)) keys "\n\n")
"\n"))))
(defun org-ref-get-odt-bibliography (&optional sort)
"Create an ascii bibliography ofr odt export when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by
key. This is a variant of `org-ref-get-ascii-bibliography' where
some things are escaped since odt is an xml format."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(mapconcat (lambda (x)
(xml-escape-string (org-ref-get-bibtex-entry-ascii x)))
keys "\n"))))
(defun org-ref-pdf-p (filename)
"Check if FILENAME is PDF file.
From the PDF specification 1.7:
The first line of a PDF file shall be a header consisting of
the 5 characters %PDF- followed by a version number of the
form 1.N, where N is a digit between 0 and 7."
(let* ((header (with-temp-buffer
(set-buffer-multibyte nil)
(insert-file-contents-literally filename nil 0 5)
(buffer-string)))
(valid (string-equal (encode-coding-string header 'utf-8) "%PDF-")))
(if valid
valid
(message "Invalid pdf. Header = %s" header)
nil)))
;;;###autoload
(defmacro org-ref-link-set-parameters (type &rest parameters)
"Set link TYPE properties to PARAMETERS."
(declare (indent 1))
(if (fboundp 'org-link-set-parameters)
`(org-link-set-parameters ,type ,@parameters)
`(org-add-link-type ,type ,(plist-get parameters :follow) ,(plist-get parameters :export))))
;; This section creates some code that should speed up org-ref for large files.
;; I use org-element-parse-buffer a lot for getting information about labels
;; etc. However, it gets called a lot, and this is slow in large documents. Here
;; we try to use a cache that helps speed this up at least on loading. Some
;; notes for the future: on loading, it seems like fontification triggers buffer
;; changes, so here we only consider char changes. I am not sure this is the
;; best strategy overall. It is faster to use regexps for finding this
;; information, but those are substantially more difficult to debug in my
;; experience. There is an unfortunate number of ways to reference things in
;; org-mode, and so far this has been most reliable. An alternative might be to
;; leveralge what happens in font-lock somehow to update local variables
;; containing org-ref labels, refs, cites, etc. That would miss some #+names
;; though, and maybe some other things like custom-ids.
(defvar-local org-ref-char-change-tick nil
"Local variable to track character changes.")
(defvar-local org-ref-parse-buffer-cache nil
"Local variable to store parse buffer data.")
(defun org-ref-parse-buffer (&optional force)
"This is a thin wrapper around `org-element-parse-buffer'.
The idea is to cache the data, and return it unless we can tell
the buffer has been modified since the last time we ran it.
if FORCE is non-nil reparse the buffer no matter what."
(if force
(progn
(message "Forcing update.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(cond
((null org-ref-parse-buffer-cache)
;; (message "First parse.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
((not (eq org-ref-char-change-tick (buffer-chars-modified-tick)))
;; (message "Updating from a char change in the buffer.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(t
;; (message "Using cache.")
org-ref-parse-buffer-cache))))
;; * org-ref command
(defun org-ref ()
"Check the current org-buffer for potential issues."
(interactive)
(let* ((buf (get-buffer-create "*org-ref*"))
(cb (current-buffer))
(fname (buffer-file-name))
;; Check if elc is ok before anything else because if it is not, it
;; causes problems in org-ref.
(elc-ok (let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(orel-mod)
(org-ref-elc (concat
(file-name-sans-extension
(locate-library "org-ref"))
".elc"))
(orelc-mod)
(elc-version))
(when (file-exists-p org-ref-el)
(setq orel-mod (file-attribute-modification-time (file-attributes org-ref-el))))
(when (file-exists-p org-ref-elc)
(setq orelc-mod (file-attribute-modification-time (file-attributes org-ref-elc))))
(with-current-buffer buf
(read-only-mode -1)
(erase-buffer)
(org-mode)
(insert (format "#+title: org-ref report on [[%s][%s]]\n\n" (buffer-file-name cb) (buffer-name cb)))
(insert (format "org-ref called from %s" (buffer-file-name cb)))
(unless (time-less-p orel-mod orelc-mod)
(insert (format "org-ref.elc (%s) is older than org-ref.el (%s). That is probably not right. Please delete %s.\n"
(format-time-string "%Y-%m-%d %H:%M:%S" orelc-mod)
(format-time-string "%Y-%m-%d %H:%M:%S" orel-mod)
org-ref-elc))
(insert (format "- load-prefer-newer = %s\n" load-prefer-newer))
(insert (format " consider
- deleting %s
- [[elisp:(delete-file \"%s\")]]
- add (setq load-prefer-newer t) to your init files
- using https://github.com/emacscollective/auto-compile.\n" org-ref-elc org-ref-elc))
;; Check for byte-compiling compatibility with current emacs
(when (and org-ref-elc
(file-exists-p org-ref-elc))
(setq elc-version (with-temp-buffer
(insert-file-contents org-ref-elc)
(goto-char (point-min))
(when (re-search-forward ";;; in Emacs version \\([0-9]\\{2\\}\\.[0-9]+\\)"
nil t)
(match-string 1))))
(unless (string= elc-version
(format "%s.%s" emacs-major-version emacs-minor-version))
(insert (format "%s compiled with Emacs %s but you are running %s. That could be a problem.\n"
elc-version emacs-major-version emacs-minor-version))))))))
(bad-citations (org-ref-bad-cite-candidates))
(bad-refs (org-ref-bad-ref-candidates))
(bad-labels (org-ref-bad-label-candidates))
(bad-files (org-ref-bad-file-link-candidates))
(bib-candidates '())
(unreferenced-labels '())
natbib-required
natbib-used
cleveref-required
cleveref-used
biblatex-required
biblatex-used
mbuffer
mchar
(org-latex-prefer-user-labels (and (boundp 'org-latex-prefer-user-labels)
org-latex-prefer-user-labels)))
;; See if natbib, biblatex or cleveref are required
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(when (member (org-element-property :type link) org-ref-natbib-types)
(setq natbib-required t))
(when (member (org-element-property :type link) org-ref-biblatex-types)
(setq biblatex-required t))
(when (member (org-element-property :type link) '("cref" "Cref"))
(setq cleveref-required t)))
nil t)
;; See if natbib is probably used. This will miss a case where natbib is included somehow.
(setq natbib-used
(or
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{natbib} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{natbib}" nil t))))
(setq biblatex-used
(or
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{biblatex} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{biblatex}" nil t))))
(setq cleveref-used
(or
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{cleveref} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{cleveref}" nil t))))
;; setup bib-candidates. This checks a variety of things in the
;; bibliography, bibtex files. check for which bibliographies are used
(cl-loop for bibfile in (org-ref-find-bibliography)
do
(let ((bibdialect))
(with-current-buffer (find-file-noselect bibfile)
(setq bibdialect bibtex-dialect))
(cl-pushnew
(format "[[%s]] (dialect = %s)\n" bibfile bibdialect)
bib-candidates)))
;; Check bibliography style exists
(save-excursion
(goto-char 0)
(unless (re-search-forward "bibliographystyle:\\|\\\\bibliographystyle{" nil t)
(cl-pushnew
"No bibliography style found. This may be ok, if your latex class style sets that up, but if not this is an error. Try adding something like:
bibliographystyle:unsrt
at the end of your file.\n"
bib-candidates)))
;; Check if latex knows of the bibliographystyle. We only check links here.
;; I also assume this style exists as a bst file that kpsewhich can find.
(save-excursion
(goto-char 0)
(when (re-search-forward "bibliographystyle:" nil t)
;; on a link. get style
(let ((path (org-element-property :path (org-element-context))))
(unless (= 0 (shell-command (format "kpsewhich %s.bst" path)))
(cl-pushnew
(format "bibliographystyle \"%s\" may be unknown" path)
bib-candidates)))))
;; check for multiple bibliography links
(let* ((bib-links (-filter
(lambda (el)
(string= (org-element-property :type el) "bibliography"))
(org-element-map (org-element-parse-buffer) 'link 'identity)))
(n-bib-links (length bib-links)))
(when (> n-bib-links 1)
(mapc (lambda (link)
(setq
bib-candidates
(append
bib-candidates
(list (format "Multiple bibliography link: %s"
(org-element-property :raw-link link))))))
bib-links)))
;; Check for bibliography files existence.
(mapc (lambda (bibfile)
(unless (file-exists-p bibfile)
(cl-pushnew
(format "%s does not exist." bibfile)
bib-candidates)))
(org-ref-find-bibliography))
;; check for spaces in bibliography
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc (lambda (bibfile)
(when (string-match " " bibfile)
(cl-pushnew
(format "One or more spaces found in path to %s. No spaces are allowed in bibtex file paths. We recommend replacing them with -. Underscores usually cause other problems." bibfile)
bib-candidates)))
bibfiles))
;; validate bibtex files
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc
(lambda (bibfile)
(unless (with-current-buffer
(find-file-noselect bibfile)
(bibtex-validate))
(cl-pushnew
(format "Invalid bibtex file found. [[file:%s]]\n" bibfile)
bib-candidates)))
bibfiles)
;; check types
(mapc
(lambda (bibfile)
(with-current-buffer
(find-file-noselect bibfile)
(goto-char (point-min))
(while (re-search-forward "^@\\(.*?\\)[({]" nil t)
(when (and (not (string= "string" (downcase (match-string-no-properties 1))))
(not (member (s-trim (downcase (match-string-no-properties 1)))
(cdr (assoc bibtex-dialect
(list
(cons 'BibTeX (mapcar (lambda (e) (downcase (car e)))
bibtex-BibTeX-entry-alist))
(cons 'biblatex (mapcar (lambda (e) (downcase (car e)))
bibtex-biblatex-entry-alist))))))))
(cl-pushnew
(format "Invalid bibtex entry type (%s) found in [[file:%s::%s]]\n" (match-string-no-properties 1)
bibfile (line-number-at-pos))
bib-candidates)))))
bibfiles))
;; unreferenced labels
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((matches '()))
;; these are the org-ref label:stuff kinds
(while (re-search-forward
"[^#+]label:\\([a-zA-Z0-9:-]*\\)" nil t)
(cl-pushnew (cons
(match-string-no-properties 1)
(point))
matches))
;; now add all the other kinds of labels.
;; #+label:
(save-excursion
(goto-char (point-min))
(while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" nil t)
;; do not do this for tables. We get those in `org-ref-get-tblnames'.
;; who would have thought you have save match data here? Trust me. When
;; I wrote this, you did.
(unless (save-match-data (equal (car (org-element-at-point)) 'table))
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches))))
;; \label{}
(save-excursion
(goto-char (point-min))
(while (re-search-forward "\\\\label{\\([a-zA-Z0-9:-]*\\)}"
nil t)
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches)))
;; #+tblname: and actually #+label
(cl-loop for cell in (org-element-map (org-element-parse-buffer 'element) 'table
(lambda (table)
(cons (org-element-property :name table)
(org-element-property :begin table))))
do
(cl-pushnew cell matches))
;; CUSTOM_IDs
(org-map-entries
(lambda ()
(let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
(when (not (null custom_id))
(cl-pushnew (cons custom_id (point)) matches)))))
(goto-char (point-min))
(while (re-search-forward "^#\\+name:\\s-+\\(.*\\)" nil t)
(cl-pushnew (cons (match-string 1) (point)) matches))
;; unreference labels
(let ((refs (org-element-map (org-element-parse-buffer) 'link
(lambda (el)
(when (or (string= "ref" (org-element-property :type el))
(string= "eqref" (org-element-property :type el))
(string= "pageref" (org-element-property :type el))
(string= "nameref" (org-element-property :type el))
(string= "autoref" (org-element-property :type el))
(string= "cref" (org-element-property :type el))
(string= "Cref" (org-element-property :type el)))
(org-element-property :path el))))))
(cl-loop for (label . p) in matches
do
(when (and label (not (-contains? refs label)))
(cl-pushnew
(cons label (set-marker (make-marker) p))
unreferenced-labels)))))))
(with-current-buffer buf
(when bad-citations
(insert "\n* Bad citations\n")
(cl-loop for (key . marker) in bad-citations
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-refs
(insert "\n* Bad ref links\n")
(cl-loop for (key . marker) in bad-refs
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-labels
(insert "\n* Multiply defined label links\n")
(cl-loop for (key . marker) in bad-labels
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when unreferenced-labels
(insert "\n* Unreferenced label links\n")
(cl-loop for (key . marker) in unreferenced-labels
when (not (string= key ""))
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bib-candidates
(insert "\n* Bibliography\n")
(cl-loop for candidate in bib-candidates
do
(insert (format "- %s" candidate))))
(insert "\n* Miscellaneous\n")
(cl-loop for s in `(,(format "org-latex-prefer-user-labels = %s"
org-latex-prefer-user-labels)
,(format "bibtex-dialect = %s" bibtex-dialect)
,(format "biblatex is%srequired." (if biblatex-required " " " not "))
,(format "biblatex is%sused." (if biblatex-used " " " not "))
,(format "emacs-version = %s" (emacs-version))
,(format "org-version = %s" (org-version))
,(org-ref-version)
,(format "org-ref.el installed at %s" (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
,(format "completion backend = %s" org-ref-completion-library)
,(format "org-ref-insert-cite-function = %s" org-ref-insert-cite-function)
,(format "org-ref-insert-label-function = %s" org-ref-insert-label-function)
,(format "org-ref-insert-ref-function = %s" org-ref-insert-ref-function)
,(format "org-ref-cite-onclick-function = %s" org-ref-cite-onclick-function)
,(format "org-ref-default-bibliography = %S" org-ref-default-bibliography)
,(format "org-ref-default-bibliography is a list = %S" (listp org-ref-default-bibliography))
,(format "org-latex-pdf-process is defined as %s" org-latex-pdf-process)
,(format "natbib is%srequired." (if natbib-required " " " not "))
,(format "natbib is%sin %s or %s."
(if natbib-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "cleveref is%srequired." (if cleveref-required " " " not "))
,(format "cleveref is%sin %s or %s."
(if cleveref-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "bibtex-completion installed = %s" (featurep 'bibtex-completion))
,(format "bibtex-completion loaded = %s" (fboundp 'bibtex-completion-candidates)))
do
(insert "- " s "\n"))
(insert (format "- org-latex-default-packages-alist\n"))
(cl-loop for el in org-latex-default-packages-alist
do
(insert (format " %S\n" el)))
(if (null org-latex-packages-alist)
(insert "- org-latex-packages-alist is nil\n")
(insert "- org-latex-packages-alist\n")
(cl-loop for el in org-latex-packages-alist
do
(insert (format " %S\n" el))))
(insert (format "- ox-bibtex loaded = %s\n" (featurep 'ox-bibtex)))
(insert (format "- ox-bibtex loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ox-bibtex-i (seq-position load-history (assoc (locate-library "ox-bibtex") load-history))))
(and org-ref-i ox-bibtex-i
(> org-ref-i ox-bibtex-i)))))
(insert (format "- ebib loaded = %s\n" (featurep 'ebib)))
(insert (format "- ebib loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ebib-i (seq-position load-history (assoc (locate-library "ebib") load-history))))
(and org-ref-i ebib-i
(> org-ref-i ebib-i)))))
(insert "- cite link definition:\n" (with-temp-buffer
(insert (format "%S" (assoc "cite" org-link-parameters)))
(pp-buffer)
(buffer-string)))
(insert "\n* LaTeX setup\n\n")
(cl-loop for executable in '("latex" "pdflatex" "bibtex" "biblatex"
"makeindex" "makeglossaries")
do
(insert (format "%s is installed at %s\n" executable (executable-find executable))))
(insert "\n* Warnings\n")
(if (get-buffer "*Warnings*")
(cl-loop for line in (s-split "\n" (with-current-buffer "*Warnings*"
(buffer-string)))
if (s-starts-with? "Warning (org-ref):" line)
do
(insert " - " line "\n"))
(insert "- No (org-ref) Warnings found."))
(insert (format "\n* Utilities
- [[elisp:(progn (find-file %S) (ispell))][Spell check document]]
- [[elisp:(progn (find-file %S) (org-ref))][recheck document with org-ref]]
" fname fname))
(goto-char (point-min))
;; (setq header-line-format "Press q to quit.")
;; (local-set-key "q"
;; #'(lambda ()
;; (interactive)
;; (delete-window)))
(read-only-mode))
(display-buffer-in-side-window buf '((side . right)))))
(provide 'org-ref-utils)
;;; org-ref-utils.el ends here
| 25719 | ;;; org-ref-utils.el --- Utility functions for org-ref -*- lexical-binding: t; -*-
;; Copyright (C) 2016 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
(eval-when-compile
(require 'cl-lib))
(require 'org)
(require 'org-ref-pdf) ; for pdftotext-executable
(defcustom org-ref-bib-html "<h1 class='org-ref-bib-h1'>Bibliography</h1>\n"
"HTML header to use for bibliography in HTML export."
:type 'string
:group 'org-ref)
(defcustom org-ref-bib-html-sorted nil
"Determine whether the HTML bibliography should be sorted."
:type 'boolean
:group 'org-ref)
(defcustom org-ref-search-whitespace-regexp "\\s-+"
"A whitespace regexp for use in `org-ref-strip-string."
:group 'org-ref)
(defvar org-ref-cite-types)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-notes-function)
(defvar org-ref-bibliography-entry-format)
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-key-in-file-p "org-ref-core.el")
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-under-cursor "org-ref-core.el")
;;; Code:
;;;###autoload
(defun org-ref-version ()
"Provide a version string for org-ref.
Copies the string to the clipboard."
(interactive)
;; version in the el file.
(let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(org-ref-dir (file-name-directory org-ref-el))
org-version
git-commit
version-string)
(setq org-version (with-temp-buffer
(insert-file-contents org-ref-el)
(goto-char (point-min))
(re-search-forward ";; Version:")
(s-trim (buffer-substring (point)
(line-end-position)))))
(setq git-commit
;; If in git, get current commit
(let ((default-directory org-ref-dir))
(when (and
;; this is tricky, as a submodule, .git is a file
(or (file-directory-p ".git") (file-exists-p ".git"))
(= 0 (shell-command "git rev-parse --git-dir")))
(format "%s in %s"
(s-trim (shell-command-to-string "git rev-parse HEAD"))
(s-trim (shell-command-to-string "git rev-parse --show-toplevel"))))))
(setq version-string (format "org-ref: Version %s%s"
org-version
(if git-commit
(format " (git-commit %s)" git-commit)
"")))
(kill-new version-string)
(message version-string)))
(defun org-ref-report-issue ()
"Report an issue in org-ref.
Opens https://github.com/jkitchin/org-ref/issues/new."
(save-window-excursion
(org-ref-debug)
(kill-new (buffer-string)))
(message "org-ref-debug has been run. You can paste the results in the issue website if you like.")
(browse-url "https://github.com/jkitchin/org-ref/issues/new"))
;;* Debug(require 'org-ref-pdf)
(defmacro ords (&rest body)
"Evaluate BODY and return a string."
`(format "%s" (progn ,@body)))
;;;###autoload
(defun org-ref-debug ()
"Print some debug information to a buffer."
(interactive)
(switch-to-buffer "*org-ref-debug*")
(erase-buffer)
(org-mode)
(insert
(s-format "#+TITLE: org-ref debug
${org-ref-version}
* Variables
1. org-ref-completion-library: ${org-ref-completion-library}
2. org-ref-bibliography-notes: ${org-ref-bibliography-notes} (exists ${orbn-p})
3. org-ref-default-bibliography: ${org-ref-default-bibliography} (exists ${ordb-p}) (listp ${ordb-listp})
4. org-ref-pdf-directory: ${org-ref-pdf-directory} (exists ${orpd-p})
* System
system-type: ${system}
system-configuration: ${system-configuration}
window system: ${window-system}
Emacs: ${emacs-version}
org-version: ${org-version}
* about org-ref
org-ref installed in ${org-ref-location}.
** Dependencies
helm-bibtex ${helm-bibtex-path}
* org-ref-pdf (loaded: ${org-ref-pdf-p})
system pdftotext: ${pdftotext}
You set pdftotext-executable to ${pdftotext-executable} (exists: ${pdftotext-executable-p})
* org-ref-url-utils (loaded: ${org-ref-url-p})
* export variables
org-latex-pdf-process:
${org-latex-pdf-process}
"
'aget
`(("org-ref-completion-library" . ,(format "%s" org-ref-completion-library))
("org-ref-bibliography-notes" . ,(format "%s" org-ref-bibliography-notes))
("org-ref-bibliography-notes exists" . ,(format "%s" (when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes))))
("org-ref-version" . ,(org-ref-version))
("org-latex-pdf-process" . ,(format "%S" org-latex-pdf-process))
("org-ref-default-bibliography" . ,(format "%s" org-ref-default-bibliography))
("ordb-p" . ,(format "%s" (mapcar 'file-exists-p org-ref-default-bibliography)))
("ordb-listp" . ,(ords (listp org-ref-default-bibliography)))
("orbn-p" . ,(when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes)))
("org-ref-pdf-directory" . ,(format "%s" org-ref-pdf-directory))
("orpd-p" . ,(format "%s" (file-exists-p org-ref-pdf-directory)))
("org-ref-location" . ,(format "%s" (locate-library "org-ref")))
("system" . ,(format "System: %s" system-type))
("system-configuration" . ,(ords system-configuration))
("window-system" . ,(format "Window system: %s" window-system))
("emacs-version" . ,(ords (emacs-version)))
("org-version" . ,(org-version))
("helm-bibtex-path" . ,(ords (locate-library "helm-bibtex")))
("org-ref-pdf-p" . ,(ords (featurep 'org-ref-pdf)))
("pdftotext" . ,(ords (if (featurep 'org-ref-pdf)
(executable-find "pdftotext")
"org-ref-pdf not loaded")))
("pdftotext-executable" . ,(ords (if (featurep 'org-ref-pdf)
pdftotext-executable
"org-ref-pdf not loaded")))
("pdftotext-executable-p" . ,(ords (if (featurep 'org-ref-pdf)
(or
(executable-find pdftotext-executable)
(file-exists-p pdftotext-executable))
"org-ref-pdf not loaded")))
("org-ref-url-p" . ,(ords (featurep 'org-ref-url)))))))
(defun org-ref-reftex-get-bib-field (field entry &optional format)
"Get FIELD from a bibtex ENTRY in optional FORMAT.
Similar to `reftex-get-bib-field', but removes enclosing braces
and quotes in FIELD in the bibtex ENTRY."
(let ((result))
(setq result (reftex-get-bib-field field entry format))
(when (and (not (string= result "")) (string= "{" (substring result 0 1)))
(setq result (substring result 1 -1)))
(when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
(setq result (substring result 1 -1)))
result))
(defun org-ref-reftex-format-citation (entry format)
"Format the bibtex ENTRY according to the FORMAT argument.
ENTRY is from `bibtex-parse-entry'
The FORMAT is a string with these percent escapes.
In the format, the following percent escapes will be expanded.
%l The BibTeX label of the citation.
%a List of author names, see also `reftex-cite-punctuation'.
%2a Like %a, but abbreviate more than 2 authors like Jones et al.
%A First author name only.
%e Works like %a, but on list of editor names. (%2e and %E work as well)
It is also possible to access all other BibTeX database fields:
%b booktitle %c chapter %d edition %h howpublished
%i institution %j journal %k key %m month
%n number %o organization %p pages %P first page
%r address %s school %u publisher %t title
%v volume %y year
%B booktitle, abbreviated %T title, abbreviated
%U url
%D doi
%S series %N note
%f pdf filename (key.pdf)
%F absolute pdf filename (returned from `org-ref-get-pdf-filename-function')
Usually, only %l is needed. The other stuff is mainly for the echo area
display, and for (setq reftex-comment-citations t).
%< as a special operator kills punctuation and space around it after the
string has been formatted.
A pair of square brackets indicates an optional argument, and RefTeX
will prompt for the values of these arguments.
Beware that all this only works with BibTeX database files. When
citations are made from the \bibitems in an explicit thebibliography
environment, only %l is available."
;; Format a citation from the info in the BibTeX ENTRY
(unless (stringp format) (setq format "\\cite{%l}"))
(if (and reftex-comment-citations
(string-match "%l" reftex-cite-comment-format))
(error "Reftex-cite-comment-format contains invalid %%l"))
(while (string-match
"\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
format)
(let ((n (string-to-number (match-string 4 format)))
(l (string-to-char (match-string 5 format)))
rpl b e)
(save-match-data
(setq rpl
(cond
((= l ?l) (concat
(org-ref-reftex-get-bib-field "&key" entry)
(if reftex-comment-citations
reftex-cite-comment-format
"")))
((= l ?a) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(reftex-format-names
(reftex-get-bib-names "author" entry)
(or n 2))))
((= l ?A) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(car (reftex-get-bib-names "author" entry))))
((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
((= l ?B) (reftex-abbreviate-title
(org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
((= l ?e) (reftex-format-names
(reftex-get-bib-names "editor" entry)
(or n 2)))
((= l ?E) (car (reftex-get-bib-names "editor" entry)))
((= l ?f) (concat (org-ref-reftex-get-bib-field "=key=" entry) ".pdf"))
((= l ?F) (funcall org-ref-get-pdf-filename-function
(org-ref-reftex-get-bib-field "=key=" entry)))
((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
(if (string= "" jt)
(reftex-get-bib-field "journaltitle" entry)
jt)))
((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
((= l ?N) (org-ref-reftex-get-bib-field "note" entry))
((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
((= l ?P) (car (split-string
(org-ref-reftex-get-bib-field "pages" entry)
"[- .]+")))
((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
;; strip enclosing brackets from title if they are there
((= l ?t) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry)))
((= l ?T) (reftex-abbreviate-title
(replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry))))
((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
(if (string= rpl "")
(setq b (match-beginning 2) e (match-end 2))
(setq b (match-beginning 3) e (match-end 3)))
(setq format (concat (substring format 0 b) rpl (substring format e)))))
(while (string-match "%%" format)
(setq format (replace-match "%" t t format)))
(while (string-match "[ ,.;:]*%<" format)
(setq format (replace-match "" t t format)))
format)
(defun org-ref-get-bibtex-entry-citation (key)
"Return a string for the bibliography entry corresponding to KEY.
Format according to the type in `org-ref-bibliography-entry-format'."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry) (bibtex-entry) (entry-type) (format))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq bibtex-entry (bibtex-parse-entry))
;; downcase field names so they work in the format-citation code
(dolist (cons-cell bibtex-entry)
(setf (car cons-cell) (downcase (car cons-cell))))
(setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
(setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
(if format
(setq entry (org-ref-reftex-format-citation bibtex-entry format))
;; if no format, we use the bibtex entry itself as a fallback
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))))
entry))
(defun org-ref-get-bibtex-entry (key)
"Return the bibtex entry as a string."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))
entry)))
;;*** key at point functions
(defun org-ref-get-pdf-filename (key)
"Return the pdf filename associated with a bibtex KEY.
This searches for the pattern KEY*.pdf. If one result is found it
is returned, but if multiple results are found, e.g. there are
related files to the KEY you are prompted for which one you want."
(if org-ref-pdf-directory
(let* ((pdf-dirs (if (listp org-ref-pdf-directory)
org-ref-pdf-directory
(list org-ref-pdf-directory)))
(pdfs (-flatten (--map (file-expand-wildcards
(f-join it (format "%s*.pdf" key)))
(-flatten pdf-dirs)))))
(cond
((= 0 (length pdfs))
(expand-file-name (format "%s.pdf" key) org-ref-pdf-directory))
((= 1 (length pdfs))
(car pdfs))
((> (length pdfs) 1)
(completing-read "Choose: " pdfs))))
;; No org-ref-pdf-directory defined so return just a file name.
(format "%s.pdf" key)))
(defun org-ref-get-mendeley-filename (key)
"Return the pdf filename indicated by mendeley file field.
Falls back to `org-ref-get-pdf-filename' if file field does not exist.
Contributed by https://github.com/autosquid.
Argument KEY is the bibtex key."
(let* ((results (org-ref-get-bibtex-key-and-file key))
(bibfile (cdr results))
entry)
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(let ((e (org-ref-reftex-get-bib-field "file" entry)))
(if (> (length e) 4)
(let ((clean-field (replace-regexp-in-string "{\\|}\\|\\\\" "" e)))
(let ((first-file (car (split-string clean-field ";" t))))
(format "/%s" (substring first-file 1
(- (length first-file) 4)))))
(format (concat
(file-name-as-directory org-ref-pdf-directory)
"%s.pdf")
key))))))
(defun org-ref-get-pdf-filename-helm-bibtex (key)
"Use helm-bibtex to retrieve a PDF filename for KEY.
helm-bibtex looks in both the configured directory
`bibtex-completion-library-path' and in the fields of the bibtex
item for a filename. It understands file fields exported by
Jabref, Mendeley and Zotero. See `bibtex-completion-find-pdf'."
(let ((bibtex-completion-bibliography (org-ref-find-bibliography)))
(or (car (bibtex-completion-find-pdf key)) "")))
;;;###autoload
(defun org-ref-open-pdf-at-point ()
"Open the pdf for bibtex key under point if it exists."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key)))
(if (file-exists-p pdf-file)
(org-open-file pdf-file)
(message "no pdf found for %s" key))))
;;;###autoload
(defun org-ref-open-url-at-point ()
"Open the url for bibtex key under point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(catch 'done
(let ((url (s-trim (bibtex-autokey-get-field "url"))))
(unless (s-blank? url)
(browse-url url)
(throw 'done nil)))
(let ((doi (s-trim (bibtex-autokey-get-field "doi"))))
(unless (s-blank? doi)
(if (string-match "^http" doi)
(browse-url doi)
(browse-url (format "http://dx.doi.org/%s" doi)))
(throw 'done nil))))))))
;;;###autoload
(defun org-ref-open-notes-at-point (&optional thekey)
"Open the notes for bibtex key under point in a cite link in a buffer.
Can also be called with THEKEY in a program."
(interactive)
(when (null thekey)
(setq thekey (org-ref-get-bibtex-key-under-cursor)))
(funcall org-ref-notes-function thekey))
;;;###autoload
(defun org-ref-citation-at-point ()
"Give message of current citation at point."
(interactive)
(org-ref-format-entry (org-ref-get-bibtex-key-under-cursor)))
;;;###autoload
(defun org-ref-open-citation-at-point ()
"Open bibtex file to key at point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(find-file bibfile)
(bibtex-search-entry key)))
;;*** cite menu
(defvar org-ref-cite-menu-funcs '()
"Functions to run on cite click menu.
Each entry is a list of (key menu-name function). The function
must take no arguments and work on the key at point. Do not
modify this variable, it is set to empty in the menu click
function, and functions are conditionally added to it.")
(defvar org-ref-user-cite-menu-funcs
'(("C" "rossref" org-ref-crossref-at-point)
("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
("s" "Copy summary" org-ref-copy-entry-as-summary))
"User-defined functions to run on bibtex key at point.")
;;;###autoload
(defun org-ref-copy-entry-as-summary ()
"Copy the bibtex entry for the citation at point as a summary."
(interactive)
(kill-new (org-ref-bib-citation)))
;;;###autoload
(defun org-ref-copy-cite-as-summary ()
"Copy a summary for the citation at point to the clipboard."
(interactive)
(kill-new (org-ref-link-message)))
;;;###autoload
(defun org-ref-copy-entry-at-point-to-file ()
"Copy the bibtex entry for the citation at point to NEW-FILE.
Prompt for NEW-FILE includes bib files in
`org-ref-default-bibliography', and bib files in current working
directory. You can also specify a new file."
(interactive)
(let ((new-file (completing-read
"Copy to bibfile: "
(append org-ref-default-bibliography
(f-entries "." (lambda (f) (f-ext? f "bib"))))))
(key (org-ref-get-bibtex-key-under-cursor)))
(save-window-excursion
(org-ref-open-citation-at-point)
(bibtex-copy-entry-as-kill))
(let ((bibtex-files (list (file-truename new-file))))
(if (assoc key (bibtex-global-key-alist))
(message "That key already exists in %s" new-file)
;; add to file
(save-window-excursion
(find-file new-file)
(goto-char (point-max))
;; make sure we are at the beginning of a line.
(unless (looking-at "^") (insert "\n\n"))
(bibtex-yank)
(save-buffer))))))
(defun org-ref-get-doi-at-point ()
"Get doi for key at point."
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results))
doi)
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(setq doi (bibtex-autokey-get-field "doi"))
;; in case doi is a url, remove the url part.
(replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
;;**** functions that operate on key at point for click menu
;;;###autoload
(defun org-ref-ads-at-point ()
"Open the doi in ADS for bibtex key under point."
(interactive)
(doi-utils-ads (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-at-point ()
"Open the doi in wos for bibtex key under point."
(interactive)
(doi-utils-wos (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-citing-at-point ()
"Open the doi in wos citing articles for bibtex key under point."
(interactive)
(doi-utils-wos-citing (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-related-at-point ()
"Open the doi in wos related articles for bibtex key under point."
(interactive)
(doi-utils-wos-related (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-google-scholar-at-point ()
"Search google scholar for bibtex key under point using the title."
(interactive)
(browse-url
(url-encode-url
(format
"http://scholar.google.com/scholar?q=%s"
(let* ((key-file (org-ref-get-bibtex-key-and-file))
(key (car key-file))
(file (cdr key-file))
entry)
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(org-ref-reftex-get-bib-field "title" entry)))))))
;;;###autoload
(defun org-ref-pubmed-at-point ()
"Open the doi in pubmed for bibtex key under point."
(interactive)
(doi-utils-pubmed (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-crossref-at-point ()
"Open the doi in crossref for bibtex key under point."
(interactive)
(doi-utils-crossref (org-ref-get-doi-at-point)))
;;* General org-ref utilities
(defun org-ref-strip-string (string)
"Strip leading and trailing whitespace from the STRING."
(replace-regexp-in-string
(concat org-ref-search-whitespace-regexp "$" ) ""
(replace-regexp-in-string
(concat "^" org-ref-search-whitespace-regexp ) "" string)))
(defun org-ref-split-and-strip-string (string)
"Split key-string and strip keys in STRING.
Assumes the key-string is comma delimited."
(mapcar 'org-ref-strip-string (split-string string ",")))
(defun org-ref-get-bibtex-keys (&optional sort)
"Return a list of unique keys in the buffer.
Use SORT to specify alphabetical order by key."
(let ((keys '()))
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(let ((plist (nth 1 link)))
(when (-contains? org-ref-cite-types (plist-get plist ':type))
(dolist
(key
(org-ref-split-and-strip-string (plist-get plist ':path)))
(when (not (-contains? keys key))
(setq keys (append keys (list key))))))))
;; set with-affiliated to get keys in captions
nil nil nil t)
(when sort
;; Sort keys alphabetically
(setq keys (cl-sort keys 'string-lessp :key 'downcase)))
keys))
;;;###autoload
(defun org-ref-bibliography (&optional sort)
"Create a new buffer with a bibliography.
If SORT is non-nil it is alphabetically sorted by key
This is mostly for convenience to see what has been cited.
Entries are formatted according to the bibtex entry type in
`org-ref-bibliography-entry-format', and the actual entries are
generated by `org-ref-reftex-format-citation'."
(interactive)
(let ((bib (mapconcat
'identity
(cl-loop for i from 1
for citation in
(mapcar
(lambda (key)
(let* ((results (org-ref-get-bibtex-key-and-file key))
(key (car results))
(bibfile (cdr results)))
(format "cite:%s %s" key
(if bibfile
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-format-entry key)))
"!!! No entry found !!!"))))
(org-ref-get-bibtex-keys sort))
collect (format "%3s. %s" i citation))
"\n\n")))
(switch-to-buffer-other-window (format "%s-bibliography" (buffer-file-name)))
(erase-buffer)
(insert bib)
(org-mode)))
(defun org-ref-get-bibtex-entry-html (key)
"Return an html string for the bibliography entry corresponding to KEY."
(let ((output))
(setq output (concat (format "<a name=\"%s\"></a>" key)
(org-ref-get-bibtex-entry-citation key)))
(setq output (org-ref-clean-unused-entry-html output))
(format "<li><a id=\"%s\">[%s]</a> %s</li>"
key key output)))
(defun org-ref-clean-unused-entry-html (entry-html)
"Return from the html string ENTRY-HTML a cleaner version"
;; unescape the &
(setq entry-html (replace-regexp-in-string "\\\\&" "&" entry-html))
;; hack to replace {} around text
(setq entry-html (replace-regexp-in-string "{" "" entry-html))
(setq entry-html (replace-regexp-in-string "}" "" entry-html))
;; get rid of empty parens
(setq entry-html (replace-regexp-in-string "()" "" entry-html))
;; Remove empty volume, number field if empty
(setq entry-html (replace-regexp-in-string "<b></b>," "" entry-html))
;; get rid of empty link and doi
(setq entry-html (replace-regexp-in-string " <a href=\"\">\\(link\\)?</a>\\.?" "" entry-html))
;; change double dash to single dash
(setq entry-html (replace-regexp-in-string "--" "-" entry-html))
(setq entry-html (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" entry-html))
entry-html)
(defun org-ref-get-html-bibliography (&optional sort)
"Create an html bibliography when there are keys.
If one of SORT and `org-ref-bib-html-sorted' is non-nil,
the bibliography is alphabetically sorted."
(let ((keys (org-ref-get-bibtex-keys (or sort org-ref-bib-html-sorted))))
(when keys
(concat org-ref-bib-html "<ul class='org-ref-bib'>"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
"\n</ul>"))))
(defun org-ref-get-bibtex-entry-org (key)
"Return an org string for the bibliography entry corresponding to KEY."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
file entry)
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s" key
(file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(format "** %s - %s
:PROPERTIES:
%s
:END:
" (org-ref-reftex-get-bib-field "author" entry)
(org-ref-reftex-get-bib-field "title" entry)
(concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
(mapconcat
(lambda (element) (format " :%s: %s"
(upcase (car element))
(cdr element)))
entry
"\n"))))))
(defun org-ref-get-org-bibliography (&optional sort)
"Create an org bibliography when there are keys.
If SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat "* Bibliography\n"
(mapconcat (lambda (x)
(org-ref-get-bibtex-entry-org x)) keys "\n")
"\n"))))
(defun org-ref-get-bibtex-entry-ascii (key)
"Return an ascii string for the bibliography entry corresponding to KEY."
(format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
(defun org-ref-get-bibtex-entry-md (key)
"Return a md string for the bibliography entry corresponding to KEY."
;; We create an anchor to the key that we can jump to, and provide a jump back
;; link with the md5 of the key.
(format "<a id=\"%s\"></a>[%s] %s%s [↩](#%s)"
key key
(org-ref-clean-unused-entry-html (org-ref-get-bibtex-entry-citation key))
""
;; Note: This is to temporarily resolve issue #558. This worked fine
;; for me earlier, so I don't know why it doesn't work in this issue.
;; (if (plist-get info :md-publish-bibtex)
;; (format
;; " <a href=\"data:text/plain;charset=US-ASCII;base64,%s\" title=\"%s\">[bib]</a>"
;; (base64-encode-string (org-ref-get-bibtex-entry key))
;; (concat "Right-click to open\n" (xml-escape-string
;; (org-ref-get-bibtex-entry key))))
;; "")
(md5 key)))
(defun org-ref-get-ascii-bibliography (&optional sort)
"Create an ascii bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"\n\nBibliography\n=============\n\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
"\n"))))
(defun org-ref-get-md-bibliography (&optional sort)
"Create an md bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"# Bibliography\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-md x)) keys "\n\n")
"\n"))))
(defun org-ref-get-odt-bibliography (&optional sort)
"Create an ascii bibliography ofr odt export when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by
key. This is a variant of `org-ref-get-ascii-bibliography' where
some things are escaped since odt is an xml format."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(mapconcat (lambda (x)
(xml-escape-string (org-ref-get-bibtex-entry-ascii x)))
keys "\n"))))
(defun org-ref-pdf-p (filename)
"Check if FILENAME is PDF file.
From the PDF specification 1.7:
The first line of a PDF file shall be a header consisting of
the 5 characters %PDF- followed by a version number of the
form 1.N, where N is a digit between 0 and 7."
(let* ((header (with-temp-buffer
(set-buffer-multibyte nil)
(insert-file-contents-literally filename nil 0 5)
(buffer-string)))
(valid (string-equal (encode-coding-string header 'utf-8) "%PDF-")))
(if valid
valid
(message "Invalid pdf. Header = %s" header)
nil)))
;;;###autoload
(defmacro org-ref-link-set-parameters (type &rest parameters)
"Set link TYPE properties to PARAMETERS."
(declare (indent 1))
(if (fboundp 'org-link-set-parameters)
`(org-link-set-parameters ,type ,@parameters)
`(org-add-link-type ,type ,(plist-get parameters :follow) ,(plist-get parameters :export))))
;; This section creates some code that should speed up org-ref for large files.
;; I use org-element-parse-buffer a lot for getting information about labels
;; etc. However, it gets called a lot, and this is slow in large documents. Here
;; we try to use a cache that helps speed this up at least on loading. Some
;; notes for the future: on loading, it seems like fontification triggers buffer
;; changes, so here we only consider char changes. I am not sure this is the
;; best strategy overall. It is faster to use regexps for finding this
;; information, but those are substantially more difficult to debug in my
;; experience. There is an unfortunate number of ways to reference things in
;; org-mode, and so far this has been most reliable. An alternative might be to
;; leveralge what happens in font-lock somehow to update local variables
;; containing org-ref labels, refs, cites, etc. That would miss some #+names
;; though, and maybe some other things like custom-ids.
(defvar-local org-ref-char-change-tick nil
"Local variable to track character changes.")
(defvar-local org-ref-parse-buffer-cache nil
"Local variable to store parse buffer data.")
(defun org-ref-parse-buffer (&optional force)
"This is a thin wrapper around `org-element-parse-buffer'.
The idea is to cache the data, and return it unless we can tell
the buffer has been modified since the last time we ran it.
if FORCE is non-nil reparse the buffer no matter what."
(if force
(progn
(message "Forcing update.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(cond
((null org-ref-parse-buffer-cache)
;; (message "First parse.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
((not (eq org-ref-char-change-tick (buffer-chars-modified-tick)))
;; (message "Updating from a char change in the buffer.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(t
;; (message "Using cache.")
org-ref-parse-buffer-cache))))
;; * org-ref command
(defun org-ref ()
"Check the current org-buffer for potential issues."
(interactive)
(let* ((buf (get-buffer-create "*org-ref*"))
(cb (current-buffer))
(fname (buffer-file-name))
;; Check if elc is ok before anything else because if it is not, it
;; causes problems in org-ref.
(elc-ok (let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(orel-mod)
(org-ref-elc (concat
(file-name-sans-extension
(locate-library "org-ref"))
".elc"))
(orelc-mod)
(elc-version))
(when (file-exists-p org-ref-el)
(setq orel-mod (file-attribute-modification-time (file-attributes org-ref-el))))
(when (file-exists-p org-ref-elc)
(setq orelc-mod (file-attribute-modification-time (file-attributes org-ref-elc))))
(with-current-buffer buf
(read-only-mode -1)
(erase-buffer)
(org-mode)
(insert (format "#+title: org-ref report on [[%s][%s]]\n\n" (buffer-file-name cb) (buffer-name cb)))
(insert (format "org-ref called from %s" (buffer-file-name cb)))
(unless (time-less-p orel-mod orelc-mod)
(insert (format "org-ref.elc (%s) is older than org-ref.el (%s). That is probably not right. Please delete %s.\n"
(format-time-string "%Y-%m-%d %H:%M:%S" orelc-mod)
(format-time-string "%Y-%m-%d %H:%M:%S" orel-mod)
org-ref-elc))
(insert (format "- load-prefer-newer = %s\n" load-prefer-newer))
(insert (format " consider
- deleting %s
- [[elisp:(delete-file \"%s\")]]
- add (setq load-prefer-newer t) to your init files
- using https://github.com/emacscollective/auto-compile.\n" org-ref-elc org-ref-elc))
;; Check for byte-compiling compatibility with current emacs
(when (and org-ref-elc
(file-exists-p org-ref-elc))
(setq elc-version (with-temp-buffer
(insert-file-contents org-ref-elc)
(goto-char (point-min))
(when (re-search-forward ";;; in Emacs version \\([0-9]\\{2\\}\\.[0-9]+\\)"
nil t)
(match-string 1))))
(unless (string= elc-version
(format "%s.%s" emacs-major-version emacs-minor-version))
(insert (format "%s compiled with Emacs %s but you are running %s. That could be a problem.\n"
elc-version emacs-major-version emacs-minor-version))))))))
(bad-citations (org-ref-bad-cite-candidates))
(bad-refs (org-ref-bad-ref-candidates))
(bad-labels (org-ref-bad-label-candidates))
(bad-files (org-ref-bad-file-link-candidates))
(bib-candidates '())
(unreferenced-labels '())
natbib-required
natbib-used
cleveref-required
cleveref-used
biblatex-required
biblatex-used
mbuffer
mchar
(org-latex-prefer-user-labels (and (boundp 'org-latex-prefer-user-labels)
org-latex-prefer-user-labels)))
;; See if natbib, biblatex or cleveref are required
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(when (member (org-element-property :type link) org-ref-natbib-types)
(setq natbib-required t))
(when (member (org-element-property :type link) org-ref-biblatex-types)
(setq biblatex-required t))
(when (member (org-element-property :type link) '("cref" "Cref"))
(setq cleveref-required t)))
nil t)
;; See if natbib is probably used. This will miss a case where natbib is included somehow.
(setq natbib-used
(or
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{natbib} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{natbib}" nil t))))
(setq biblatex-used
(or
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{biblatex} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{biblatex}" nil t))))
(setq cleveref-used
(or
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{cleveref} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{cleveref}" nil t))))
;; setup bib-candidates. This checks a variety of things in the
;; bibliography, bibtex files. check for which bibliographies are used
(cl-loop for bibfile in (org-ref-find-bibliography)
do
(let ((bibdialect))
(with-current-buffer (find-file-noselect bibfile)
(setq bibdialect bibtex-dialect))
(cl-pushnew
(format "[[%s]] (dialect = %s)\n" bibfile bibdialect)
bib-candidates)))
;; Check bibliography style exists
(save-excursion
(goto-char 0)
(unless (re-search-forward "bibliographystyle:\\|\\\\bibliographystyle{" nil t)
(cl-pushnew
"No bibliography style found. This may be ok, if your latex class style sets that up, but if not this is an error. Try adding something like:
bibliographystyle:unsrt
at the end of your file.\n"
bib-candidates)))
;; Check if latex knows of the bibliographystyle. We only check links here.
;; I also assume this style exists as a bst file that kpsewhich can find.
(save-excursion
(goto-char 0)
(when (re-search-forward "bibliographystyle:" nil t)
;; on a link. get style
(let ((path (org-element-property :path (org-element-context))))
(unless (= 0 (shell-command (format "kpsewhich %s.bst" path)))
(cl-pushnew
(format "bibliographystyle \"%s\" may be unknown" path)
bib-candidates)))))
;; check for multiple bibliography links
(let* ((bib-links (-filter
(lambda (el)
(string= (org-element-property :type el) "bibliography"))
(org-element-map (org-element-parse-buffer) 'link 'identity)))
(n-bib-links (length bib-links)))
(when (> n-bib-links 1)
(mapc (lambda (link)
(setq
bib-candidates
(append
bib-candidates
(list (format "Multiple bibliography link: %s"
(org-element-property :raw-link link))))))
bib-links)))
;; Check for bibliography files existence.
(mapc (lambda (bibfile)
(unless (file-exists-p bibfile)
(cl-pushnew
(format "%s does not exist." bibfile)
bib-candidates)))
(org-ref-find-bibliography))
;; check for spaces in bibliography
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc (lambda (bibfile)
(when (string-match " " bibfile)
(cl-pushnew
(format "One or more spaces found in path to %s. No spaces are allowed in bibtex file paths. We recommend replacing them with -. Underscores usually cause other problems." bibfile)
bib-candidates)))
bibfiles))
;; validate bibtex files
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc
(lambda (bibfile)
(unless (with-current-buffer
(find-file-noselect bibfile)
(bibtex-validate))
(cl-pushnew
(format "Invalid bibtex file found. [[file:%s]]\n" bibfile)
bib-candidates)))
bibfiles)
;; check types
(mapc
(lambda (bibfile)
(with-current-buffer
(find-file-noselect bibfile)
(goto-char (point-min))
(while (re-search-forward "^@\\(.*?\\)[({]" nil t)
(when (and (not (string= "string" (downcase (match-string-no-properties 1))))
(not (member (s-trim (downcase (match-string-no-properties 1)))
(cdr (assoc bibtex-dialect
(list
(cons 'BibTeX (mapcar (lambda (e) (downcase (car e)))
bibtex-BibTeX-entry-alist))
(cons 'biblatex (mapcar (lambda (e) (downcase (car e)))
bibtex-biblatex-entry-alist))))))))
(cl-pushnew
(format "Invalid bibtex entry type (%s) found in [[file:%s::%s]]\n" (match-string-no-properties 1)
bibfile (line-number-at-pos))
bib-candidates)))))
bibfiles))
;; unreferenced labels
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((matches '()))
;; these are the org-ref label:stuff kinds
(while (re-search-forward
"[^#+]label:\\([a-zA-Z0-9:-]*\\)" nil t)
(cl-pushnew (cons
(match-string-no-properties 1)
(point))
matches))
;; now add all the other kinds of labels.
;; #+label:
(save-excursion
(goto-char (point-min))
(while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" nil t)
;; do not do this for tables. We get those in `org-ref-get-tblnames'.
;; who would have thought you have save match data here? Trust me. When
;; I wrote this, you did.
(unless (save-match-data (equal (car (org-element-at-point)) 'table))
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches))))
;; \label{}
(save-excursion
(goto-char (point-min))
(while (re-search-forward "\\\\label{\\([a-zA-Z0-9:-]*\\)}"
nil t)
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches)))
;; #+tblname: and actually #+label
(cl-loop for cell in (org-element-map (org-element-parse-buffer 'element) 'table
(lambda (table)
(cons (org-element-property :name table)
(org-element-property :begin table))))
do
(cl-pushnew cell matches))
;; CUSTOM_IDs
(org-map-entries
(lambda ()
(let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
(when (not (null custom_id))
(cl-pushnew (cons custom_id (point)) matches)))))
(goto-char (point-min))
(while (re-search-forward "^#\\+name:\\s-+\\(.*\\)" nil t)
(cl-pushnew (cons (match-string 1) (point)) matches))
;; unreference labels
(let ((refs (org-element-map (org-element-parse-buffer) 'link
(lambda (el)
(when (or (string= "ref" (org-element-property :type el))
(string= "eqref" (org-element-property :type el))
(string= "pageref" (org-element-property :type el))
(string= "nameref" (org-element-property :type el))
(string= "autoref" (org-element-property :type el))
(string= "cref" (org-element-property :type el))
(string= "Cref" (org-element-property :type el)))
(org-element-property :path el))))))
(cl-loop for (label . p) in matches
do
(when (and label (not (-contains? refs label)))
(cl-pushnew
(cons label (set-marker (make-marker) p))
unreferenced-labels)))))))
(with-current-buffer buf
(when bad-citations
(insert "\n* Bad citations\n")
(cl-loop for (key . marker) in bad-citations
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-refs
(insert "\n* Bad ref links\n")
(cl-loop for (key . marker) in bad-refs
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-labels
(insert "\n* Multiply defined label links\n")
(cl-loop for (key . marker) in bad-labels
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when unreferenced-labels
(insert "\n* Unreferenced label links\n")
(cl-loop for (key . marker) in unreferenced-labels
when (not (string= key ""))
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bib-candidates
(insert "\n* Bibliography\n")
(cl-loop for candidate in bib-candidates
do
(insert (format "- %s" candidate))))
(insert "\n* Miscellaneous\n")
(cl-loop for s in `(,(format "org-latex-prefer-user-labels = %s"
org-latex-prefer-user-labels)
,(format "bibtex-dialect = %s" bibtex-dialect)
,(format "biblatex is%srequired." (if biblatex-required " " " not "))
,(format "biblatex is%sused." (if biblatex-used " " " not "))
,(format "emacs-version = %s" (emacs-version))
,(format "org-version = %s" (org-version))
,(org-ref-version)
,(format "org-ref.el installed at %s" (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
,(format "completion backend = %s" org-ref-completion-library)
,(format "org-ref-insert-cite-function = %s" org-ref-insert-cite-function)
,(format "org-ref-insert-label-function = %s" org-ref-insert-label-function)
,(format "org-ref-insert-ref-function = %s" org-ref-insert-ref-function)
,(format "org-ref-cite-onclick-function = %s" org-ref-cite-onclick-function)
,(format "org-ref-default-bibliography = %S" org-ref-default-bibliography)
,(format "org-ref-default-bibliography is a list = %S" (listp org-ref-default-bibliography))
,(format "org-latex-pdf-process is defined as %s" org-latex-pdf-process)
,(format "natbib is%srequired." (if natbib-required " " " not "))
,(format "natbib is%sin %s or %s."
(if natbib-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "cleveref is%srequired." (if cleveref-required " " " not "))
,(format "cleveref is%sin %s or %s."
(if cleveref-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "bibtex-completion installed = %s" (featurep 'bibtex-completion))
,(format "bibtex-completion loaded = %s" (fboundp 'bibtex-completion-candidates)))
do
(insert "- " s "\n"))
(insert (format "- org-latex-default-packages-alist\n"))
(cl-loop for el in org-latex-default-packages-alist
do
(insert (format " %S\n" el)))
(if (null org-latex-packages-alist)
(insert "- org-latex-packages-alist is nil\n")
(insert "- org-latex-packages-alist\n")
(cl-loop for el in org-latex-packages-alist
do
(insert (format " %S\n" el))))
(insert (format "- ox-bibtex loaded = %s\n" (featurep 'ox-bibtex)))
(insert (format "- ox-bibtex loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ox-bibtex-i (seq-position load-history (assoc (locate-library "ox-bibtex") load-history))))
(and org-ref-i ox-bibtex-i
(> org-ref-i ox-bibtex-i)))))
(insert (format "- ebib loaded = %s\n" (featurep 'ebib)))
(insert (format "- ebib loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ebib-i (seq-position load-history (assoc (locate-library "ebib") load-history))))
(and org-ref-i ebib-i
(> org-ref-i ebib-i)))))
(insert "- cite link definition:\n" (with-temp-buffer
(insert (format "%S" (assoc "cite" org-link-parameters)))
(pp-buffer)
(buffer-string)))
(insert "\n* LaTeX setup\n\n")
(cl-loop for executable in '("latex" "pdflatex" "bibtex" "biblatex"
"makeindex" "makeglossaries")
do
(insert (format "%s is installed at %s\n" executable (executable-find executable))))
(insert "\n* Warnings\n")
(if (get-buffer "*Warnings*")
(cl-loop for line in (s-split "\n" (with-current-buffer "*Warnings*"
(buffer-string)))
if (s-starts-with? "Warning (org-ref):" line)
do
(insert " - " line "\n"))
(insert "- No (org-ref) Warnings found."))
(insert (format "\n* Utilities
- [[elisp:(progn (find-file %S) (ispell))][Spell check document]]
- [[elisp:(progn (find-file %S) (org-ref))][recheck document with org-ref]]
" fname fname))
(goto-char (point-min))
;; (setq header-line-format "Press q to quit.")
;; (local-set-key "q"
;; #'(lambda ()
;; (interactive)
;; (delete-window)))
(read-only-mode))
(display-buffer-in-side-window buf '((side . right)))))
(provide 'org-ref-utils)
;;; org-ref-utils.el ends here
| true | ;;; org-ref-utils.el --- Utility functions for org-ref -*- lexical-binding: t; -*-
;; Copyright (C) 2016 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords:
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
(eval-when-compile
(require 'cl-lib))
(require 'org)
(require 'org-ref-pdf) ; for pdftotext-executable
(defcustom org-ref-bib-html "<h1 class='org-ref-bib-h1'>Bibliography</h1>\n"
"HTML header to use for bibliography in HTML export."
:type 'string
:group 'org-ref)
(defcustom org-ref-bib-html-sorted nil
"Determine whether the HTML bibliography should be sorted."
:type 'boolean
:group 'org-ref)
(defcustom org-ref-search-whitespace-regexp "\\s-+"
"A whitespace regexp for use in `org-ref-strip-string."
:group 'org-ref)
(defvar org-ref-cite-types)
(defvar org-ref-get-pdf-filename-function)
(defvar org-ref-notes-function)
(defvar org-ref-bibliography-entry-format)
(declare-function 'org-ref-get-bibtex-key-and-file "org-ref-core.el")
(declare-function 'org-ref-key-in-file-p "org-ref-core.el")
(declare-function 'org-ref-find-bibliography "org-ref-core.el")
(declare-function 'org-ref-bib-citation "org-ref-core.el")
(declare-function 'org-ref-get-bibtex-key-under-cursor "org-ref-core.el")
;;; Code:
;;;###autoload
(defun org-ref-version ()
"Provide a version string for org-ref.
Copies the string to the clipboard."
(interactive)
;; version in the el file.
(let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(org-ref-dir (file-name-directory org-ref-el))
org-version
git-commit
version-string)
(setq org-version (with-temp-buffer
(insert-file-contents org-ref-el)
(goto-char (point-min))
(re-search-forward ";; Version:")
(s-trim (buffer-substring (point)
(line-end-position)))))
(setq git-commit
;; If in git, get current commit
(let ((default-directory org-ref-dir))
(when (and
;; this is tricky, as a submodule, .git is a file
(or (file-directory-p ".git") (file-exists-p ".git"))
(= 0 (shell-command "git rev-parse --git-dir")))
(format "%s in %s"
(s-trim (shell-command-to-string "git rev-parse HEAD"))
(s-trim (shell-command-to-string "git rev-parse --show-toplevel"))))))
(setq version-string (format "org-ref: Version %s%s"
org-version
(if git-commit
(format " (git-commit %s)" git-commit)
"")))
(kill-new version-string)
(message version-string)))
(defun org-ref-report-issue ()
"Report an issue in org-ref.
Opens https://github.com/jkitchin/org-ref/issues/new."
(save-window-excursion
(org-ref-debug)
(kill-new (buffer-string)))
(message "org-ref-debug has been run. You can paste the results in the issue website if you like.")
(browse-url "https://github.com/jkitchin/org-ref/issues/new"))
;;* Debug(require 'org-ref-pdf)
(defmacro ords (&rest body)
"Evaluate BODY and return a string."
`(format "%s" (progn ,@body)))
;;;###autoload
(defun org-ref-debug ()
"Print some debug information to a buffer."
(interactive)
(switch-to-buffer "*org-ref-debug*")
(erase-buffer)
(org-mode)
(insert
(s-format "#+TITLE: org-ref debug
${org-ref-version}
* Variables
1. org-ref-completion-library: ${org-ref-completion-library}
2. org-ref-bibliography-notes: ${org-ref-bibliography-notes} (exists ${orbn-p})
3. org-ref-default-bibliography: ${org-ref-default-bibliography} (exists ${ordb-p}) (listp ${ordb-listp})
4. org-ref-pdf-directory: ${org-ref-pdf-directory} (exists ${orpd-p})
* System
system-type: ${system}
system-configuration: ${system-configuration}
window system: ${window-system}
Emacs: ${emacs-version}
org-version: ${org-version}
* about org-ref
org-ref installed in ${org-ref-location}.
** Dependencies
helm-bibtex ${helm-bibtex-path}
* org-ref-pdf (loaded: ${org-ref-pdf-p})
system pdftotext: ${pdftotext}
You set pdftotext-executable to ${pdftotext-executable} (exists: ${pdftotext-executable-p})
* org-ref-url-utils (loaded: ${org-ref-url-p})
* export variables
org-latex-pdf-process:
${org-latex-pdf-process}
"
'aget
`(("org-ref-completion-library" . ,(format "%s" org-ref-completion-library))
("org-ref-bibliography-notes" . ,(format "%s" org-ref-bibliography-notes))
("org-ref-bibliography-notes exists" . ,(format "%s" (when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes))))
("org-ref-version" . ,(org-ref-version))
("org-latex-pdf-process" . ,(format "%S" org-latex-pdf-process))
("org-ref-default-bibliography" . ,(format "%s" org-ref-default-bibliography))
("ordb-p" . ,(format "%s" (mapcar 'file-exists-p org-ref-default-bibliography)))
("ordb-listp" . ,(ords (listp org-ref-default-bibliography)))
("orbn-p" . ,(when org-ref-bibliography-notes
(file-exists-p org-ref-bibliography-notes)))
("org-ref-pdf-directory" . ,(format "%s" org-ref-pdf-directory))
("orpd-p" . ,(format "%s" (file-exists-p org-ref-pdf-directory)))
("org-ref-location" . ,(format "%s" (locate-library "org-ref")))
("system" . ,(format "System: %s" system-type))
("system-configuration" . ,(ords system-configuration))
("window-system" . ,(format "Window system: %s" window-system))
("emacs-version" . ,(ords (emacs-version)))
("org-version" . ,(org-version))
("helm-bibtex-path" . ,(ords (locate-library "helm-bibtex")))
("org-ref-pdf-p" . ,(ords (featurep 'org-ref-pdf)))
("pdftotext" . ,(ords (if (featurep 'org-ref-pdf)
(executable-find "pdftotext")
"org-ref-pdf not loaded")))
("pdftotext-executable" . ,(ords (if (featurep 'org-ref-pdf)
pdftotext-executable
"org-ref-pdf not loaded")))
("pdftotext-executable-p" . ,(ords (if (featurep 'org-ref-pdf)
(or
(executable-find pdftotext-executable)
(file-exists-p pdftotext-executable))
"org-ref-pdf not loaded")))
("org-ref-url-p" . ,(ords (featurep 'org-ref-url)))))))
(defun org-ref-reftex-get-bib-field (field entry &optional format)
"Get FIELD from a bibtex ENTRY in optional FORMAT.
Similar to `reftex-get-bib-field', but removes enclosing braces
and quotes in FIELD in the bibtex ENTRY."
(let ((result))
(setq result (reftex-get-bib-field field entry format))
(when (and (not (string= result "")) (string= "{" (substring result 0 1)))
(setq result (substring result 1 -1)))
(when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
(setq result (substring result 1 -1)))
result))
(defun org-ref-reftex-format-citation (entry format)
"Format the bibtex ENTRY according to the FORMAT argument.
ENTRY is from `bibtex-parse-entry'
The FORMAT is a string with these percent escapes.
In the format, the following percent escapes will be expanded.
%l The BibTeX label of the citation.
%a List of author names, see also `reftex-cite-punctuation'.
%2a Like %a, but abbreviate more than 2 authors like Jones et al.
%A First author name only.
%e Works like %a, but on list of editor names. (%2e and %E work as well)
It is also possible to access all other BibTeX database fields:
%b booktitle %c chapter %d edition %h howpublished
%i institution %j journal %k key %m month
%n number %o organization %p pages %P first page
%r address %s school %u publisher %t title
%v volume %y year
%B booktitle, abbreviated %T title, abbreviated
%U url
%D doi
%S series %N note
%f pdf filename (key.pdf)
%F absolute pdf filename (returned from `org-ref-get-pdf-filename-function')
Usually, only %l is needed. The other stuff is mainly for the echo area
display, and for (setq reftex-comment-citations t).
%< as a special operator kills punctuation and space around it after the
string has been formatted.
A pair of square brackets indicates an optional argument, and RefTeX
will prompt for the values of these arguments.
Beware that all this only works with BibTeX database files. When
citations are made from the \bibitems in an explicit thebibliography
environment, only %l is available."
;; Format a citation from the info in the BibTeX ENTRY
(unless (stringp format) (setq format "\\cite{%l}"))
(if (and reftex-comment-citations
(string-match "%l" reftex-cite-comment-format))
(error "Reftex-cite-comment-format contains invalid %%l"))
(while (string-match
"\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
format)
(let ((n (string-to-number (match-string 4 format)))
(l (string-to-char (match-string 5 format)))
rpl b e)
(save-match-data
(setq rpl
(cond
((= l ?l) (concat
(org-ref-reftex-get-bib-field "&key" entry)
(if reftex-comment-citations
reftex-cite-comment-format
"")))
((= l ?a) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(reftex-format-names
(reftex-get-bib-names "author" entry)
(or n 2))))
((= l ?A) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(car (reftex-get-bib-names "author" entry))))
((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
((= l ?B) (reftex-abbreviate-title
(org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
((= l ?e) (reftex-format-names
(reftex-get-bib-names "editor" entry)
(or n 2)))
((= l ?E) (car (reftex-get-bib-names "editor" entry)))
((= l ?f) (concat (org-ref-reftex-get-bib-field "=key=" entry) ".pdf"))
((= l ?F) (funcall org-ref-get-pdf-filename-function
(org-ref-reftex-get-bib-field "=key=" entry)))
((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
(if (string= "" jt)
(reftex-get-bib-field "journaltitle" entry)
jt)))
((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
((= l ?N) (org-ref-reftex-get-bib-field "note" entry))
((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
((= l ?P) (car (split-string
(org-ref-reftex-get-bib-field "pages" entry)
"[- .]+")))
((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
;; strip enclosing brackets from title if they are there
((= l ?t) (replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry)))
((= l ?T) (reftex-abbreviate-title
(replace-regexp-in-string
"\n\\|\t\\|\s+" " "
(org-ref-reftex-get-bib-field "title" entry))))
((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
(if (string= rpl "")
(setq b (match-beginning 2) e (match-end 2))
(setq b (match-beginning 3) e (match-end 3)))
(setq format (concat (substring format 0 b) rpl (substring format e)))))
(while (string-match "%%" format)
(setq format (replace-match "%" t t format)))
(while (string-match "[ ,.;:]*%<" format)
(setq format (replace-match "" t t format)))
format)
(defun org-ref-get-bibtex-entry-citation (key)
"Return a string for the bibliography entry corresponding to KEY.
Format according to the type in `org-ref-bibliography-entry-format'."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry) (bibtex-entry) (entry-type) (format))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq bibtex-entry (bibtex-parse-entry))
;; downcase field names so they work in the format-citation code
(dolist (cons-cell bibtex-entry)
(setf (car cons-cell) (downcase (car cons-cell))))
(setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
(setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
(if format
(setq entry (org-ref-reftex-format-citation bibtex-entry format))
;; if no format, we use the bibtex entry itself as a fallback
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))))
entry))
(defun org-ref-get-bibtex-entry (key)
"Return the bibtex entry as a string."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
(file) (entry))
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s"
key (file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(save-restriction
(bibtex-narrow-to-entry)
(setq entry (buffer-string)))
entry)))
;;*** key at point functions
(defun org-ref-get-pdf-filename (key)
"Return the pdf filename associated with a bibtex KEY.
This searches for the pattern KEY*.pdf. If one result is found it
is returned, but if multiple results are found, e.g. there are
related files to the KEY you are prompted for which one you want."
(if org-ref-pdf-directory
(let* ((pdf-dirs (if (listp org-ref-pdf-directory)
org-ref-pdf-directory
(list org-ref-pdf-directory)))
(pdfs (-flatten (--map (file-expand-wildcards
(f-join it (format "%s*.pdf" key)))
(-flatten pdf-dirs)))))
(cond
((= 0 (length pdfs))
(expand-file-name (format "%s.pdf" key) org-ref-pdf-directory))
((= 1 (length pdfs))
(car pdfs))
((> (length pdfs) 1)
(completing-read "Choose: " pdfs))))
;; No org-ref-pdf-directory defined so return just a file name.
(format "%s.pdf" key)))
(defun org-ref-get-mendeley-filename (key)
"Return the pdf filename indicated by mendeley file field.
Falls back to `org-ref-get-pdf-filename' if file field does not exist.
Contributed by https://github.com/autosquid.
Argument KEY is the bibtex key."
(let* ((results (org-ref-get-bibtex-key-and-file key))
(bibfile (cdr results))
entry)
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(let ((e (org-ref-reftex-get-bib-field "file" entry)))
(if (> (length e) 4)
(let ((clean-field (replace-regexp-in-string "{\\|}\\|\\\\" "" e)))
(let ((first-file (car (split-string clean-field ";" t))))
(format "/%s" (substring first-file 1
(- (length first-file) 4)))))
(format (concat
(file-name-as-directory org-ref-pdf-directory)
"%s.pdf")
key))))))
(defun org-ref-get-pdf-filename-helm-bibtex (key)
"Use helm-bibtex to retrieve a PDF filename for KEY.
helm-bibtex looks in both the configured directory
`bibtex-completion-library-path' and in the fields of the bibtex
item for a filename. It understands file fields exported by
Jabref, Mendeley and Zotero. See `bibtex-completion-find-pdf'."
(let ((bibtex-completion-bibliography (org-ref-find-bibliography)))
(or (car (bibtex-completion-find-pdf key)) "")))
;;;###autoload
(defun org-ref-open-pdf-at-point ()
"Open the pdf for bibtex key under point if it exists."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(pdf-file (funcall org-ref-get-pdf-filename-function key)))
(if (file-exists-p pdf-file)
(org-open-file pdf-file)
(message "no pdf found for %s" key))))
;;;###autoload
(defun org-ref-open-url-at-point ()
"Open the url for bibtex key under point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
;; I like this better than bibtex-url which does not always find
;; the urls
(catch 'done
(let ((url (s-trim (bibtex-autokey-get-field "url"))))
(unless (s-blank? url)
(browse-url url)
(throw 'done nil)))
(let ((doi (s-trim (bibtex-autokey-get-field "doi"))))
(unless (s-blank? doi)
(if (string-match "^http" doi)
(browse-url doi)
(browse-url (format "http://dx.doi.org/%s" doi)))
(throw 'done nil))))))))
;;;###autoload
(defun org-ref-open-notes-at-point (&optional thekey)
"Open the notes for bibtex key under point in a cite link in a buffer.
Can also be called with THEKEY in a program."
(interactive)
(when (null thekey)
(setq thekey (org-ref-get-bibtex-key-under-cursor)))
(funcall org-ref-notes-function thekey))
;;;###autoload
(defun org-ref-citation-at-point ()
"Give message of current citation at point."
(interactive)
(org-ref-format-entry (org-ref-get-bibtex-key-under-cursor)))
;;;###autoload
(defun org-ref-open-citation-at-point ()
"Open bibtex file to key at point."
(interactive)
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results)))
(find-file bibfile)
(bibtex-search-entry key)))
;;*** cite menu
(defvar org-ref-cite-menu-funcs '()
"Functions to run on cite click menu.
Each entry is a list of (key menu-name function). The function
must take no arguments and work on the key at point. Do not
modify this variable, it is set to empty in the menu click
function, and functions are conditionally added to it.")
(defvar org-ref-user-cite-menu-funcs
'(("C" "rossref" org-ref-crossref-at-point)
("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
("s" "Copy summary" org-ref-copy-entry-as-summary))
"User-defined functions to run on bibtex key at point.")
;;;###autoload
(defun org-ref-copy-entry-as-summary ()
"Copy the bibtex entry for the citation at point as a summary."
(interactive)
(kill-new (org-ref-bib-citation)))
;;;###autoload
(defun org-ref-copy-cite-as-summary ()
"Copy a summary for the citation at point to the clipboard."
(interactive)
(kill-new (org-ref-link-message)))
;;;###autoload
(defun org-ref-copy-entry-at-point-to-file ()
"Copy the bibtex entry for the citation at point to NEW-FILE.
Prompt for NEW-FILE includes bib files in
`org-ref-default-bibliography', and bib files in current working
directory. You can also specify a new file."
(interactive)
(let ((new-file (completing-read
"Copy to bibfile: "
(append org-ref-default-bibliography
(f-entries "." (lambda (f) (f-ext? f "bib"))))))
(key (org-ref-get-bibtex-key-under-cursor)))
(save-window-excursion
(org-ref-open-citation-at-point)
(bibtex-copy-entry-as-kill))
(let ((bibtex-files (list (file-truename new-file))))
(if (assoc key (bibtex-global-key-alist))
(message "That key already exists in %s" new-file)
;; add to file
(save-window-excursion
(find-file new-file)
(goto-char (point-max))
;; make sure we are at the beginning of a line.
(unless (looking-at "^") (insert "\n\n"))
(bibtex-yank)
(save-buffer))))))
(defun org-ref-get-doi-at-point ()
"Get doi for key at point."
(let* ((results (org-ref-get-bibtex-key-and-file))
(key (car results))
(bibfile (cdr results))
doi)
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(setq doi (bibtex-autokey-get-field "doi"))
;; in case doi is a url, remove the url part.
(replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
;;**** functions that operate on key at point for click menu
;;;###autoload
(defun org-ref-ads-at-point ()
"Open the doi in ADS for bibtex key under point."
(interactive)
(doi-utils-ads (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-at-point ()
"Open the doi in wos for bibtex key under point."
(interactive)
(doi-utils-wos (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-citing-at-point ()
"Open the doi in wos citing articles for bibtex key under point."
(interactive)
(doi-utils-wos-citing (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-wos-related-at-point ()
"Open the doi in wos related articles for bibtex key under point."
(interactive)
(doi-utils-wos-related (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-google-scholar-at-point ()
"Search google scholar for bibtex key under point using the title."
(interactive)
(browse-url
(url-encode-url
(format
"http://scholar.google.com/scholar?q=%s"
(let* ((key-file (org-ref-get-bibtex-key-and-file))
(key (car key-file))
(file (cdr key-file))
entry)
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(org-ref-reftex-get-bib-field "title" entry)))))))
;;;###autoload
(defun org-ref-pubmed-at-point ()
"Open the doi in pubmed for bibtex key under point."
(interactive)
(doi-utils-pubmed (org-ref-get-doi-at-point)))
;;;###autoload
(defun org-ref-crossref-at-point ()
"Open the doi in crossref for bibtex key under point."
(interactive)
(doi-utils-crossref (org-ref-get-doi-at-point)))
;;* General org-ref utilities
(defun org-ref-strip-string (string)
"Strip leading and trailing whitespace from the STRING."
(replace-regexp-in-string
(concat org-ref-search-whitespace-regexp "$" ) ""
(replace-regexp-in-string
(concat "^" org-ref-search-whitespace-regexp ) "" string)))
(defun org-ref-split-and-strip-string (string)
"Split key-string and strip keys in STRING.
Assumes the key-string is comma delimited."
(mapcar 'org-ref-strip-string (split-string string ",")))
(defun org-ref-get-bibtex-keys (&optional sort)
"Return a list of unique keys in the buffer.
Use SORT to specify alphabetical order by key."
(let ((keys '()))
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(let ((plist (nth 1 link)))
(when (-contains? org-ref-cite-types (plist-get plist ':type))
(dolist
(key
(org-ref-split-and-strip-string (plist-get plist ':path)))
(when (not (-contains? keys key))
(setq keys (append keys (list key))))))))
;; set with-affiliated to get keys in captions
nil nil nil t)
(when sort
;; Sort keys alphabetically
(setq keys (cl-sort keys 'string-lessp :key 'downcase)))
keys))
;;;###autoload
(defun org-ref-bibliography (&optional sort)
"Create a new buffer with a bibliography.
If SORT is non-nil it is alphabetically sorted by key
This is mostly for convenience to see what has been cited.
Entries are formatted according to the bibtex entry type in
`org-ref-bibliography-entry-format', and the actual entries are
generated by `org-ref-reftex-format-citation'."
(interactive)
(let ((bib (mapconcat
'identity
(cl-loop for i from 1
for citation in
(mapcar
(lambda (key)
(let* ((results (org-ref-get-bibtex-key-and-file key))
(key (car results))
(bibfile (cdr results)))
(format "cite:%s %s" key
(if bibfile
(save-excursion
(with-temp-buffer
(insert-file-contents bibfile)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key)
(org-ref-format-entry key)))
"!!! No entry found !!!"))))
(org-ref-get-bibtex-keys sort))
collect (format "%3s. %s" i citation))
"\n\n")))
(switch-to-buffer-other-window (format "%s-bibliography" (buffer-file-name)))
(erase-buffer)
(insert bib)
(org-mode)))
(defun org-ref-get-bibtex-entry-html (key)
"Return an html string for the bibliography entry corresponding to KEY."
(let ((output))
(setq output (concat (format "<a name=\"%s\"></a>" key)
(org-ref-get-bibtex-entry-citation key)))
(setq output (org-ref-clean-unused-entry-html output))
(format "<li><a id=\"%s\">[%s]</a> %s</li>"
key key output)))
(defun org-ref-clean-unused-entry-html (entry-html)
"Return from the html string ENTRY-HTML a cleaner version"
;; unescape the &
(setq entry-html (replace-regexp-in-string "\\\\&" "&" entry-html))
;; hack to replace {} around text
(setq entry-html (replace-regexp-in-string "{" "" entry-html))
(setq entry-html (replace-regexp-in-string "}" "" entry-html))
;; get rid of empty parens
(setq entry-html (replace-regexp-in-string "()" "" entry-html))
;; Remove empty volume, number field if empty
(setq entry-html (replace-regexp-in-string "<b></b>," "" entry-html))
;; get rid of empty link and doi
(setq entry-html (replace-regexp-in-string " <a href=\"\">\\(link\\)?</a>\\.?" "" entry-html))
;; change double dash to single dash
(setq entry-html (replace-regexp-in-string "--" "-" entry-html))
(setq entry-html (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" entry-html))
entry-html)
(defun org-ref-get-html-bibliography (&optional sort)
"Create an html bibliography when there are keys.
If one of SORT and `org-ref-bib-html-sorted' is non-nil,
the bibliography is alphabetically sorted."
(let ((keys (org-ref-get-bibtex-keys (or sort org-ref-bib-html-sorted))))
(when keys
(concat org-ref-bib-html "<ul class='org-ref-bib'>"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
"\n</ul>"))))
(defun org-ref-get-bibtex-entry-org (key)
"Return an org string for the bibliography entry corresponding to KEY."
(let ((org-ref-bibliography-files (org-ref-find-bibliography))
file entry)
(setq file (catch 'result
(cl-loop for file in org-ref-bibliography-files do
(if (org-ref-key-in-file-p key (file-truename file))
(throw 'result file)
(message "%s not found in %s" key
(file-truename file))))))
(with-temp-buffer
(insert-file-contents file)
(bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
(bibtex-search-entry key nil 0)
(setq entry (bibtex-parse-entry))
(format "** %s - %s
:PROPERTIES:
%s
:END:
" (org-ref-reftex-get-bib-field "author" entry)
(org-ref-reftex-get-bib-field "title" entry)
(concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
(mapconcat
(lambda (element) (format " :%s: %s"
(upcase (car element))
(cdr element)))
entry
"\n"))))))
(defun org-ref-get-org-bibliography (&optional sort)
"Create an org bibliography when there are keys.
If SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat "* Bibliography\n"
(mapconcat (lambda (x)
(org-ref-get-bibtex-entry-org x)) keys "\n")
"\n"))))
(defun org-ref-get-bibtex-entry-ascii (key)
"Return an ascii string for the bibliography entry corresponding to KEY."
(format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
(defun org-ref-get-bibtex-entry-md (key)
"Return a md string for the bibliography entry corresponding to KEY."
;; We create an anchor to the key that we can jump to, and provide a jump back
;; link with the md5 of the key.
(format "<a id=\"%s\"></a>[%s] %s%s [↩](#%s)"
key key
(org-ref-clean-unused-entry-html (org-ref-get-bibtex-entry-citation key))
""
;; Note: This is to temporarily resolve issue #558. This worked fine
;; for me earlier, so I don't know why it doesn't work in this issue.
;; (if (plist-get info :md-publish-bibtex)
;; (format
;; " <a href=\"data:text/plain;charset=US-ASCII;base64,%s\" title=\"%s\">[bib]</a>"
;; (base64-encode-string (org-ref-get-bibtex-entry key))
;; (concat "Right-click to open\n" (xml-escape-string
;; (org-ref-get-bibtex-entry key))))
;; "")
(md5 key)))
(defun org-ref-get-ascii-bibliography (&optional sort)
"Create an ascii bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"\n\nBibliography\n=============\n\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
"\n"))))
(defun org-ref-get-md-bibliography (&optional sort)
"Create an md bibliography when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by key."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(concat
"# Bibliography\n"
(mapconcat (lambda (x) (org-ref-get-bibtex-entry-md x)) keys "\n\n")
"\n"))))
(defun org-ref-get-odt-bibliography (&optional sort)
"Create an ascii bibliography ofr odt export when there are keys.
if SORT is non-nil the bibliography is sorted alphabetically by
key. This is a variant of `org-ref-get-ascii-bibliography' where
some things are escaped since odt is an xml format."
(let ((keys (org-ref-get-bibtex-keys sort)))
(when keys
(mapconcat (lambda (x)
(xml-escape-string (org-ref-get-bibtex-entry-ascii x)))
keys "\n"))))
(defun org-ref-pdf-p (filename)
"Check if FILENAME is PDF file.
From the PDF specification 1.7:
The first line of a PDF file shall be a header consisting of
the 5 characters %PDF- followed by a version number of the
form 1.N, where N is a digit between 0 and 7."
(let* ((header (with-temp-buffer
(set-buffer-multibyte nil)
(insert-file-contents-literally filename nil 0 5)
(buffer-string)))
(valid (string-equal (encode-coding-string header 'utf-8) "%PDF-")))
(if valid
valid
(message "Invalid pdf. Header = %s" header)
nil)))
;;;###autoload
(defmacro org-ref-link-set-parameters (type &rest parameters)
"Set link TYPE properties to PARAMETERS."
(declare (indent 1))
(if (fboundp 'org-link-set-parameters)
`(org-link-set-parameters ,type ,@parameters)
`(org-add-link-type ,type ,(plist-get parameters :follow) ,(plist-get parameters :export))))
;; This section creates some code that should speed up org-ref for large files.
;; I use org-element-parse-buffer a lot for getting information about labels
;; etc. However, it gets called a lot, and this is slow in large documents. Here
;; we try to use a cache that helps speed this up at least on loading. Some
;; notes for the future: on loading, it seems like fontification triggers buffer
;; changes, so here we only consider char changes. I am not sure this is the
;; best strategy overall. It is faster to use regexps for finding this
;; information, but those are substantially more difficult to debug in my
;; experience. There is an unfortunate number of ways to reference things in
;; org-mode, and so far this has been most reliable. An alternative might be to
;; leveralge what happens in font-lock somehow to update local variables
;; containing org-ref labels, refs, cites, etc. That would miss some #+names
;; though, and maybe some other things like custom-ids.
(defvar-local org-ref-char-change-tick nil
"Local variable to track character changes.")
(defvar-local org-ref-parse-buffer-cache nil
"Local variable to store parse buffer data.")
(defun org-ref-parse-buffer (&optional force)
"This is a thin wrapper around `org-element-parse-buffer'.
The idea is to cache the data, and return it unless we can tell
the buffer has been modified since the last time we ran it.
if FORCE is non-nil reparse the buffer no matter what."
(if force
(progn
(message "Forcing update.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(cond
((null org-ref-parse-buffer-cache)
;; (message "First parse.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
((not (eq org-ref-char-change-tick (buffer-chars-modified-tick)))
;; (message "Updating from a char change in the buffer.")
(setq-local org-ref-char-change-tick (buffer-chars-modified-tick))
(setq-local org-ref-parse-buffer-cache (org-element-parse-buffer)))
(t
;; (message "Using cache.")
org-ref-parse-buffer-cache))))
;; * org-ref command
(defun org-ref ()
"Check the current org-buffer for potential issues."
(interactive)
(let* ((buf (get-buffer-create "*org-ref*"))
(cb (current-buffer))
(fname (buffer-file-name))
;; Check if elc is ok before anything else because if it is not, it
;; causes problems in org-ref.
(elc-ok (let* ((org-ref-el (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
(orel-mod)
(org-ref-elc (concat
(file-name-sans-extension
(locate-library "org-ref"))
".elc"))
(orelc-mod)
(elc-version))
(when (file-exists-p org-ref-el)
(setq orel-mod (file-attribute-modification-time (file-attributes org-ref-el))))
(when (file-exists-p org-ref-elc)
(setq orelc-mod (file-attribute-modification-time (file-attributes org-ref-elc))))
(with-current-buffer buf
(read-only-mode -1)
(erase-buffer)
(org-mode)
(insert (format "#+title: org-ref report on [[%s][%s]]\n\n" (buffer-file-name cb) (buffer-name cb)))
(insert (format "org-ref called from %s" (buffer-file-name cb)))
(unless (time-less-p orel-mod orelc-mod)
(insert (format "org-ref.elc (%s) is older than org-ref.el (%s). That is probably not right. Please delete %s.\n"
(format-time-string "%Y-%m-%d %H:%M:%S" orelc-mod)
(format-time-string "%Y-%m-%d %H:%M:%S" orel-mod)
org-ref-elc))
(insert (format "- load-prefer-newer = %s\n" load-prefer-newer))
(insert (format " consider
- deleting %s
- [[elisp:(delete-file \"%s\")]]
- add (setq load-prefer-newer t) to your init files
- using https://github.com/emacscollective/auto-compile.\n" org-ref-elc org-ref-elc))
;; Check for byte-compiling compatibility with current emacs
(when (and org-ref-elc
(file-exists-p org-ref-elc))
(setq elc-version (with-temp-buffer
(insert-file-contents org-ref-elc)
(goto-char (point-min))
(when (re-search-forward ";;; in Emacs version \\([0-9]\\{2\\}\\.[0-9]+\\)"
nil t)
(match-string 1))))
(unless (string= elc-version
(format "%s.%s" emacs-major-version emacs-minor-version))
(insert (format "%s compiled with Emacs %s but you are running %s. That could be a problem.\n"
elc-version emacs-major-version emacs-minor-version))))))))
(bad-citations (org-ref-bad-cite-candidates))
(bad-refs (org-ref-bad-ref-candidates))
(bad-labels (org-ref-bad-label-candidates))
(bad-files (org-ref-bad-file-link-candidates))
(bib-candidates '())
(unreferenced-labels '())
natbib-required
natbib-used
cleveref-required
cleveref-used
biblatex-required
biblatex-used
mbuffer
mchar
(org-latex-prefer-user-labels (and (boundp 'org-latex-prefer-user-labels)
org-latex-prefer-user-labels)))
;; See if natbib, biblatex or cleveref are required
(org-element-map (org-element-parse-buffer) 'link
(lambda (link)
(when (member (org-element-property :type link) org-ref-natbib-types)
(setq natbib-required t))
(when (member (org-element-property :type link) org-ref-biblatex-types)
(setq biblatex-required t))
(when (member (org-element-property :type link) '("cref" "Cref"))
(setq cleveref-required t)))
nil t)
;; See if natbib is probably used. This will miss a case where natbib is included somehow.
(setq natbib-used
(or
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "natbib" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{natbib} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{natbib}" nil t))))
(setq biblatex-used
(or
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "biblatex" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{biblatex} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{biblatex}" nil t))))
(setq cleveref-used
(or
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-default-packages-alist))
(member "cleveref" (mapcar (lambda (x) (when (listp x) (nth 1 x))) org-latex-packages-alist))
;; see of something like \usepackage{cleveref} exists.
(save-excursion
(goto-char (point-min))
(re-search-forward "{cleveref}" nil t))))
;; setup bib-candidates. This checks a variety of things in the
;; bibliography, bibtex files. check for which bibliographies are used
(cl-loop for bibfile in (org-ref-find-bibliography)
do
(let ((bibdialect))
(with-current-buffer (find-file-noselect bibfile)
(setq bibdialect bibtex-dialect))
(cl-pushnew
(format "[[%s]] (dialect = %s)\n" bibfile bibdialect)
bib-candidates)))
;; Check bibliography style exists
(save-excursion
(goto-char 0)
(unless (re-search-forward "bibliographystyle:\\|\\\\bibliographystyle{" nil t)
(cl-pushnew
"No bibliography style found. This may be ok, if your latex class style sets that up, but if not this is an error. Try adding something like:
bibliographystyle:unsrt
at the end of your file.\n"
bib-candidates)))
;; Check if latex knows of the bibliographystyle. We only check links here.
;; I also assume this style exists as a bst file that kpsewhich can find.
(save-excursion
(goto-char 0)
(when (re-search-forward "bibliographystyle:" nil t)
;; on a link. get style
(let ((path (org-element-property :path (org-element-context))))
(unless (= 0 (shell-command (format "kpsewhich %s.bst" path)))
(cl-pushnew
(format "bibliographystyle \"%s\" may be unknown" path)
bib-candidates)))))
;; check for multiple bibliography links
(let* ((bib-links (-filter
(lambda (el)
(string= (org-element-property :type el) "bibliography"))
(org-element-map (org-element-parse-buffer) 'link 'identity)))
(n-bib-links (length bib-links)))
(when (> n-bib-links 1)
(mapc (lambda (link)
(setq
bib-candidates
(append
bib-candidates
(list (format "Multiple bibliography link: %s"
(org-element-property :raw-link link))))))
bib-links)))
;; Check for bibliography files existence.
(mapc (lambda (bibfile)
(unless (file-exists-p bibfile)
(cl-pushnew
(format "%s does not exist." bibfile)
bib-candidates)))
(org-ref-find-bibliography))
;; check for spaces in bibliography
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc (lambda (bibfile)
(when (string-match " " bibfile)
(cl-pushnew
(format "One or more spaces found in path to %s. No spaces are allowed in bibtex file paths. We recommend replacing them with -. Underscores usually cause other problems." bibfile)
bib-candidates)))
bibfiles))
;; validate bibtex files
(let ((bibfiles (mapcar 'expand-file-name
(org-ref-find-bibliography))))
(mapc
(lambda (bibfile)
(unless (with-current-buffer
(find-file-noselect bibfile)
(bibtex-validate))
(cl-pushnew
(format "Invalid bibtex file found. [[file:%s]]\n" bibfile)
bib-candidates)))
bibfiles)
;; check types
(mapc
(lambda (bibfile)
(with-current-buffer
(find-file-noselect bibfile)
(goto-char (point-min))
(while (re-search-forward "^@\\(.*?\\)[({]" nil t)
(when (and (not (string= "string" (downcase (match-string-no-properties 1))))
(not (member (s-trim (downcase (match-string-no-properties 1)))
(cdr (assoc bibtex-dialect
(list
(cons 'BibTeX (mapcar (lambda (e) (downcase (car e)))
bibtex-BibTeX-entry-alist))
(cons 'biblatex (mapcar (lambda (e) (downcase (car e)))
bibtex-biblatex-entry-alist))))))))
(cl-pushnew
(format "Invalid bibtex entry type (%s) found in [[file:%s::%s]]\n" (match-string-no-properties 1)
bibfile (line-number-at-pos))
bib-candidates)))))
bibfiles))
;; unreferenced labels
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(let ((matches '()))
;; these are the org-ref label:stuff kinds
(while (re-search-forward
"[^#+]label:\\([a-zA-Z0-9:-]*\\)" nil t)
(cl-pushnew (cons
(match-string-no-properties 1)
(point))
matches))
;; now add all the other kinds of labels.
;; #+label:
(save-excursion
(goto-char (point-min))
(while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" nil t)
;; do not do this for tables. We get those in `org-ref-get-tblnames'.
;; who would have thought you have save match data here? Trust me. When
;; I wrote this, you did.
(unless (save-match-data (equal (car (org-element-at-point)) 'table))
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches))))
;; \label{}
(save-excursion
(goto-char (point-min))
(while (re-search-forward "\\\\label{\\([a-zA-Z0-9:-]*\\)}"
nil t)
(cl-pushnew (cons (match-string-no-properties 1) (point)) matches)))
;; #+tblname: and actually #+label
(cl-loop for cell in (org-element-map (org-element-parse-buffer 'element) 'table
(lambda (table)
(cons (org-element-property :name table)
(org-element-property :begin table))))
do
(cl-pushnew cell matches))
;; CUSTOM_IDs
(org-map-entries
(lambda ()
(let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
(when (not (null custom_id))
(cl-pushnew (cons custom_id (point)) matches)))))
(goto-char (point-min))
(while (re-search-forward "^#\\+name:\\s-+\\(.*\\)" nil t)
(cl-pushnew (cons (match-string 1) (point)) matches))
;; unreference labels
(let ((refs (org-element-map (org-element-parse-buffer) 'link
(lambda (el)
(when (or (string= "ref" (org-element-property :type el))
(string= "eqref" (org-element-property :type el))
(string= "pageref" (org-element-property :type el))
(string= "nameref" (org-element-property :type el))
(string= "autoref" (org-element-property :type el))
(string= "cref" (org-element-property :type el))
(string= "Cref" (org-element-property :type el)))
(org-element-property :path el))))))
(cl-loop for (label . p) in matches
do
(when (and label (not (-contains? refs label)))
(cl-pushnew
(cons label (set-marker (make-marker) p))
unreferenced-labels)))))))
(with-current-buffer buf
(when bad-citations
(insert "\n* Bad citations\n")
(cl-loop for (key . marker) in bad-citations
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-refs
(insert "\n* Bad ref links\n")
(cl-loop for (key . marker) in bad-refs
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bad-labels
(insert "\n* Multiply defined label links\n")
(cl-loop for (key . marker) in bad-labels
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when unreferenced-labels
(insert "\n* Unreferenced label links\n")
(cl-loop for (key . marker) in unreferenced-labels
when (not (string= key ""))
do
(setq mbuffer (buffer-name (marker-buffer marker))
mchar (marker-position marker))
(insert (format "- [[elisp:(progn (switch-to-buffer %S) (goto-char %S)(org-show-entry))][%s]]\n"
mbuffer mchar key))))
(when bib-candidates
(insert "\n* Bibliography\n")
(cl-loop for candidate in bib-candidates
do
(insert (format "- %s" candidate))))
(insert "\n* Miscellaneous\n")
(cl-loop for s in `(,(format "org-latex-prefer-user-labels = %s"
org-latex-prefer-user-labels)
,(format "bibtex-dialect = %s" bibtex-dialect)
,(format "biblatex is%srequired." (if biblatex-required " " " not "))
,(format "biblatex is%sused." (if biblatex-used " " " not "))
,(format "emacs-version = %s" (emacs-version))
,(format "org-version = %s" (org-version))
,(org-ref-version)
,(format "org-ref.el installed at %s" (concat
(file-name-sans-extension
(locate-library "org-ref"))
".el"))
,(format "completion backend = %s" org-ref-completion-library)
,(format "org-ref-insert-cite-function = %s" org-ref-insert-cite-function)
,(format "org-ref-insert-label-function = %s" org-ref-insert-label-function)
,(format "org-ref-insert-ref-function = %s" org-ref-insert-ref-function)
,(format "org-ref-cite-onclick-function = %s" org-ref-cite-onclick-function)
,(format "org-ref-default-bibliography = %S" org-ref-default-bibliography)
,(format "org-ref-default-bibliography is a list = %S" (listp org-ref-default-bibliography))
,(format "org-latex-pdf-process is defined as %s" org-latex-pdf-process)
,(format "natbib is%srequired." (if natbib-required " " " not "))
,(format "natbib is%sin %s or %s."
(if natbib-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "cleveref is%srequired." (if cleveref-required " " " not "))
,(format "cleveref is%sin %s or %s."
(if cleveref-used " " " not ")
(propertize "org-latex-default-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-default-packages-alist
"\n"))
'font-lock-face '(:foreground "red3"))
(propertize "org-latex-packages-alist"
'help-echo (format "%S" (mapconcat
(lambda (s)
(format "%s" s))
org-latex-packages-alist
"\n"))
'font-lock-face '(:foreground "red3")))
,(format "bibtex-completion installed = %s" (featurep 'bibtex-completion))
,(format "bibtex-completion loaded = %s" (fboundp 'bibtex-completion-candidates)))
do
(insert "- " s "\n"))
(insert (format "- org-latex-default-packages-alist\n"))
(cl-loop for el in org-latex-default-packages-alist
do
(insert (format " %S\n" el)))
(if (null org-latex-packages-alist)
(insert "- org-latex-packages-alist is nil\n")
(insert "- org-latex-packages-alist\n")
(cl-loop for el in org-latex-packages-alist
do
(insert (format " %S\n" el))))
(insert (format "- ox-bibtex loaded = %s\n" (featurep 'ox-bibtex)))
(insert (format "- ox-bibtex loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ox-bibtex-i (seq-position load-history (assoc (locate-library "ox-bibtex") load-history))))
(and org-ref-i ox-bibtex-i
(> org-ref-i ox-bibtex-i)))))
(insert (format "- ebib loaded = %s\n" (featurep 'ebib)))
(insert (format "- ebib loaded after org-ref = %s\n"
(let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) )
(ebib-i (seq-position load-history (assoc (locate-library "ebib") load-history))))
(and org-ref-i ebib-i
(> org-ref-i ebib-i)))))
(insert "- cite link definition:\n" (with-temp-buffer
(insert (format "%S" (assoc "cite" org-link-parameters)))
(pp-buffer)
(buffer-string)))
(insert "\n* LaTeX setup\n\n")
(cl-loop for executable in '("latex" "pdflatex" "bibtex" "biblatex"
"makeindex" "makeglossaries")
do
(insert (format "%s is installed at %s\n" executable (executable-find executable))))
(insert "\n* Warnings\n")
(if (get-buffer "*Warnings*")
(cl-loop for line in (s-split "\n" (with-current-buffer "*Warnings*"
(buffer-string)))
if (s-starts-with? "Warning (org-ref):" line)
do
(insert " - " line "\n"))
(insert "- No (org-ref) Warnings found."))
(insert (format "\n* Utilities
- [[elisp:(progn (find-file %S) (ispell))][Spell check document]]
- [[elisp:(progn (find-file %S) (org-ref))][recheck document with org-ref]]
" fname fname))
(goto-char (point-min))
;; (setq header-line-format "Press q to quit.")
;; (local-set-key "q"
;; #'(lambda ()
;; (interactive)
;; (delete-window)))
(read-only-mode))
(display-buffer-in-side-window buf '((side . right)))))
(provide 'org-ref-utils)
;;; org-ref-utils.el ends here
|
[
{
"context": "012-2014 Free Software Foundation, Inc.\n;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>\n;; Keyword",
"end": 151,
"score": 0.9999042749404907,
"start": 131,
"tag": "NAME",
"value": "Jonathan Leech-Pepin"
},
{
"context": "Foundation, Inc.\n;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>\n;; Keywords: ou",
"end": 156,
"score": 0.7290096282958984,
"start": 153,
"tag": "EMAIL",
"value": "jon"
}
] | elpa/org-20140303/ox-texinfo.el | larifari/emacsd | 0 | ;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine
;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
;; Author: Jonathan Leech-Pepin <jonathan.leechpepin at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This library implements a Texinfo back-end for Org generic
;; exporter.
;;
;; To test it, run
;;
;; M-: (org-export-to-buffer 'texinfo "*Test Texinfo*") RET
;;
;; in an Org mode buffer then switch to the buffer to see the Texinfo
;; export. See ox.el for more details on how this exporter works.
;;
;; It introduces nine new buffer keywords: "TEXINFO_CLASS",
;; "TEXINFO_FILENAME", "TEXINFO_HEADER", "TEXINFO_POST_HEADER",
;; "TEXINFO_DIR_CATEGORY", "TEXINFO_DIR_TITLE", "TEXINFO_DIR_DESC"
;; "SUBTITLE" and "SUBAUTHOR".
;;
;; It introduces 1 new headline property keywords:
;; "TEXINFO_MENU_TITLE" for optional menu titles.
;;
;; To include inline code snippets (for example for generating @kbd{}
;; and @key{} commands), the following export-snippet keys are
;; accepted:
;;
;; texinfo
;; info
;;
;; You can add them for export snippets via any of the below:
;;
;; (add-to-list 'org-export-snippet-translation-alist
;; '("info" . "texinfo"))
;;
;;; Code:
(eval-when-compile (require 'cl))
(require 'ox)
(defvar orgtbl-exp-regexp)
;;; Define Back-End
(org-export-define-backend 'texinfo
'((bold . org-texinfo-bold)
(center-block . org-texinfo-center-block)
(clock . org-texinfo-clock)
(code . org-texinfo-code)
(comment . org-texinfo-comment)
(comment-block . org-texinfo-comment-block)
(drawer . org-texinfo-drawer)
(dynamic-block . org-texinfo-dynamic-block)
(entity . org-texinfo-entity)
(example-block . org-texinfo-example-block)
(export-block . org-texinfo-export-block)
(export-snippet . org-texinfo-export-snippet)
(fixed-width . org-texinfo-fixed-width)
(footnote-definition . org-texinfo-footnote-definition)
(footnote-reference . org-texinfo-footnote-reference)
(headline . org-texinfo-headline)
(inline-src-block . org-texinfo-inline-src-block)
(inlinetask . org-texinfo-inlinetask)
(italic . org-texinfo-italic)
(item . org-texinfo-item)
(keyword . org-texinfo-keyword)
(line-break . org-texinfo-line-break)
(link . org-texinfo-link)
(paragraph . org-texinfo-paragraph)
(plain-list . org-texinfo-plain-list)
(plain-text . org-texinfo-plain-text)
(planning . org-texinfo-planning)
(property-drawer . org-texinfo-property-drawer)
(quote-block . org-texinfo-quote-block)
(quote-section . org-texinfo-quote-section)
(radio-target . org-texinfo-radio-target)
(section . org-texinfo-section)
(special-block . org-texinfo-special-block)
(src-block . org-texinfo-src-block)
(statistics-cookie . org-texinfo-statistics-cookie)
(subscript . org-texinfo-subscript)
(superscript . org-texinfo-superscript)
(table . org-texinfo-table)
(table-cell . org-texinfo-table-cell)
(table-row . org-texinfo-table-row)
(target . org-texinfo-target)
(template . org-texinfo-template)
(timestamp . org-texinfo-timestamp)
(verbatim . org-texinfo-verbatim)
(verse-block . org-texinfo-verse-block))
:export-block "TEXINFO"
:filters-alist
'((:filter-headline . org-texinfo-filter-section-blank-lines)
(:filter-section . org-texinfo-filter-section-blank-lines))
:menu-entry
'(?i "Export to Texinfo"
((?t "As TEXI file" org-texinfo-export-to-texinfo)
(?i "As INFO file" org-texinfo-export-to-info)))
:options-alist
'((:texinfo-filename "TEXINFO_FILENAME" nil org-texinfo-filename t)
(:texinfo-class "TEXINFO_CLASS" nil org-texinfo-default-class t)
(:texinfo-header "TEXINFO_HEADER" nil nil newline)
(:texinfo-post-header "TEXINFO_POST_HEADER" nil nil newline)
(:subtitle "SUBTITLE" nil nil newline)
(:subauthor "SUBAUTHOR" nil nil newline)
(:texinfo-dircat "TEXINFO_DIR_CATEGORY" nil nil t)
(:texinfo-dirtitle "TEXINFO_DIR_TITLE" nil nil t)
(:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)))
;;; User Configurable Variables
(defgroup org-export-texinfo nil
"Options for exporting Org mode files to Texinfo."
:tag "Org Export Texinfo"
:version "24.4"
:package-version '(Org . "8.0")
:group 'org-export)
;;; Preamble
(defcustom org-texinfo-filename ""
"Default filename for Texinfo output."
:group 'org-export-texinfo
:type '(string :tag "Export Filename"))
(defcustom org-texinfo-coding-system nil
"Default document encoding for Texinfo output.
If `nil' it will default to `buffer-file-coding-system'."
:group 'org-export-texinfo
:type 'coding-system)
(defcustom org-texinfo-default-class "info"
"The default Texinfo class."
:group 'org-export-texinfo
:type '(string :tag "Texinfo class"))
(defcustom org-texinfo-classes
'(("info"
"\\input texinfo @c -*- texinfo -*-"
("@chapter %s" . "@unnumbered %s")
("@section %s" . "@unnumberedsec %s")
("@subsection %s" . "@unnumberedsubsec %s")
("@subsubsection %s" . "@unnumberedsubsubsec %s")))
"Alist of Texinfo classes and associated header and structure.
If #+Texinfo_CLASS is set in the buffer, use its value and the
associated information. Here is the structure of each cell:
\(class-name
header-string
\(numbered-section . unnumbered-section\)
...\)
The sectioning structure
------------------------
The sectioning structure of the class is given by the elements
following the header string. For each sectioning level, a number
of strings is specified. A %s formatter is mandatory in each
section string and will be replaced by the title of the section.
Instead of a list of sectioning commands, you can also specify
a function name. That function will be called with two
parameters, the \(reduced) level of the headline, and a predicate
non-nil when the headline should be numbered. It must return
a format string in which the section title will be added."
:group 'org-export-texinfo
:type '(repeat
(list (string :tag "Texinfo class")
(string :tag "Texinfo header")
(repeat :tag "Levels" :inline t
(choice
(cons :tag "Heading"
(string :tag " numbered")
(string :tag "unnumbered"))
(function :tag "Hook computing sectioning"))))))
;;; Headline
(defcustom org-texinfo-format-headline-function 'ignore
"Function to format headline text.
This function will be called with 5 arguments:
TODO the todo keyword (string or nil).
TODO-TYPE the type of todo (symbol: `todo', `done', nil)
PRIORITY the priority of the headline (integer or nil)
TEXT the main headline text (string).
TAGS the tags as a list of strings (list of strings or nil).
The function result will be used in the section format string.
As an example, one could set the variable to the following, in
order to reproduce the default set-up:
\(defun org-texinfo-format-headline (todo todo-type priority text tags)
\"Default format function for a headline.\"
\(concat (when todo
\(format \"\\\\textbf{\\\\textsc{\\\\textsf{%s}}} \" todo))
\(when priority
\(format \"\\\\framebox{\\\\#%c} \" priority))
text
\(when tags
\(format \"\\\\hfill{}\\\\textsc{%s}\"
\(mapconcat 'identity tags \":\"))))"
:group 'org-export-texinfo
:type 'function)
;;; Node listing (menu)
(defcustom org-texinfo-node-description-column 32
"Column at which to start the description in the node
listings.
If a node title is greater than this length, the description will
be placed after the end of the title."
:group 'org-export-texinfo
:type 'integer)
;;; Footnotes
;;
;; Footnotes are inserted directly
;;; Timestamps
(defcustom org-texinfo-active-timestamp-format "@emph{%s}"
"A printf format string to be applied to active timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-inactive-timestamp-format "@emph{%s}"
"A printf format string to be applied to inactive timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-diary-timestamp-format "@emph{%s}"
"A printf format string to be applied to diary timestamps."
:group 'org-export-texinfo
:type 'string)
;;; Links
(defcustom org-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
"Format string for links with unknown path type."
:group 'org-export-texinfo
:type 'string)
;;; Tables
(defcustom org-texinfo-tables-verbatim nil
"When non-nil, tables are exported verbatim."
:group 'org-export-texinfo
:type 'boolean)
(defcustom org-texinfo-table-scientific-notation "%s\\,(%s)"
"Format string to display numbers in scientific notation.
The format should have \"%s\" twice, for mantissa and exponent
\(i.e. \"%s\\\\times10^{%s}\").
When nil, no transformation is made."
:group 'org-export-texinfo
:type '(choice
(string :tag "Format string")
(const :tag "No formatting")))
(defcustom org-texinfo-def-table-markup "@samp"
"Default setting for @table environments."
:group 'org-export-texinfo
:type 'string)
;;; Text markup
(defcustom org-texinfo-text-markup-alist '((bold . "@strong{%s}")
(code . code)
(italic . "@emph{%s}")
(verbatim . verb)
(comment . "@c %s"))
"Alist of Texinfo expressions to convert text markup.
The key must be a symbol among `bold', `italic' and `comment'.
The value is a formatting string to wrap fontified text with.
Value can also be set to the following symbols: `verb' and
`code'. For the former, Org will use \"@verb\" to
create a format string and select a delimiter character that
isn't in the string. For the latter, Org will use \"@code\"
to typeset and try to protect special characters.
If no association can be found for a given markup, text will be
returned as-is."
:group 'org-export-texinfo
:type 'alist
:options '(bold code italic verbatim comment))
;;; Drawers
(defcustom org-texinfo-format-drawer-function
(lambda (name contents) contents)
"Function called to format a drawer in Texinfo code.
The function must accept two parameters:
NAME the drawer name, like \"LOGBOOK\"
CONTENTS the contents of the drawer.
The function should return the string to be exported.
The default function simply returns the value of CONTENTS."
:group 'org-export-texinfo
:version "24.4"
:package-version '(Org . "8.3")
:type 'function)
;;; Inlinetasks
(defcustom org-texinfo-format-inlinetask-function 'ignore
"Function called to format an inlinetask in Texinfo code.
The function must accept six parameters:
TODO the todo keyword, as a string
TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
PRIORITY the inlinetask priority, as a string
NAME the inlinetask name, as a string.
TAGS the inlinetask tags, as a list of strings.
CONTENTS the contents of the inlinetask, as a string.
The function should return the string to be exported.
For example, the variable could be set to the following function
in order to mimic default behavior:
\(defun org-texinfo-format-inlinetask \(todo type priority name tags contents\)
\"Format an inline task element for Texinfo export.\"
\(let ((full-title
\(concat
\(when todo
\(format \"@strong{%s} \" todo))
\(when priority (format \"#%c \" priority))
title
\(when tags
\(format \":%s:\"
\(mapconcat 'identity tags \":\")))))
\(format (concat \"@center %s\n\n\"
\"%s\"
\"\n\"))
full-title contents))"
:group 'org-export-texinfo
:type 'function)
;;; Src blocks
;;
;; Src Blocks are example blocks, except for LISP
;;; Compilation
(defcustom org-texinfo-info-process
'("makeinfo %f")
"Commands to process a Texinfo file to an INFO file.
This is list of strings, each of them will be given to the shell
as a command. %f in the command will be replaced by the full
file name, %b by the file base name \(i.e without extension) and
%o by the base directory of the file."
:group 'org-export-texinfo
:type '(repeat :tag "Shell command sequence"
(string :tag "Shell command")))
(defcustom org-texinfo-logfiles-extensions
'("aux" "toc" "cp" "fn" "ky" "pg" "tp" "vr")
"The list of file extensions to consider as Texinfo logfiles.
The logfiles will be remove if `org-texinfo-remove-logfiles' is
non-nil."
:group 'org-export-texinfo
:type '(repeat (string :tag "Extension")))
(defcustom org-texinfo-remove-logfiles t
"Non-nil means remove the logfiles produced by compiling a Texinfo file.
By default, logfiles are files with these extensions: .aux, .toc,
.cp, .fn, .ky, .pg and .tp. To define the set of logfiles to remove,
set `org-texinfo-logfiles-extensions'."
:group 'org-export-latex
:type 'boolean)
;;; Constants
(defconst org-texinfo-max-toc-depth 4
"Maximum depth for creation of detailed menu listings. Beyond
this depth Texinfo will not recognize the nodes and will cause
errors. Left as a constant in case this value ever changes.")
(defconst org-texinfo-supported-coding-systems
'("US-ASCII" "UTF-8" "ISO-8859-15" "ISO-8859-1" "ISO-8859-2" "koi8-r" "koi8-u")
"List of coding systems supported by Texinfo, as strings.
Specified coding system will be matched against these strings.
If two strings share the same prefix (e.g. \"ISO-8859-1\" and
\"ISO-8859-15\"), the most specific one has to be listed first.")
;;; Internal Functions
(defun org-texinfo-filter-section-blank-lines (headline back-end info)
"Filter controlling number of blank lines after a section."
(let ((blanks (make-string 2 ?\n)))
(replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" blanks headline)))
(defun org-texinfo--find-verb-separator (s)
"Return a character not used in string S.
This is used to choose a separator for constructs like \\verb."
(let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
(loop for c across ll
when (not (string-match (regexp-quote (char-to-string c)) s))
return (char-to-string c))))
(defun org-texinfo--make-option-string (options)
"Return a comma separated string of keywords and values.
OPTIONS is an alist where the key is the options keyword as
a string, and the value a list containing the keyword value, or
nil."
(mapconcat (lambda (pair)
(concat (first pair)
(when (> (length (second pair)) 0)
(concat "=" (second pair)))))
options
","))
(defun org-texinfo--text-markup (text markup)
"Format TEXT depending on MARKUP text markup.
See `org-texinfo-text-markup-alist' for details."
(let ((fmt (cdr (assq markup org-texinfo-text-markup-alist))))
(cond
;; No format string: Return raw text.
((not fmt) text)
((eq 'verb fmt)
(let ((separator (org-texinfo--find-verb-separator text)))
(concat "@verb{" separator text separator "}")))
((eq 'code fmt)
(let ((start 0)
(rtn "")
char)
(while (string-match "[@{}]" text)
(setq char (match-string 0 text))
(if (> (match-beginning 0) 0)
(setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
(setq text (substring text (1+ (match-beginning 0))))
(setq char (concat "@" char)
rtn (concat rtn char)))
(setq text (concat rtn text)
fmt "@code{%s}")
(format fmt text)))
;; Else use format string.
(t (format fmt text)))))
(defun org-texinfo--get-node (headline info)
"Return node entry associated to HEADLINE.
INFO is a plist used as a communication channel."
(let ((menu-title (org-export-get-alt-title headline info)))
(org-texinfo--sanitize-menu
(replace-regexp-in-string
"%" "%%"
(if menu-title (org-export-data menu-title info)
(org-texinfo--sanitize-headline
(org-element-property :title headline) info))))))
;;; Headline sanitizing
(defun org-texinfo--sanitize-headline (headline info)
"Remove all formatting from the text of a headline for use in
node and menu listing."
(mapconcat 'identity
(org-texinfo--sanitize-headline-contents headline info) " "))
(defun org-texinfo--sanitize-headline-contents (headline info)
"Retrieve the content of the headline.
Any content that can contain further formatting is checked
recursively, to ensure that nested content is also properly
retrieved."
(loop for contents in headline append
(cond
;; already a string
((stringp contents)
(list (replace-regexp-in-string " $" "" contents)))
;; Is exported as-is (value)
((org-element-map contents '(verbatim code)
(lambda (value) (org-element-property :value value)) info))
;; Has content and recurse into the content
((org-element-contents contents)
(org-texinfo--sanitize-headline-contents
(org-element-contents contents) info)))))
;;; Menu sanitizing
(defun org-texinfo--sanitize-menu (title)
"Remove invalid characters from TITLE for use in menus and
nodes.
Based on Texinfo specifications, the following must be removed:
@ { } ( ) : . ,"
(replace-regexp-in-string "[@{}():,.]" "" title))
;;; Content sanitizing
(defun org-texinfo--sanitize-content (text)
"Ensure characters are properly escaped when used in headlines or blocks.
Escape characters are: @ { }"
(replace-regexp-in-string "\\\([@{}]\\\)" "@\\1" text))
;;; Menu creation
(defun org-texinfo--build-menu (tree level info &optional detailed)
"Create the @menu/@end menu information from TREE at headline
level LEVEL.
TREE contains the parse-tree to work with, either of the entire
document or of a specific parent headline. LEVEL indicates what
level of headlines to look at when generating the menu. INFO is
a plist containing contextual information.
Detailed determines whether to build a single level of menu, or
recurse into all children as well."
(let ((menu (org-texinfo--generate-menu-list tree level info))
output text-menu)
(cond
(detailed
;; Looping is done within the menu generation.
(setq text-menu (org-texinfo--generate-detailed menu level info)))
(t
(setq text-menu (org-texinfo--generate-menu-items menu info))))
(when text-menu
(setq output (org-texinfo--format-menu text-menu))
(mapconcat 'identity output "\n"))))
(defun org-texinfo--generate-detailed (menu level info)
"Generate a detailed listing of all subheadings within MENU starting at LEVEL.
MENU is the parse-tree to work with. LEVEL is the starting level
for the menu headlines and from which recursion occurs. INFO is
a plist containing contextual information."
(when level
(let ((max-depth (min org-texinfo-max-toc-depth
(plist-get info :headline-levels))))
(when (> max-depth level)
(loop for headline in menu append
(let* ((title (org-texinfo--menu-headlines headline info))
;; Create list of menu entries for the next level
(sublist (org-texinfo--generate-menu-list
headline (1+ level) info))
;; Generate the menu items for that level. If
;; there are none omit that heading completely,
;; otherwise join the title to it's related entries.
(submenu (if (org-texinfo--generate-menu-items sublist info)
(append (list title)
(org-texinfo--generate-menu-items sublist info))
'nil))
;; Start the process over the next level down.
(recursion (org-texinfo--generate-detailed sublist (1+ level) info)))
(setq recursion (append submenu recursion))
recursion))))))
(defun org-texinfo--generate-menu-list (tree level info)
"Generate the list of headlines that are within a given level
of the tree for further formatting.
TREE is the parse-tree containing the headlines. LEVEL is the
headline level to generate a list of. INFO is a plist holding
contextual information."
(org-element-map tree 'headline
(lambda (head)
(and (= (org-export-get-relative-level head info) level)
;; Do not take note of footnotes or copying headlines.
(not (org-element-property :COPYING head))
(not (org-element-property :footnote-section-p head))
;; Collect headline.
head))
info))
(defun org-texinfo--generate-menu-items (items info)
"Generate a list of headline information from the listing ITEMS.
ITEMS is a list of the headlines to be converted into entries.
INFO is a plist containing contextual information.
Returns a list containing the following information from each
headline: length, title, description. This is used to format the
menu using `org-texinfo--format-menu'."
(loop for headline in items collect
(let* ((menu-title (org-texinfo--sanitize-menu
(org-export-data
(org-export-get-alt-title headline info)
info)))
(title (org-texinfo--sanitize-menu
(org-texinfo--sanitize-headline
(org-element-property :title headline) info)))
(descr (org-export-data
(org-element-property :DESCRIPTION headline)
info))
(menu-entry (if (string= "" menu-title) title menu-title))
(len (length menu-entry))
(output (list len menu-entry descr)))
output)))
(defun org-texinfo--menu-headlines (headline info)
"Retrieve the title from HEADLINE.
INFO is a plist holding contextual information.
Return the headline as a list of (length title description) with
length of -1 and nil description. This is used in
`org-texinfo--format-menu' to identify headlines as opposed to
entries."
(let ((title (org-export-data
(org-element-property :title headline) info)))
(list -1 title 'nil)))
(defun org-texinfo--format-menu (text-menu)
"Format the TEXT-MENU items to be properly printed in the menu.
Each entry in the menu should be provided as (length title
description).
Headlines in the detailed menu are given length -1 to ensure they
are never confused with other entries. They also have no
description.
Other menu items are output as:
Title:: description
With the spacing between :: and description based on the length
of the longest menu entry."
(let (output)
(setq output
(mapcar (lambda (name)
(let* ((title (nth 1 name))
(desc (nth 2 name))
(length (nth 0 name))
(column (max
;;6 is "* " ":: " for inserted text
length
(-
org-texinfo-node-description-column
6)))
(spacing (- column length)
))
(if (> length -1)
(concat "* " title ":: "
(make-string spacing ?\s)
(if desc
(concat desc)))
(concat "\n" title "\n"))))
text-menu))
output))
;;; Template
(defun org-texinfo-template (contents info)
"Return complete document string after Texinfo conversion.
CONTENTS is the transcoded contents string. INFO is a plist
holding export options."
(let* ((title (org-export-data (plist-get info :title) info))
(info-filename (or (plist-get info :texinfo-filename)
(file-name-nondirectory
(org-export-output-file-name ".info"))))
(author (org-export-data (plist-get info :author) info))
(lang (org-export-data (plist-get info :language) info))
(texinfo-header (plist-get info :texinfo-header))
(texinfo-post-header (plist-get info :texinfo-post-header))
(subtitle (plist-get info :subtitle))
(subauthor (plist-get info :subauthor))
(class (plist-get info :texinfo-class))
(header (nth 1 (assoc class org-texinfo-classes)))
(copying
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (hl) (and (org-element-property :COPYING hl) hl)) info t))
(dircat (plist-get info :texinfo-dircat))
(dirtitle (plist-get info :texinfo-dirtitle))
(dirdesc (plist-get info :texinfo-dirdesc))
;; Spacing to align description (column 32 - 3 for `* ' and
;; `.' in text.
(dirspacing (- 29 (length dirtitle)))
(menu (org-texinfo-make-menu info 'main))
(detail-menu (org-texinfo-make-menu info 'detailed)))
(concat
;; Header
header "\n"
"@c %**start of header\n"
;; Filename and Title
"@setfilename " info-filename "\n"
"@settitle " title "\n"
;; Coding system.
(format
"@documentencoding %s\n"
(catch 'coding-system
(let ((case-fold-search t)
(name (symbol-name (or org-texinfo-coding-system
buffer-file-coding-system))))
(dolist (system org-texinfo-supported-coding-systems "UTF-8")
(when (org-string-match-p (regexp-quote system) name)
(throw 'coding-system system))))))
"\n"
(format "@documentlanguage %s\n" lang)
"\n\n"
"@c Version and Contact Info\n"
"@set AUTHOR " author "\n"
;; Additional Header Options set by `#+TEXINFO_HEADER
(if texinfo-header
(concat "\n"
texinfo-header
"\n"))
"@c %**end of header\n"
"@finalout\n"
"\n\n"
;; Additional Header Options set by #+TEXINFO_POST_HEADER
(if texinfo-post-header
(concat "\n"
texinfo-post-header
"\n"))
;; Copying
"@copying\n"
;; Only export the content of the headline, do not need the
;; initial headline.
(org-export-data (nth 2 copying) info)
"@end copying\n"
"\n\n"
;; Info directory information
;; Only supply if both title and category are provided
(if (and dircat dirtitle)
(concat "@dircategory " dircat "\n"
"@direntry\n"
"* " dirtitle "."
(make-string dirspacing ?\s)
dirdesc "\n"
"@end direntry\n"))
"\n\n"
;; Title
"@titlepage\n"
"@title " title "\n\n"
(if subtitle
(concat "@subtitle " subtitle "\n"))
"@author " author "\n"
(if subauthor
(concat subauthor "\n"))
"\n"
"@c The following two commands start the copyright page.\n"
"@page\n"
"@vskip 0pt plus 1filll\n"
"@insertcopying\n"
"@end titlepage\n\n"
"@c Output the table of contents at the beginning.\n"
"@contents\n\n"
;; Configure Top Node when not for Tex
"@ifnottex\n"
"@node Top\n"
"@top " title " Manual\n"
"@insertcopying\n"
"@end ifnottex\n\n"
;; Do not output menus if they are empty
(if menu
;; Menu
(concat "@menu\n"
menu
"\n\n"
;; Detailed Menu
(if detail-menu
(concat "@detailmenu\n"
" --- The Detailed Node Listing ---\n"
detail-menu
"\n\n"
"@end detailmenu\n"))
"@end menu\n"))
"\n\n"
;; Document's body.
contents
"\n"
;; Creator.
(let ((creator-info (plist-get info :with-creator)))
(cond
((not creator-info) "")
((eq creator-info 'comment)
(format "@c %s\n" (plist-get info :creator)))
(t (concat (plist-get info :creator) "\n"))))
;; Document end.
"\n@bye")))
;;; Transcode Functions
;;; Bold
(defun org-texinfo-bold (bold contents info)
"Transcode BOLD from Org to Texinfo.
CONTENTS is the text with bold markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'bold))
;;; Center Block
(defun org-texinfo-center-block (center-block contents info)
"Transcode a CENTER-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Clock
(defun org-texinfo-clock (clock contents info)
"Transcode a CLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(format "@strong{%s} " org-clock-string)
(format org-texinfo-inactive-timestamp-format
(concat (org-translate-time
(org-element-property :raw-value
(org-element-property :value clock)))
(let ((time (org-element-property :duration clock)))
(and time (format " (%s)" time)))))
"@*"))
;;; Code
(defun org-texinfo-code (code contents info)
"Transcode a CODE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value code) 'code))
;;; Comment
(defun org-texinfo-comment (comment contents info)
"Transcode a COMMENT object from Org to Texinfo.
CONTENTS is the text in the comment. INFO is a plist holding
contextual information."
(org-texinfo--text-markup (org-element-property :value comment) 'comment))
;;; Comment Block
(defun org-texinfo-comment-block (comment-block contents info)
"Transcode a COMMENT-BLOCK object from Org to Texinfo.
CONTENTS is the text within the block. INFO is a plist holding
contextual information."
(format "@ignore\n%s@end ignore" (org-element-property :value comment-block)))
;;; Drawer
(defun org-texinfo-drawer (drawer contents info)
"Transcode a DRAWER element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((name (org-element-property :drawer-name drawer))
(output (funcall org-texinfo-format-drawer-function
name contents)))
output))
;;; Dynamic Block
(defun org-texinfo-dynamic-block (dynamic-block contents info)
"Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information. See `org-export-data'."
contents)
;;; Entity
(defun org-texinfo-entity (entity contents info)
"Transcode an ENTITY object from Org to Texinfo.
CONTENTS are the definition itself. INFO is a plist holding
contextual information."
(let ((ent (org-element-property :latex entity)))
(if (org-element-property :latex-math-p entity) (format "@math{%s}" ent) ent)))
;;; Example Block
(defun org-texinfo-example-block (example-block contents info)
"Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@verbatim\n%s@end verbatim"
(org-export-format-code-default example-block info)))
;;; Export Block
(defun org-texinfo-export-block (export-block contents info)
"Transcode a EXPORT-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (string= (org-element-property :type export-block) "TEXINFO")
(org-remove-indentation (org-element-property :value export-block))))
;;; Export Snippet
(defun org-texinfo-export-snippet (export-snippet contents info)
"Transcode a EXPORT-SNIPPET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (eq (org-export-snippet-backend export-snippet) 'texinfo)
(org-element-property :value export-snippet)))
;;; Fixed Width
(defun org-texinfo-fixed-width (fixed-width contents info)
"Transcode a FIXED-WIDTH element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(format "@example\n%s\n@end example"
(org-remove-indentation
(org-texinfo--sanitize-content
(org-element-property :value fixed-width)))))
;;; Footnote Reference
;;
(defun org-texinfo-footnote-reference (footnote contents info)
"Create a footnote reference for FOOTNOTE.
FOOTNOTE is the footnote to define. CONTENTS is nil. INFO is a
plist holding contextual information."
(let ((def (org-export-get-footnote-definition footnote info)))
(format "@footnote{%s}"
(org-trim (org-export-data def info)))))
;;; Headline
(defun org-texinfo-headline (headline contents info)
"Transcode a HEADLINE element from Org to Texinfo.
CONTENTS holds the contents of the headline. INFO is a plist
holding contextual information."
(let* ((class (plist-get info :texinfo-class))
(level (org-export-get-relative-level headline info))
(numberedp (org-export-numbered-headline-p headline info))
(class-sectioning (assoc class org-texinfo-classes))
;; Find the index type, if any
(index (org-element-property :INDEX headline))
;; Check if it is an appendix
(appendix (org-element-property :APPENDIX headline))
;; Retrieve headline text
(text (org-texinfo--sanitize-headline
(org-element-property :title headline) info))
;; Create node info, to insert it before section formatting.
;; Use custom menu title if present
(node (format "@node %s\n" (org-texinfo--get-node headline info)))
;; Menus must be generated with first child, otherwise they
;; will not nest properly
(menu (let* ((first (org-export-first-sibling-p headline info))
(parent (org-export-get-parent-headline headline))
(title (org-texinfo--sanitize-headline
(org-element-property :title parent) info))
heading listing
(tree (plist-get info :parse-tree)))
(if first
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (ref)
(if (member title (org-element-property :title ref))
(push ref heading)))
info t))
(setq listing (org-texinfo--build-menu
(car heading) level info))
(if listing
(setq listing (replace-regexp-in-string
"%" "%%" listing)
listing (format
"\n@menu\n%s\n@end menu\n\n" listing))
'nil)))
;; Section formatting will set two placeholders: one for the
;; title and the other for the contents.
(section-fmt
(let ((sec (if (and (symbolp (nth 2 class-sectioning))
(fboundp (nth 2 class-sectioning)))
(funcall (nth 2 class-sectioning) level numberedp)
(nth (1+ level) class-sectioning))))
(cond
;; No section available for that LEVEL.
((not sec) nil)
;; Section format directly returned by a function.
((stringp sec) sec)
;; (numbered-section . unnumbered-section)
((not (consp (cdr sec)))
(cond
;;If an index, always unnumbered
(index
(concat menu node (cdr sec) "\n%s"))
(appendix
(concat menu node (replace-regexp-in-string
"unnumbered"
"appendix"
(cdr sec)) "\n%s"))
;; Otherwise number as needed.
(t
(concat menu node
(funcall
(if numberedp #'car #'cdr) sec) "\n%s")))))))
(todo
(and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword headline)))
(and todo (org-export-data todo info)))))
(todo-type (and todo (org-element-property :todo-type headline)))
(tags (and (plist-get info :with-tags)
(org-export-get-tags headline info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority headline)))
;; Create the headline text along with a no-tag version. The
;; latter is required to remove tags from table of contents.
(full-text (org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text tags)
;; Default formatting.
(concat
(when todo
(format "@strong{%s} " todo))
(when priority (format "@emph{#%s} " priority))
text
(when tags
(format " :%s:"
(mapconcat 'identity tags ":")))))))
(full-text-no-tag
(org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text nil)
;; Default formatting.
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "@emph{#%c} " priority))
text))))
(pre-blanks
(make-string (org-element-property :pre-blank headline) 10)))
(cond
;; Case 1: This is a footnote section: ignore it.
((org-element-property :footnote-section-p headline) nil)
;; Case 2: This is the `copying' section: ignore it
;; This is used elsewhere.
((org-element-property :COPYING headline) nil)
;; Case 3: An index. If it matches one of the known indexes,
;; print it as such following the contents, otherwise
;; print the contents and leave the index up to the user.
(index
(format
section-fmt full-text
(concat pre-blanks contents "\n"
(if (member index '("cp" "fn" "ky" "pg" "tp" "vr"))
(concat "@printindex " index)))))
;; Case 4: This is a deep sub-tree: export it as a list item.
;; Also export as items headlines for which no section
;; format has been found.
((or (not section-fmt) (org-export-low-level-p headline info))
;; Build the real contents of the sub-tree.
(let ((low-level-body
(concat
;; If the headline is the first sibling, start a list.
(when (org-export-first-sibling-p headline info)
(format "@%s\n" (if numberedp 'enumerate 'itemize)))
;; Itemize headline
"@item\n" full-text "\n" pre-blanks contents)))
;; If headline is not the last sibling simply return
;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
;; blank line.
(if (not (org-export-last-sibling-p headline info)) low-level-body
(replace-regexp-in-string
"[ \t\n]*\\'"
(format "\n@end %s" (if numberedp 'enumerate 'itemize))
low-level-body))))
;; Case 5: Standard headline. Export it as a section.
(t
(cond
((not (and tags (eq (plist-get info :with-tags) 'not-in-toc)))
;; Regular section. Use specified format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents)))
((string-match "\\`@\\(.*?\\){" section-fmt)
;; If tags should be removed from table of contents, insert
;; title without tags as an alternative heading in sectioning
;; command.
(format (replace-match (concat (match-string 1 section-fmt) "[%s]")
nil nil section-fmt 1)
;; Replace square brackets with parenthesis since
;; square brackets are not supported in optional
;; arguments.
(replace-regexp-in-string
"\\[" "("
(replace-regexp-in-string
"\\]" ")"
full-text-no-tag))
full-text
(concat pre-blanks contents)))
(t
;; Impossible to add an alternative heading. Fallback to
;; regular sectioning format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents))))))))
;;; Inline Src Block
(defun org-texinfo-inline-src-block (inline-src-block contents info)
"Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((code (org-element-property :value inline-src-block))
(separator (org-texinfo--find-verb-separator code)))
(concat "@verb{" separator code separator "}")))
;;; Inlinetask
(defun org-texinfo-inlinetask (inlinetask contents info)
"Transcode an INLINETASK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let ((title (org-export-data (org-element-property :title inlinetask) info))
(todo (and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword inlinetask)))
(and todo (org-export-data todo info)))))
(todo-type (org-element-property :todo-type inlinetask))
(tags (and (plist-get info :with-tags)
(org-export-get-tags inlinetask info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority inlinetask))))
;; If `org-texinfo-format-inlinetask-function' is provided, call it
;; with appropriate arguments.
(if (not (eq org-texinfo-format-inlinetask-function 'ignore))
(funcall org-texinfo-format-inlinetask-function
todo todo-type priority title tags contents)
;; Otherwise, use a default template.
(let ((full-title
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "#%c " priority))
title
(when tags (format ":%s:"
(mapconcat 'identity tags ":"))))))
(format (concat "@center %s\n\n"
"%s"
"\n")
full-title contents)))))
;;; Italic
(defun org-texinfo-italic (italic contents info)
"Transcode ITALIC from Org to Texinfo.
CONTENTS is the text with italic markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'italic))
;;; Item
(defun org-texinfo-item (item contents info)
"Transcode an ITEM element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((tag (org-element-property :tag item))
(desc (org-export-data tag info)))
(concat "\n@item " (if tag desc) "\n"
(and contents (org-trim contents)) "\n")))
;;; Keyword
(defun org-texinfo-keyword (keyword contents info)
"Transcode a KEYWORD element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((key (org-element-property :key keyword))
(value (org-element-property :value keyword)))
(cond
((string= key "TEXINFO") value)
((string= key "CINDEX") (format "@cindex %s" value))
((string= key "FINDEX") (format "@findex %s" value))
((string= key "KINDEX") (format "@kindex %s" value))
((string= key "PINDEX") (format "@pindex %s" value))
((string= key "TINDEX") (format "@tindex %s" value))
((string= key "VINDEX") (format "@vindex %s" value)))))
;;; Line Break
(defun org-texinfo-line-break (line-break contents info)
"Transcode a LINE-BREAK object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
"@*\n")
;;; Link
(defun org-texinfo-link (link desc info)
"Transcode a LINK object from Org to Texinfo.
DESC is the description part of the link, or the empty string.
INFO is a plist holding contextual information. See
`org-export-data'."
(let* ((type (org-element-property :type link))
(raw-path (org-element-property :path link))
;; Ensure DESC really exists, or set it to nil.
(desc (and (not (string= desc "")) desc))
(path (cond
((member type '("http" "https" "ftp"))
(concat type ":" raw-path))
((string= type "file")
(if (file-name-absolute-p raw-path)
(concat "file://" (expand-file-name raw-path))
(concat "file://" raw-path)))
(t raw-path)))
(email (if (string= type "mailto")
(let ((text (replace-regexp-in-string
"@" "@@" raw-path)))
(concat text (if desc (concat "," desc))))))
protocol)
(cond
;; Links pointing to a headline: Find destination and build
;; appropriate referencing command.
((member type '("custom-id" "id"))
(let ((destination (org-export-resolve-id-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
((member type '("info"))
(let* ((info-path (split-string path "[:#]"))
(info-manual (car info-path))
(info-node (or (cadr info-path) "top"))
(title (or desc "")))
(format "@ref{%s,%s,,%s,}" info-node title info-manual)))
((member type '("fuzzy"))
(let ((destination (org-export-resolve-fuzzy-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
;; Special case for email addresses
(email
(format "@email{%s}" email))
;; External link with a description part.
((and path desc) (format "@uref{%s,%s}" path desc))
;; External link without a description part.
(path (format "@uref{%s}" path))
;; No path, only description. Try to do something useful.
(t (format org-texinfo-link-with-unknown-path-format desc)))))
;;; Menu
(defun org-texinfo-make-menu (info level)
"Create the menu for inclusion in the texifo document.
INFO is the parsed buffer that contains the headlines. LEVEL
determines whether to make the main menu, or the detailed menu.
This is only used for generating the primary menu. In-Node menus
are generated directly."
(let ((parse (plist-get info :parse-tree)))
(cond
;; Generate the main menu
((eq level 'main) (org-texinfo--build-menu parse 1 info))
;; Generate the detailed (recursive) menu
((eq level 'detailed)
;; Requires recursion
;;(org-texinfo--build-detailed-menu parse top info)
(org-texinfo--build-menu parse 1 info 'detailed)))))
;;; Paragraph
(defun org-texinfo-paragraph (paragraph contents info)
"Transcode a PARAGRAPH element from Org to Texinfo.
CONTENTS is the contents of the paragraph, as a string. INFO is
the plist used as a communication channel."
contents)
;;; Plain List
(defun org-texinfo-plain-list (plain-list contents info)
"Transcode a PLAIN-LIST element from Org to Texinfo.
CONTENTS is the contents of the list. INFO is a plist holding
contextual information."
(let* ((attr (org-export-read-attribute :attr_texinfo plain-list))
(indic (or (plist-get attr :indic)
org-texinfo-def-table-markup))
(type (org-element-property :type plain-list))
(table-type (plist-get attr :table-type))
;; Ensure valid texinfo table type.
(table-type (if (member table-type '("ftable" "vtable")) table-type
"table"))
(list-type (cond
((eq type 'ordered) "enumerate")
((eq type 'unordered) "itemize")
((eq type 'descriptive) table-type))))
(format "@%s%s\n@end %s"
(if (eq type 'descriptive)
(concat list-type " " indic)
list-type)
contents
list-type)))
;;; Plain Text
(defun org-texinfo-plain-text (text info)
"Transcode a TEXT string from Org to Texinfo.
TEXT is the string to transcode. INFO is a plist holding
contextual information."
;; First protect @, { and }.
(let ((output (org-texinfo--sanitize-content text)))
;; Activate smart quotes. Be sure to provide original TEXT string
;; since OUTPUT may have been modified.
(when (plist-get info :with-smart-quotes)
(setq output
(org-export-activate-smart-quotes output :texinfo info text)))
;; LaTeX into @LaTeX{} and TeX into @TeX{}
(let ((case-fold-search nil)
(start 0))
(while (string-match "\\(\\(?:La\\)?TeX\\)" output start)
(setq output (replace-match
(format "@%s{}" (match-string 1 output)) nil t output)
start (match-end 0))))
;; Convert special strings.
(when (plist-get info :with-special-strings)
(while (string-match (regexp-quote "...") output)
(setq output (replace-match "@dots{}" nil t output))))
;; Handle break preservation if required.
(when (plist-get info :preserve-breaks)
(setq output (replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " @*\n" output)))
;; Return value.
output))
;;; Planning
(defun org-texinfo-planning (planning contents info)
"Transcode a PLANNING element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(mapconcat
'identity
(delq nil
(list
(let ((closed (org-element-property :closed planning)))
(when closed
(concat
(format "@strong{%s} " org-closed-string)
(format org-texinfo-inactive-timestamp-format
(org-translate-time
(org-element-property :raw-value closed))))))
(let ((deadline (org-element-property :deadline planning)))
(when deadline
(concat
(format "@strong{%s} " org-deadline-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value deadline))))))
(let ((scheduled (org-element-property :scheduled planning)))
(when scheduled
(concat
(format "@strong{%s} " org-scheduled-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value scheduled))))))))
" ")
"@*"))
;;; Property Drawer
(defun org-texinfo-property-drawer (property-drawer contents info)
"Transcode a PROPERTY-DRAWER element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
;; The property drawer isn't exported but we want separating blank
;; lines nonetheless.
"")
;;; Quote Block
(defun org-texinfo-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((title (org-element-property :name quote-block))
(start-quote (concat "@quotation"
(if title
(format " %s" title)))))
(format "%s\n%s@end quotation" start-quote contents)))
;;; Quote Section
(defun org-texinfo-quote-section (quote-section contents info)
"Transcode a QUOTE-SECTION element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((value (org-remove-indentation
(org-element-property :value quote-section))))
(when value (format "@verbatim\n%s@end verbatim" value))))
;;; Radio Target
(defun org-texinfo-radio-target (radio-target text info)
"Transcode a RADIO-TARGET object from Org to Texinfo.
TEXT is the text of the target. INFO is a plist holding
contextual information."
(format "@anchor{%s}%s"
(org-export-solidify-link-text
(org-element-property :value radio-target))
text))
;;; Section
(defun org-texinfo-section (section contents info)
"Transcode a SECTION element from Org to Texinfo.
CONTENTS holds the contents of the section. INFO is a plist
holding contextual information."
contents)
;;; Special Block
(defun org-texinfo-special-block (special-block contents info)
"Transcode a SPECIAL-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Src Block
(defun org-texinfo-src-block (src-block contents info)
"Transcode a SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((lang (org-element-property :language src-block))
(lisp-p (string-match-p "lisp" lang))
(src-contents (org-texinfo--sanitize-content
(org-export-format-code-default src-block info))))
(cond
;; Case 1. Lisp Block
(lisp-p
(format "@lisp\n%s@end lisp"
src-contents))
;; Case 2. Other blocks
(t
(format "@example\n%s@end example"
src-contents)))))
;;; Statistics Cookie
(defun org-texinfo-statistics-cookie (statistics-cookie contents info)
"Transcode a STATISTICS-COOKIE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(org-element-property :value statistics-cookie))
;;; Subscript
(defun org-texinfo-subscript (subscript contents info)
"Transcode a SUBSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{_%s}" contents))
;;; Superscript
(defun org-texinfo-superscript (superscript contents info)
"Transcode a SUPERSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{^%s}" contents))
;;; Table
;;
;; `org-texinfo-table' is the entry point for table transcoding. It
;; takes care of tables with a "verbatim" attribute. Otherwise, it
;; delegates the job to either `org-texinfo-table--table.el-table' or
;; `org-texinfo-table--org-table' functions, depending of the type of
;; the table.
;;
;; `org-texinfo-table--align-string' is a subroutine used to build
;; alignment string for Org tables.
(defun org-texinfo-table (table contents info)
"Transcode a TABLE element from Org to Texinfo.
CONTENTS is the contents of the table. INFO is a plist holding
contextual information."
(cond
;; Case 1: verbatim table.
((or org-texinfo-tables-verbatim
(let ((attr (mapconcat 'identity
(org-element-property :attr_latex table)
" ")))
(and attr (string-match "\\<verbatim\\>" attr))))
(format "@verbatim \n%s\n@end verbatim"
;; Re-create table, without affiliated keywords.
(org-trim
(org-element-interpret-data
`(table nil ,@(org-element-contents table))))))
;; Case 2: table.el table. Convert it using appropriate tools.
((eq (org-element-property :type table) 'table.el)
(org-texinfo-table--table.el-table table contents info))
;; Case 3: Standard table.
(t (org-texinfo-table--org-table table contents info))))
(defun org-texinfo-table-column-widths (table info)
"Determine the largest table cell in each column to process alignment.
TABLE is the table element to transcode. INFO is a plist used as
a communication channel."
(let* ((rows (org-element-map table 'table-row 'identity info))
(collected (loop for row in rows collect
(org-element-map row 'table-cell 'identity info)))
(number-cells (length (car collected)))
cells counts)
(loop for row in collected do
(push (mapcar (lambda (ref)
(let* ((start (org-element-property :contents-begin ref))
(end (org-element-property :contents-end ref))
(length (- end start)))
length)) row) cells))
(setq cells (org-remove-if 'null cells))
(push (loop for count from 0 to (- number-cells 1) collect
(loop for item in cells collect
(nth count item))) counts)
(mapconcat (lambda (size)
(make-string size ?a)) (mapcar (lambda (ref)
(apply 'max `(,@ref))) (car counts))
"} {")))
(defun org-texinfo-table--org-table (table contents info)
"Return appropriate Texinfo code for an Org table.
TABLE is the table type element to transcode. CONTENTS is its
contents, as a string. INFO is a plist used as a communication
channel.
This function assumes TABLE has `org' as its `:type' attribute."
(let* ((attr (org-export-read-attribute :attr_texinfo table))
(col-width (plist-get attr :columns))
(columns (if col-width
(format "@columnfractions %s"
col-width)
(format "{%s}"
(org-texinfo-table-column-widths
table info)))))
;; Prepare the final format string for the table.
(cond
;; Longtable.
;; Others.
(t (concat
(format "@multitable %s\n%s@end multitable"
columns
contents))))))
(defun org-texinfo-table--table.el-table (table contents info)
"Returns nothing.
Rather than return an invalid table, nothing is returned."
'nil)
;;; Table Cell
(defun org-texinfo-table-cell (table-cell contents info)
"Transcode a TABLE-CELL element from Org to Texinfo.
CONTENTS is the cell contents. INFO is a plist used as
a communication channel."
(concat (if (and contents
org-texinfo-table-scientific-notation
(string-match orgtbl-exp-regexp contents))
;; Use appropriate format string for scientific
;; notation.
(format org-texinfo-table-scientific-notation
(match-string 1 contents)
(match-string 2 contents))
contents)
(when (org-export-get-next-element table-cell info) "\n@tab ")))
;;; Table Row
(defun org-texinfo-table-row (table-row contents info)
"Transcode a TABLE-ROW element from Org to Texinfo.
CONTENTS is the contents of the row. INFO is a plist used as
a communication channel."
;; Rules are ignored since table separators are deduced from
;; borders of the current row.
(when (eq (org-element-property :type table-row) 'standard)
(let ((rowgroup-tag
(cond
;; Case 1: Belongs to second or subsequent rowgroup.
((not (= 1 (org-export-table-row-group table-row info)))
"@item ")
;; Case 2: Row is from first rowgroup. Table has >=1 rowgroups.
((org-export-table-has-header-p
(org-export-get-parent-table table-row) info)
"@headitem ")
;; Case 3: Row is from first and only row group.
(t "@item "))))
(when (eq (org-element-property :type table-row) 'standard)
(concat rowgroup-tag contents "\n")))))
;;; Target
(defun org-texinfo-target (target contents info)
"Transcode a TARGET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@anchor{%s}"
(org-export-solidify-link-text (org-element-property :value target))))
;;; Timestamp
(defun org-texinfo-timestamp (timestamp contents info)
"Transcode a TIMESTAMP object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(let ((value (org-texinfo-plain-text
(org-timestamp-translate timestamp) info)))
(case (org-element-property :type timestamp)
((active active-range)
(format org-texinfo-active-timestamp-format value))
((inactive inactive-range)
(format org-texinfo-inactive-timestamp-format value))
(t (format org-texinfo-diary-timestamp-format value)))))
;;; Verbatim
(defun org-texinfo-verbatim (verbatim contents info)
"Transcode a VERBATIM object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value verbatim) 'verbatim))
;;; Verse Block
(defun org-texinfo-verse-block (verse-block contents info)
"Transcode a VERSE-BLOCK element from Org to Texinfo.
CONTENTS is verse block contents. INFO is a plist holding
contextual information."
;; In a verse environment, add a line break to each newline
;; character and change each white space at beginning of a line
;; into a space of 1 em. Also change each blank line with
;; a vertical space of 1 em.
(progn
(setq contents (replace-regexp-in-string
"^ *\\\\\\\\$" "\\\\vspace*{1em}"
(replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" contents)))
(while (string-match "^[ \t]+" contents)
(let ((new-str (format "\\hspace*{%dem}"
(length (match-string 0 contents)))))
(setq contents (replace-match new-str nil t contents))))
(format "\\begin{verse}\n%s\\end{verse}" contents)))
;;; Interactive functions
(defun org-texinfo-export-to-texinfo
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to a Texinfo file.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
Return output file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist)))
(defun org-texinfo-export-to-info
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to Texinfo then process through to INFO.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
When optional argument PUB-DIR is set, use it as the publishing
directory.
Return INFO file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist
(lambda (file) (org-texinfo-compile file)))))
;;;###autoload
(defun org-texinfo-publish-to-texinfo (plist filename pub-dir)
"Publish an org file to Texinfo.
FILENAME is the filename of the Org file to be published. PLIST
is the property list for the given project. PUB-DIR is the
publishing directory.
Return output file name."
(org-publish-org-to 'texinfo filename ".texi" plist pub-dir))
;;;###autoload
(defun org-texinfo-convert-region-to-texinfo ()
"Assume the current region has org-mode syntax, and convert it to Texinfo.
This can be used in any buffer. For example, you can write an
itemized list in org-mode syntax in an Texinfo buffer and use
this command to convert it."
(interactive)
(org-export-replace-region-by 'texinfo))
(defun org-texinfo-compile (file)
"Compile a texinfo file.
FILE is the name of the file being compiled. Processing is
done through the command specified in `org-texinfo-info-process'.
Return INFO file name or an error if it couldn't be produced."
(let* ((base-name (file-name-sans-extension (file-name-nondirectory file)))
(full-name (file-truename file))
(out-dir (file-name-directory file))
;; Properly set working directory for compilation.
(default-directory (if (file-name-absolute-p file)
(file-name-directory full-name)
default-directory))
errors)
(message (format "Processing Texinfo file %s..." file))
(save-window-excursion
(cond
;; A function is provided: Apply it.
((functionp org-texinfo-info-process)
(funcall org-texinfo-info-process (shell-quote-argument file)))
;; A list is provided: Replace %b, %f and %o with appropriate
;; values in each command before applying it. Output is
;; redirected to "*Org INFO Texinfo Output*" buffer.
((consp org-texinfo-info-process)
(let ((outbuf (get-buffer-create "*Org INFO Texinfo Output*")))
(mapc
(lambda (command)
(shell-command
(replace-regexp-in-string
"%b" (shell-quote-argument base-name)
(replace-regexp-in-string
"%f" (shell-quote-argument full-name)
(replace-regexp-in-string
"%o" (shell-quote-argument out-dir) command t t) t t) t t)
outbuf))
org-texinfo-info-process)
;; Collect standard errors from output buffer.
(setq errors (org-texinfo-collect-errors outbuf))))
(t (error "No valid command to process to Info")))
(let ((infofile (concat out-dir base-name ".info")))
;; Check for process failure. Provide collected errors if
;; possible.
(if (not (file-exists-p infofile))
(error (concat (format "INFO file %s wasn't produced" infofile)
(when errors (concat ": " errors))))
;; Else remove log files, when specified, and signal end of
;; process to user, along with any error encountered.
(when org-texinfo-remove-logfiles
(dolist (ext org-texinfo-logfiles-extensions)
(let ((file (concat out-dir base-name "." ext)))
(when (file-exists-p file) (delete-file file)))))
(message (concat "Process completed"
(if (not errors) "."
(concat " with errors: " errors)))))
;; Return output file name.
infofile))))
(defun org-texinfo-collect-errors (buffer)
"Collect some kind of errors from \"makeinfo\" command output.
BUFFER is the buffer containing output.
Return collected error types as a string, or nil if there was
none."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
;; Find final "makeinfo" run.
(when t
(let ((case-fold-search t)
(errors ""))
(when (save-excursion
(re-search-forward "perhaps incorrect sectioning?" nil t))
(setq errors (concat errors " [incorrect sectioning]")))
(when (save-excursion
(re-search-forward "missing close brace" nil t))
(setq errors (concat errors " [syntax error]")))
(when (save-excursion
(re-search-forward "Unknown command" nil t))
(setq errors (concat errors " [undefined @command]")))
(when (save-excursion
(re-search-forward "No matching @end" nil t))
(setq errors (concat errors " [block incomplete]")))
(when (save-excursion
(re-search-forward "requires a sectioning" nil t))
(setq errors (concat errors " [invalid section command]")))
(when (save-excursion
(re-search-forward "\\[unexpected\]" nil t))
(setq errors (concat errors " [unexpected error]")))
(when (save-excursion
(re-search-forward "misplaced " nil t))
(setq errors (concat errors " [syntax error]")))
(and (org-string-nw-p errors) (org-trim errors)))))))
(provide 'ox-texinfo)
;; Local variables:
;; generated-autoload-file: "org-loaddefs.el"
;; End:
;;; ox-texinfo.el ends here
| 40088 | ;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine
;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>athan.leechpepin at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This library implements a Texinfo back-end for Org generic
;; exporter.
;;
;; To test it, run
;;
;; M-: (org-export-to-buffer 'texinfo "*Test Texinfo*") RET
;;
;; in an Org mode buffer then switch to the buffer to see the Texinfo
;; export. See ox.el for more details on how this exporter works.
;;
;; It introduces nine new buffer keywords: "TEXINFO_CLASS",
;; "TEXINFO_FILENAME", "TEXINFO_HEADER", "TEXINFO_POST_HEADER",
;; "TEXINFO_DIR_CATEGORY", "TEXINFO_DIR_TITLE", "TEXINFO_DIR_DESC"
;; "SUBTITLE" and "SUBAUTHOR".
;;
;; It introduces 1 new headline property keywords:
;; "TEXINFO_MENU_TITLE" for optional menu titles.
;;
;; To include inline code snippets (for example for generating @kbd{}
;; and @key{} commands), the following export-snippet keys are
;; accepted:
;;
;; texinfo
;; info
;;
;; You can add them for export snippets via any of the below:
;;
;; (add-to-list 'org-export-snippet-translation-alist
;; '("info" . "texinfo"))
;;
;;; Code:
(eval-when-compile (require 'cl))
(require 'ox)
(defvar orgtbl-exp-regexp)
;;; Define Back-End
(org-export-define-backend 'texinfo
'((bold . org-texinfo-bold)
(center-block . org-texinfo-center-block)
(clock . org-texinfo-clock)
(code . org-texinfo-code)
(comment . org-texinfo-comment)
(comment-block . org-texinfo-comment-block)
(drawer . org-texinfo-drawer)
(dynamic-block . org-texinfo-dynamic-block)
(entity . org-texinfo-entity)
(example-block . org-texinfo-example-block)
(export-block . org-texinfo-export-block)
(export-snippet . org-texinfo-export-snippet)
(fixed-width . org-texinfo-fixed-width)
(footnote-definition . org-texinfo-footnote-definition)
(footnote-reference . org-texinfo-footnote-reference)
(headline . org-texinfo-headline)
(inline-src-block . org-texinfo-inline-src-block)
(inlinetask . org-texinfo-inlinetask)
(italic . org-texinfo-italic)
(item . org-texinfo-item)
(keyword . org-texinfo-keyword)
(line-break . org-texinfo-line-break)
(link . org-texinfo-link)
(paragraph . org-texinfo-paragraph)
(plain-list . org-texinfo-plain-list)
(plain-text . org-texinfo-plain-text)
(planning . org-texinfo-planning)
(property-drawer . org-texinfo-property-drawer)
(quote-block . org-texinfo-quote-block)
(quote-section . org-texinfo-quote-section)
(radio-target . org-texinfo-radio-target)
(section . org-texinfo-section)
(special-block . org-texinfo-special-block)
(src-block . org-texinfo-src-block)
(statistics-cookie . org-texinfo-statistics-cookie)
(subscript . org-texinfo-subscript)
(superscript . org-texinfo-superscript)
(table . org-texinfo-table)
(table-cell . org-texinfo-table-cell)
(table-row . org-texinfo-table-row)
(target . org-texinfo-target)
(template . org-texinfo-template)
(timestamp . org-texinfo-timestamp)
(verbatim . org-texinfo-verbatim)
(verse-block . org-texinfo-verse-block))
:export-block "TEXINFO"
:filters-alist
'((:filter-headline . org-texinfo-filter-section-blank-lines)
(:filter-section . org-texinfo-filter-section-blank-lines))
:menu-entry
'(?i "Export to Texinfo"
((?t "As TEXI file" org-texinfo-export-to-texinfo)
(?i "As INFO file" org-texinfo-export-to-info)))
:options-alist
'((:texinfo-filename "TEXINFO_FILENAME" nil org-texinfo-filename t)
(:texinfo-class "TEXINFO_CLASS" nil org-texinfo-default-class t)
(:texinfo-header "TEXINFO_HEADER" nil nil newline)
(:texinfo-post-header "TEXINFO_POST_HEADER" nil nil newline)
(:subtitle "SUBTITLE" nil nil newline)
(:subauthor "SUBAUTHOR" nil nil newline)
(:texinfo-dircat "TEXINFO_DIR_CATEGORY" nil nil t)
(:texinfo-dirtitle "TEXINFO_DIR_TITLE" nil nil t)
(:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)))
;;; User Configurable Variables
(defgroup org-export-texinfo nil
"Options for exporting Org mode files to Texinfo."
:tag "Org Export Texinfo"
:version "24.4"
:package-version '(Org . "8.0")
:group 'org-export)
;;; Preamble
(defcustom org-texinfo-filename ""
"Default filename for Texinfo output."
:group 'org-export-texinfo
:type '(string :tag "Export Filename"))
(defcustom org-texinfo-coding-system nil
"Default document encoding for Texinfo output.
If `nil' it will default to `buffer-file-coding-system'."
:group 'org-export-texinfo
:type 'coding-system)
(defcustom org-texinfo-default-class "info"
"The default Texinfo class."
:group 'org-export-texinfo
:type '(string :tag "Texinfo class"))
(defcustom org-texinfo-classes
'(("info"
"\\input texinfo @c -*- texinfo -*-"
("@chapter %s" . "@unnumbered %s")
("@section %s" . "@unnumberedsec %s")
("@subsection %s" . "@unnumberedsubsec %s")
("@subsubsection %s" . "@unnumberedsubsubsec %s")))
"Alist of Texinfo classes and associated header and structure.
If #+Texinfo_CLASS is set in the buffer, use its value and the
associated information. Here is the structure of each cell:
\(class-name
header-string
\(numbered-section . unnumbered-section\)
...\)
The sectioning structure
------------------------
The sectioning structure of the class is given by the elements
following the header string. For each sectioning level, a number
of strings is specified. A %s formatter is mandatory in each
section string and will be replaced by the title of the section.
Instead of a list of sectioning commands, you can also specify
a function name. That function will be called with two
parameters, the \(reduced) level of the headline, and a predicate
non-nil when the headline should be numbered. It must return
a format string in which the section title will be added."
:group 'org-export-texinfo
:type '(repeat
(list (string :tag "Texinfo class")
(string :tag "Texinfo header")
(repeat :tag "Levels" :inline t
(choice
(cons :tag "Heading"
(string :tag " numbered")
(string :tag "unnumbered"))
(function :tag "Hook computing sectioning"))))))
;;; Headline
(defcustom org-texinfo-format-headline-function 'ignore
"Function to format headline text.
This function will be called with 5 arguments:
TODO the todo keyword (string or nil).
TODO-TYPE the type of todo (symbol: `todo', `done', nil)
PRIORITY the priority of the headline (integer or nil)
TEXT the main headline text (string).
TAGS the tags as a list of strings (list of strings or nil).
The function result will be used in the section format string.
As an example, one could set the variable to the following, in
order to reproduce the default set-up:
\(defun org-texinfo-format-headline (todo todo-type priority text tags)
\"Default format function for a headline.\"
\(concat (when todo
\(format \"\\\\textbf{\\\\textsc{\\\\textsf{%s}}} \" todo))
\(when priority
\(format \"\\\\framebox{\\\\#%c} \" priority))
text
\(when tags
\(format \"\\\\hfill{}\\\\textsc{%s}\"
\(mapconcat 'identity tags \":\"))))"
:group 'org-export-texinfo
:type 'function)
;;; Node listing (menu)
(defcustom org-texinfo-node-description-column 32
"Column at which to start the description in the node
listings.
If a node title is greater than this length, the description will
be placed after the end of the title."
:group 'org-export-texinfo
:type 'integer)
;;; Footnotes
;;
;; Footnotes are inserted directly
;;; Timestamps
(defcustom org-texinfo-active-timestamp-format "@emph{%s}"
"A printf format string to be applied to active timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-inactive-timestamp-format "@emph{%s}"
"A printf format string to be applied to inactive timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-diary-timestamp-format "@emph{%s}"
"A printf format string to be applied to diary timestamps."
:group 'org-export-texinfo
:type 'string)
;;; Links
(defcustom org-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
"Format string for links with unknown path type."
:group 'org-export-texinfo
:type 'string)
;;; Tables
(defcustom org-texinfo-tables-verbatim nil
"When non-nil, tables are exported verbatim."
:group 'org-export-texinfo
:type 'boolean)
(defcustom org-texinfo-table-scientific-notation "%s\\,(%s)"
"Format string to display numbers in scientific notation.
The format should have \"%s\" twice, for mantissa and exponent
\(i.e. \"%s\\\\times10^{%s}\").
When nil, no transformation is made."
:group 'org-export-texinfo
:type '(choice
(string :tag "Format string")
(const :tag "No formatting")))
(defcustom org-texinfo-def-table-markup "@samp"
"Default setting for @table environments."
:group 'org-export-texinfo
:type 'string)
;;; Text markup
(defcustom org-texinfo-text-markup-alist '((bold . "@strong{%s}")
(code . code)
(italic . "@emph{%s}")
(verbatim . verb)
(comment . "@c %s"))
"Alist of Texinfo expressions to convert text markup.
The key must be a symbol among `bold', `italic' and `comment'.
The value is a formatting string to wrap fontified text with.
Value can also be set to the following symbols: `verb' and
`code'. For the former, Org will use \"@verb\" to
create a format string and select a delimiter character that
isn't in the string. For the latter, Org will use \"@code\"
to typeset and try to protect special characters.
If no association can be found for a given markup, text will be
returned as-is."
:group 'org-export-texinfo
:type 'alist
:options '(bold code italic verbatim comment))
;;; Drawers
(defcustom org-texinfo-format-drawer-function
(lambda (name contents) contents)
"Function called to format a drawer in Texinfo code.
The function must accept two parameters:
NAME the drawer name, like \"LOGBOOK\"
CONTENTS the contents of the drawer.
The function should return the string to be exported.
The default function simply returns the value of CONTENTS."
:group 'org-export-texinfo
:version "24.4"
:package-version '(Org . "8.3")
:type 'function)
;;; Inlinetasks
(defcustom org-texinfo-format-inlinetask-function 'ignore
"Function called to format an inlinetask in Texinfo code.
The function must accept six parameters:
TODO the todo keyword, as a string
TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
PRIORITY the inlinetask priority, as a string
NAME the inlinetask name, as a string.
TAGS the inlinetask tags, as a list of strings.
CONTENTS the contents of the inlinetask, as a string.
The function should return the string to be exported.
For example, the variable could be set to the following function
in order to mimic default behavior:
\(defun org-texinfo-format-inlinetask \(todo type priority name tags contents\)
\"Format an inline task element for Texinfo export.\"
\(let ((full-title
\(concat
\(when todo
\(format \"@strong{%s} \" todo))
\(when priority (format \"#%c \" priority))
title
\(when tags
\(format \":%s:\"
\(mapconcat 'identity tags \":\")))))
\(format (concat \"@center %s\n\n\"
\"%s\"
\"\n\"))
full-title contents))"
:group 'org-export-texinfo
:type 'function)
;;; Src blocks
;;
;; Src Blocks are example blocks, except for LISP
;;; Compilation
(defcustom org-texinfo-info-process
'("makeinfo %f")
"Commands to process a Texinfo file to an INFO file.
This is list of strings, each of them will be given to the shell
as a command. %f in the command will be replaced by the full
file name, %b by the file base name \(i.e without extension) and
%o by the base directory of the file."
:group 'org-export-texinfo
:type '(repeat :tag "Shell command sequence"
(string :tag "Shell command")))
(defcustom org-texinfo-logfiles-extensions
'("aux" "toc" "cp" "fn" "ky" "pg" "tp" "vr")
"The list of file extensions to consider as Texinfo logfiles.
The logfiles will be remove if `org-texinfo-remove-logfiles' is
non-nil."
:group 'org-export-texinfo
:type '(repeat (string :tag "Extension")))
(defcustom org-texinfo-remove-logfiles t
"Non-nil means remove the logfiles produced by compiling a Texinfo file.
By default, logfiles are files with these extensions: .aux, .toc,
.cp, .fn, .ky, .pg and .tp. To define the set of logfiles to remove,
set `org-texinfo-logfiles-extensions'."
:group 'org-export-latex
:type 'boolean)
;;; Constants
(defconst org-texinfo-max-toc-depth 4
"Maximum depth for creation of detailed menu listings. Beyond
this depth Texinfo will not recognize the nodes and will cause
errors. Left as a constant in case this value ever changes.")
(defconst org-texinfo-supported-coding-systems
'("US-ASCII" "UTF-8" "ISO-8859-15" "ISO-8859-1" "ISO-8859-2" "koi8-r" "koi8-u")
"List of coding systems supported by Texinfo, as strings.
Specified coding system will be matched against these strings.
If two strings share the same prefix (e.g. \"ISO-8859-1\" and
\"ISO-8859-15\"), the most specific one has to be listed first.")
;;; Internal Functions
(defun org-texinfo-filter-section-blank-lines (headline back-end info)
"Filter controlling number of blank lines after a section."
(let ((blanks (make-string 2 ?\n)))
(replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" blanks headline)))
(defun org-texinfo--find-verb-separator (s)
"Return a character not used in string S.
This is used to choose a separator for constructs like \\verb."
(let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
(loop for c across ll
when (not (string-match (regexp-quote (char-to-string c)) s))
return (char-to-string c))))
(defun org-texinfo--make-option-string (options)
"Return a comma separated string of keywords and values.
OPTIONS is an alist where the key is the options keyword as
a string, and the value a list containing the keyword value, or
nil."
(mapconcat (lambda (pair)
(concat (first pair)
(when (> (length (second pair)) 0)
(concat "=" (second pair)))))
options
","))
(defun org-texinfo--text-markup (text markup)
"Format TEXT depending on MARKUP text markup.
See `org-texinfo-text-markup-alist' for details."
(let ((fmt (cdr (assq markup org-texinfo-text-markup-alist))))
(cond
;; No format string: Return raw text.
((not fmt) text)
((eq 'verb fmt)
(let ((separator (org-texinfo--find-verb-separator text)))
(concat "@verb{" separator text separator "}")))
((eq 'code fmt)
(let ((start 0)
(rtn "")
char)
(while (string-match "[@{}]" text)
(setq char (match-string 0 text))
(if (> (match-beginning 0) 0)
(setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
(setq text (substring text (1+ (match-beginning 0))))
(setq char (concat "@" char)
rtn (concat rtn char)))
(setq text (concat rtn text)
fmt "@code{%s}")
(format fmt text)))
;; Else use format string.
(t (format fmt text)))))
(defun org-texinfo--get-node (headline info)
"Return node entry associated to HEADLINE.
INFO is a plist used as a communication channel."
(let ((menu-title (org-export-get-alt-title headline info)))
(org-texinfo--sanitize-menu
(replace-regexp-in-string
"%" "%%"
(if menu-title (org-export-data menu-title info)
(org-texinfo--sanitize-headline
(org-element-property :title headline) info))))))
;;; Headline sanitizing
(defun org-texinfo--sanitize-headline (headline info)
"Remove all formatting from the text of a headline for use in
node and menu listing."
(mapconcat 'identity
(org-texinfo--sanitize-headline-contents headline info) " "))
(defun org-texinfo--sanitize-headline-contents (headline info)
"Retrieve the content of the headline.
Any content that can contain further formatting is checked
recursively, to ensure that nested content is also properly
retrieved."
(loop for contents in headline append
(cond
;; already a string
((stringp contents)
(list (replace-regexp-in-string " $" "" contents)))
;; Is exported as-is (value)
((org-element-map contents '(verbatim code)
(lambda (value) (org-element-property :value value)) info))
;; Has content and recurse into the content
((org-element-contents contents)
(org-texinfo--sanitize-headline-contents
(org-element-contents contents) info)))))
;;; Menu sanitizing
(defun org-texinfo--sanitize-menu (title)
"Remove invalid characters from TITLE for use in menus and
nodes.
Based on Texinfo specifications, the following must be removed:
@ { } ( ) : . ,"
(replace-regexp-in-string "[@{}():,.]" "" title))
;;; Content sanitizing
(defun org-texinfo--sanitize-content (text)
"Ensure characters are properly escaped when used in headlines or blocks.
Escape characters are: @ { }"
(replace-regexp-in-string "\\\([@{}]\\\)" "@\\1" text))
;;; Menu creation
(defun org-texinfo--build-menu (tree level info &optional detailed)
"Create the @menu/@end menu information from TREE at headline
level LEVEL.
TREE contains the parse-tree to work with, either of the entire
document or of a specific parent headline. LEVEL indicates what
level of headlines to look at when generating the menu. INFO is
a plist containing contextual information.
Detailed determines whether to build a single level of menu, or
recurse into all children as well."
(let ((menu (org-texinfo--generate-menu-list tree level info))
output text-menu)
(cond
(detailed
;; Looping is done within the menu generation.
(setq text-menu (org-texinfo--generate-detailed menu level info)))
(t
(setq text-menu (org-texinfo--generate-menu-items menu info))))
(when text-menu
(setq output (org-texinfo--format-menu text-menu))
(mapconcat 'identity output "\n"))))
(defun org-texinfo--generate-detailed (menu level info)
"Generate a detailed listing of all subheadings within MENU starting at LEVEL.
MENU is the parse-tree to work with. LEVEL is the starting level
for the menu headlines and from which recursion occurs. INFO is
a plist containing contextual information."
(when level
(let ((max-depth (min org-texinfo-max-toc-depth
(plist-get info :headline-levels))))
(when (> max-depth level)
(loop for headline in menu append
(let* ((title (org-texinfo--menu-headlines headline info))
;; Create list of menu entries for the next level
(sublist (org-texinfo--generate-menu-list
headline (1+ level) info))
;; Generate the menu items for that level. If
;; there are none omit that heading completely,
;; otherwise join the title to it's related entries.
(submenu (if (org-texinfo--generate-menu-items sublist info)
(append (list title)
(org-texinfo--generate-menu-items sublist info))
'nil))
;; Start the process over the next level down.
(recursion (org-texinfo--generate-detailed sublist (1+ level) info)))
(setq recursion (append submenu recursion))
recursion))))))
(defun org-texinfo--generate-menu-list (tree level info)
"Generate the list of headlines that are within a given level
of the tree for further formatting.
TREE is the parse-tree containing the headlines. LEVEL is the
headline level to generate a list of. INFO is a plist holding
contextual information."
(org-element-map tree 'headline
(lambda (head)
(and (= (org-export-get-relative-level head info) level)
;; Do not take note of footnotes or copying headlines.
(not (org-element-property :COPYING head))
(not (org-element-property :footnote-section-p head))
;; Collect headline.
head))
info))
(defun org-texinfo--generate-menu-items (items info)
"Generate a list of headline information from the listing ITEMS.
ITEMS is a list of the headlines to be converted into entries.
INFO is a plist containing contextual information.
Returns a list containing the following information from each
headline: length, title, description. This is used to format the
menu using `org-texinfo--format-menu'."
(loop for headline in items collect
(let* ((menu-title (org-texinfo--sanitize-menu
(org-export-data
(org-export-get-alt-title headline info)
info)))
(title (org-texinfo--sanitize-menu
(org-texinfo--sanitize-headline
(org-element-property :title headline) info)))
(descr (org-export-data
(org-element-property :DESCRIPTION headline)
info))
(menu-entry (if (string= "" menu-title) title menu-title))
(len (length menu-entry))
(output (list len menu-entry descr)))
output)))
(defun org-texinfo--menu-headlines (headline info)
"Retrieve the title from HEADLINE.
INFO is a plist holding contextual information.
Return the headline as a list of (length title description) with
length of -1 and nil description. This is used in
`org-texinfo--format-menu' to identify headlines as opposed to
entries."
(let ((title (org-export-data
(org-element-property :title headline) info)))
(list -1 title 'nil)))
(defun org-texinfo--format-menu (text-menu)
"Format the TEXT-MENU items to be properly printed in the menu.
Each entry in the menu should be provided as (length title
description).
Headlines in the detailed menu are given length -1 to ensure they
are never confused with other entries. They also have no
description.
Other menu items are output as:
Title:: description
With the spacing between :: and description based on the length
of the longest menu entry."
(let (output)
(setq output
(mapcar (lambda (name)
(let* ((title (nth 1 name))
(desc (nth 2 name))
(length (nth 0 name))
(column (max
;;6 is "* " ":: " for inserted text
length
(-
org-texinfo-node-description-column
6)))
(spacing (- column length)
))
(if (> length -1)
(concat "* " title ":: "
(make-string spacing ?\s)
(if desc
(concat desc)))
(concat "\n" title "\n"))))
text-menu))
output))
;;; Template
(defun org-texinfo-template (contents info)
"Return complete document string after Texinfo conversion.
CONTENTS is the transcoded contents string. INFO is a plist
holding export options."
(let* ((title (org-export-data (plist-get info :title) info))
(info-filename (or (plist-get info :texinfo-filename)
(file-name-nondirectory
(org-export-output-file-name ".info"))))
(author (org-export-data (plist-get info :author) info))
(lang (org-export-data (plist-get info :language) info))
(texinfo-header (plist-get info :texinfo-header))
(texinfo-post-header (plist-get info :texinfo-post-header))
(subtitle (plist-get info :subtitle))
(subauthor (plist-get info :subauthor))
(class (plist-get info :texinfo-class))
(header (nth 1 (assoc class org-texinfo-classes)))
(copying
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (hl) (and (org-element-property :COPYING hl) hl)) info t))
(dircat (plist-get info :texinfo-dircat))
(dirtitle (plist-get info :texinfo-dirtitle))
(dirdesc (plist-get info :texinfo-dirdesc))
;; Spacing to align description (column 32 - 3 for `* ' and
;; `.' in text.
(dirspacing (- 29 (length dirtitle)))
(menu (org-texinfo-make-menu info 'main))
(detail-menu (org-texinfo-make-menu info 'detailed)))
(concat
;; Header
header "\n"
"@c %**start of header\n"
;; Filename and Title
"@setfilename " info-filename "\n"
"@settitle " title "\n"
;; Coding system.
(format
"@documentencoding %s\n"
(catch 'coding-system
(let ((case-fold-search t)
(name (symbol-name (or org-texinfo-coding-system
buffer-file-coding-system))))
(dolist (system org-texinfo-supported-coding-systems "UTF-8")
(when (org-string-match-p (regexp-quote system) name)
(throw 'coding-system system))))))
"\n"
(format "@documentlanguage %s\n" lang)
"\n\n"
"@c Version and Contact Info\n"
"@set AUTHOR " author "\n"
;; Additional Header Options set by `#+TEXINFO_HEADER
(if texinfo-header
(concat "\n"
texinfo-header
"\n"))
"@c %**end of header\n"
"@finalout\n"
"\n\n"
;; Additional Header Options set by #+TEXINFO_POST_HEADER
(if texinfo-post-header
(concat "\n"
texinfo-post-header
"\n"))
;; Copying
"@copying\n"
;; Only export the content of the headline, do not need the
;; initial headline.
(org-export-data (nth 2 copying) info)
"@end copying\n"
"\n\n"
;; Info directory information
;; Only supply if both title and category are provided
(if (and dircat dirtitle)
(concat "@dircategory " dircat "\n"
"@direntry\n"
"* " dirtitle "."
(make-string dirspacing ?\s)
dirdesc "\n"
"@end direntry\n"))
"\n\n"
;; Title
"@titlepage\n"
"@title " title "\n\n"
(if subtitle
(concat "@subtitle " subtitle "\n"))
"@author " author "\n"
(if subauthor
(concat subauthor "\n"))
"\n"
"@c The following two commands start the copyright page.\n"
"@page\n"
"@vskip 0pt plus 1filll\n"
"@insertcopying\n"
"@end titlepage\n\n"
"@c Output the table of contents at the beginning.\n"
"@contents\n\n"
;; Configure Top Node when not for Tex
"@ifnottex\n"
"@node Top\n"
"@top " title " Manual\n"
"@insertcopying\n"
"@end ifnottex\n\n"
;; Do not output menus if they are empty
(if menu
;; Menu
(concat "@menu\n"
menu
"\n\n"
;; Detailed Menu
(if detail-menu
(concat "@detailmenu\n"
" --- The Detailed Node Listing ---\n"
detail-menu
"\n\n"
"@end detailmenu\n"))
"@end menu\n"))
"\n\n"
;; Document's body.
contents
"\n"
;; Creator.
(let ((creator-info (plist-get info :with-creator)))
(cond
((not creator-info) "")
((eq creator-info 'comment)
(format "@c %s\n" (plist-get info :creator)))
(t (concat (plist-get info :creator) "\n"))))
;; Document end.
"\n@bye")))
;;; Transcode Functions
;;; Bold
(defun org-texinfo-bold (bold contents info)
"Transcode BOLD from Org to Texinfo.
CONTENTS is the text with bold markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'bold))
;;; Center Block
(defun org-texinfo-center-block (center-block contents info)
"Transcode a CENTER-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Clock
(defun org-texinfo-clock (clock contents info)
"Transcode a CLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(format "@strong{%s} " org-clock-string)
(format org-texinfo-inactive-timestamp-format
(concat (org-translate-time
(org-element-property :raw-value
(org-element-property :value clock)))
(let ((time (org-element-property :duration clock)))
(and time (format " (%s)" time)))))
"@*"))
;;; Code
(defun org-texinfo-code (code contents info)
"Transcode a CODE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value code) 'code))
;;; Comment
(defun org-texinfo-comment (comment contents info)
"Transcode a COMMENT object from Org to Texinfo.
CONTENTS is the text in the comment. INFO is a plist holding
contextual information."
(org-texinfo--text-markup (org-element-property :value comment) 'comment))
;;; Comment Block
(defun org-texinfo-comment-block (comment-block contents info)
"Transcode a COMMENT-BLOCK object from Org to Texinfo.
CONTENTS is the text within the block. INFO is a plist holding
contextual information."
(format "@ignore\n%s@end ignore" (org-element-property :value comment-block)))
;;; Drawer
(defun org-texinfo-drawer (drawer contents info)
"Transcode a DRAWER element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((name (org-element-property :drawer-name drawer))
(output (funcall org-texinfo-format-drawer-function
name contents)))
output))
;;; Dynamic Block
(defun org-texinfo-dynamic-block (dynamic-block contents info)
"Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information. See `org-export-data'."
contents)
;;; Entity
(defun org-texinfo-entity (entity contents info)
"Transcode an ENTITY object from Org to Texinfo.
CONTENTS are the definition itself. INFO is a plist holding
contextual information."
(let ((ent (org-element-property :latex entity)))
(if (org-element-property :latex-math-p entity) (format "@math{%s}" ent) ent)))
;;; Example Block
(defun org-texinfo-example-block (example-block contents info)
"Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@verbatim\n%s@end verbatim"
(org-export-format-code-default example-block info)))
;;; Export Block
(defun org-texinfo-export-block (export-block contents info)
"Transcode a EXPORT-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (string= (org-element-property :type export-block) "TEXINFO")
(org-remove-indentation (org-element-property :value export-block))))
;;; Export Snippet
(defun org-texinfo-export-snippet (export-snippet contents info)
"Transcode a EXPORT-SNIPPET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (eq (org-export-snippet-backend export-snippet) 'texinfo)
(org-element-property :value export-snippet)))
;;; Fixed Width
(defun org-texinfo-fixed-width (fixed-width contents info)
"Transcode a FIXED-WIDTH element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(format "@example\n%s\n@end example"
(org-remove-indentation
(org-texinfo--sanitize-content
(org-element-property :value fixed-width)))))
;;; Footnote Reference
;;
(defun org-texinfo-footnote-reference (footnote contents info)
"Create a footnote reference for FOOTNOTE.
FOOTNOTE is the footnote to define. CONTENTS is nil. INFO is a
plist holding contextual information."
(let ((def (org-export-get-footnote-definition footnote info)))
(format "@footnote{%s}"
(org-trim (org-export-data def info)))))
;;; Headline
(defun org-texinfo-headline (headline contents info)
"Transcode a HEADLINE element from Org to Texinfo.
CONTENTS holds the contents of the headline. INFO is a plist
holding contextual information."
(let* ((class (plist-get info :texinfo-class))
(level (org-export-get-relative-level headline info))
(numberedp (org-export-numbered-headline-p headline info))
(class-sectioning (assoc class org-texinfo-classes))
;; Find the index type, if any
(index (org-element-property :INDEX headline))
;; Check if it is an appendix
(appendix (org-element-property :APPENDIX headline))
;; Retrieve headline text
(text (org-texinfo--sanitize-headline
(org-element-property :title headline) info))
;; Create node info, to insert it before section formatting.
;; Use custom menu title if present
(node (format "@node %s\n" (org-texinfo--get-node headline info)))
;; Menus must be generated with first child, otherwise they
;; will not nest properly
(menu (let* ((first (org-export-first-sibling-p headline info))
(parent (org-export-get-parent-headline headline))
(title (org-texinfo--sanitize-headline
(org-element-property :title parent) info))
heading listing
(tree (plist-get info :parse-tree)))
(if first
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (ref)
(if (member title (org-element-property :title ref))
(push ref heading)))
info t))
(setq listing (org-texinfo--build-menu
(car heading) level info))
(if listing
(setq listing (replace-regexp-in-string
"%" "%%" listing)
listing (format
"\n@menu\n%s\n@end menu\n\n" listing))
'nil)))
;; Section formatting will set two placeholders: one for the
;; title and the other for the contents.
(section-fmt
(let ((sec (if (and (symbolp (nth 2 class-sectioning))
(fboundp (nth 2 class-sectioning)))
(funcall (nth 2 class-sectioning) level numberedp)
(nth (1+ level) class-sectioning))))
(cond
;; No section available for that LEVEL.
((not sec) nil)
;; Section format directly returned by a function.
((stringp sec) sec)
;; (numbered-section . unnumbered-section)
((not (consp (cdr sec)))
(cond
;;If an index, always unnumbered
(index
(concat menu node (cdr sec) "\n%s"))
(appendix
(concat menu node (replace-regexp-in-string
"unnumbered"
"appendix"
(cdr sec)) "\n%s"))
;; Otherwise number as needed.
(t
(concat menu node
(funcall
(if numberedp #'car #'cdr) sec) "\n%s")))))))
(todo
(and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword headline)))
(and todo (org-export-data todo info)))))
(todo-type (and todo (org-element-property :todo-type headline)))
(tags (and (plist-get info :with-tags)
(org-export-get-tags headline info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority headline)))
;; Create the headline text along with a no-tag version. The
;; latter is required to remove tags from table of contents.
(full-text (org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text tags)
;; Default formatting.
(concat
(when todo
(format "@strong{%s} " todo))
(when priority (format "@emph{#%s} " priority))
text
(when tags
(format " :%s:"
(mapconcat 'identity tags ":")))))))
(full-text-no-tag
(org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text nil)
;; Default formatting.
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "@emph{#%c} " priority))
text))))
(pre-blanks
(make-string (org-element-property :pre-blank headline) 10)))
(cond
;; Case 1: This is a footnote section: ignore it.
((org-element-property :footnote-section-p headline) nil)
;; Case 2: This is the `copying' section: ignore it
;; This is used elsewhere.
((org-element-property :COPYING headline) nil)
;; Case 3: An index. If it matches one of the known indexes,
;; print it as such following the contents, otherwise
;; print the contents and leave the index up to the user.
(index
(format
section-fmt full-text
(concat pre-blanks contents "\n"
(if (member index '("cp" "fn" "ky" "pg" "tp" "vr"))
(concat "@printindex " index)))))
;; Case 4: This is a deep sub-tree: export it as a list item.
;; Also export as items headlines for which no section
;; format has been found.
((or (not section-fmt) (org-export-low-level-p headline info))
;; Build the real contents of the sub-tree.
(let ((low-level-body
(concat
;; If the headline is the first sibling, start a list.
(when (org-export-first-sibling-p headline info)
(format "@%s\n" (if numberedp 'enumerate 'itemize)))
;; Itemize headline
"@item\n" full-text "\n" pre-blanks contents)))
;; If headline is not the last sibling simply return
;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
;; blank line.
(if (not (org-export-last-sibling-p headline info)) low-level-body
(replace-regexp-in-string
"[ \t\n]*\\'"
(format "\n@end %s" (if numberedp 'enumerate 'itemize))
low-level-body))))
;; Case 5: Standard headline. Export it as a section.
(t
(cond
((not (and tags (eq (plist-get info :with-tags) 'not-in-toc)))
;; Regular section. Use specified format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents)))
((string-match "\\`@\\(.*?\\){" section-fmt)
;; If tags should be removed from table of contents, insert
;; title without tags as an alternative heading in sectioning
;; command.
(format (replace-match (concat (match-string 1 section-fmt) "[%s]")
nil nil section-fmt 1)
;; Replace square brackets with parenthesis since
;; square brackets are not supported in optional
;; arguments.
(replace-regexp-in-string
"\\[" "("
(replace-regexp-in-string
"\\]" ")"
full-text-no-tag))
full-text
(concat pre-blanks contents)))
(t
;; Impossible to add an alternative heading. Fallback to
;; regular sectioning format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents))))))))
;;; Inline Src Block
(defun org-texinfo-inline-src-block (inline-src-block contents info)
"Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((code (org-element-property :value inline-src-block))
(separator (org-texinfo--find-verb-separator code)))
(concat "@verb{" separator code separator "}")))
;;; Inlinetask
(defun org-texinfo-inlinetask (inlinetask contents info)
"Transcode an INLINETASK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let ((title (org-export-data (org-element-property :title inlinetask) info))
(todo (and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword inlinetask)))
(and todo (org-export-data todo info)))))
(todo-type (org-element-property :todo-type inlinetask))
(tags (and (plist-get info :with-tags)
(org-export-get-tags inlinetask info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority inlinetask))))
;; If `org-texinfo-format-inlinetask-function' is provided, call it
;; with appropriate arguments.
(if (not (eq org-texinfo-format-inlinetask-function 'ignore))
(funcall org-texinfo-format-inlinetask-function
todo todo-type priority title tags contents)
;; Otherwise, use a default template.
(let ((full-title
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "#%c " priority))
title
(when tags (format ":%s:"
(mapconcat 'identity tags ":"))))))
(format (concat "@center %s\n\n"
"%s"
"\n")
full-title contents)))))
;;; Italic
(defun org-texinfo-italic (italic contents info)
"Transcode ITALIC from Org to Texinfo.
CONTENTS is the text with italic markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'italic))
;;; Item
(defun org-texinfo-item (item contents info)
"Transcode an ITEM element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((tag (org-element-property :tag item))
(desc (org-export-data tag info)))
(concat "\n@item " (if tag desc) "\n"
(and contents (org-trim contents)) "\n")))
;;; Keyword
(defun org-texinfo-keyword (keyword contents info)
"Transcode a KEYWORD element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((key (org-element-property :key keyword))
(value (org-element-property :value keyword)))
(cond
((string= key "TEXINFO") value)
((string= key "CINDEX") (format "@cindex %s" value))
((string= key "FINDEX") (format "@findex %s" value))
((string= key "KINDEX") (format "@kindex %s" value))
((string= key "PINDEX") (format "@pindex %s" value))
((string= key "TINDEX") (format "@tindex %s" value))
((string= key "VINDEX") (format "@vindex %s" value)))))
;;; Line Break
(defun org-texinfo-line-break (line-break contents info)
"Transcode a LINE-BREAK object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
"@*\n")
;;; Link
(defun org-texinfo-link (link desc info)
"Transcode a LINK object from Org to Texinfo.
DESC is the description part of the link, or the empty string.
INFO is a plist holding contextual information. See
`org-export-data'."
(let* ((type (org-element-property :type link))
(raw-path (org-element-property :path link))
;; Ensure DESC really exists, or set it to nil.
(desc (and (not (string= desc "")) desc))
(path (cond
((member type '("http" "https" "ftp"))
(concat type ":" raw-path))
((string= type "file")
(if (file-name-absolute-p raw-path)
(concat "file://" (expand-file-name raw-path))
(concat "file://" raw-path)))
(t raw-path)))
(email (if (string= type "mailto")
(let ((text (replace-regexp-in-string
"@" "@@" raw-path)))
(concat text (if desc (concat "," desc))))))
protocol)
(cond
;; Links pointing to a headline: Find destination and build
;; appropriate referencing command.
((member type '("custom-id" "id"))
(let ((destination (org-export-resolve-id-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
((member type '("info"))
(let* ((info-path (split-string path "[:#]"))
(info-manual (car info-path))
(info-node (or (cadr info-path) "top"))
(title (or desc "")))
(format "@ref{%s,%s,,%s,}" info-node title info-manual)))
((member type '("fuzzy"))
(let ((destination (org-export-resolve-fuzzy-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
;; Special case for email addresses
(email
(format "@email{%s}" email))
;; External link with a description part.
((and path desc) (format "@uref{%s,%s}" path desc))
;; External link without a description part.
(path (format "@uref{%s}" path))
;; No path, only description. Try to do something useful.
(t (format org-texinfo-link-with-unknown-path-format desc)))))
;;; Menu
(defun org-texinfo-make-menu (info level)
"Create the menu for inclusion in the texifo document.
INFO is the parsed buffer that contains the headlines. LEVEL
determines whether to make the main menu, or the detailed menu.
This is only used for generating the primary menu. In-Node menus
are generated directly."
(let ((parse (plist-get info :parse-tree)))
(cond
;; Generate the main menu
((eq level 'main) (org-texinfo--build-menu parse 1 info))
;; Generate the detailed (recursive) menu
((eq level 'detailed)
;; Requires recursion
;;(org-texinfo--build-detailed-menu parse top info)
(org-texinfo--build-menu parse 1 info 'detailed)))))
;;; Paragraph
(defun org-texinfo-paragraph (paragraph contents info)
"Transcode a PARAGRAPH element from Org to Texinfo.
CONTENTS is the contents of the paragraph, as a string. INFO is
the plist used as a communication channel."
contents)
;;; Plain List
(defun org-texinfo-plain-list (plain-list contents info)
"Transcode a PLAIN-LIST element from Org to Texinfo.
CONTENTS is the contents of the list. INFO is a plist holding
contextual information."
(let* ((attr (org-export-read-attribute :attr_texinfo plain-list))
(indic (or (plist-get attr :indic)
org-texinfo-def-table-markup))
(type (org-element-property :type plain-list))
(table-type (plist-get attr :table-type))
;; Ensure valid texinfo table type.
(table-type (if (member table-type '("ftable" "vtable")) table-type
"table"))
(list-type (cond
((eq type 'ordered) "enumerate")
((eq type 'unordered) "itemize")
((eq type 'descriptive) table-type))))
(format "@%s%s\n@end %s"
(if (eq type 'descriptive)
(concat list-type " " indic)
list-type)
contents
list-type)))
;;; Plain Text
(defun org-texinfo-plain-text (text info)
"Transcode a TEXT string from Org to Texinfo.
TEXT is the string to transcode. INFO is a plist holding
contextual information."
;; First protect @, { and }.
(let ((output (org-texinfo--sanitize-content text)))
;; Activate smart quotes. Be sure to provide original TEXT string
;; since OUTPUT may have been modified.
(when (plist-get info :with-smart-quotes)
(setq output
(org-export-activate-smart-quotes output :texinfo info text)))
;; LaTeX into @LaTeX{} and TeX into @TeX{}
(let ((case-fold-search nil)
(start 0))
(while (string-match "\\(\\(?:La\\)?TeX\\)" output start)
(setq output (replace-match
(format "@%s{}" (match-string 1 output)) nil t output)
start (match-end 0))))
;; Convert special strings.
(when (plist-get info :with-special-strings)
(while (string-match (regexp-quote "...") output)
(setq output (replace-match "@dots{}" nil t output))))
;; Handle break preservation if required.
(when (plist-get info :preserve-breaks)
(setq output (replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " @*\n" output)))
;; Return value.
output))
;;; Planning
(defun org-texinfo-planning (planning contents info)
"Transcode a PLANNING element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(mapconcat
'identity
(delq nil
(list
(let ((closed (org-element-property :closed planning)))
(when closed
(concat
(format "@strong{%s} " org-closed-string)
(format org-texinfo-inactive-timestamp-format
(org-translate-time
(org-element-property :raw-value closed))))))
(let ((deadline (org-element-property :deadline planning)))
(when deadline
(concat
(format "@strong{%s} " org-deadline-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value deadline))))))
(let ((scheduled (org-element-property :scheduled planning)))
(when scheduled
(concat
(format "@strong{%s} " org-scheduled-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value scheduled))))))))
" ")
"@*"))
;;; Property Drawer
(defun org-texinfo-property-drawer (property-drawer contents info)
"Transcode a PROPERTY-DRAWER element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
;; The property drawer isn't exported but we want separating blank
;; lines nonetheless.
"")
;;; Quote Block
(defun org-texinfo-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((title (org-element-property :name quote-block))
(start-quote (concat "@quotation"
(if title
(format " %s" title)))))
(format "%s\n%s@end quotation" start-quote contents)))
;;; Quote Section
(defun org-texinfo-quote-section (quote-section contents info)
"Transcode a QUOTE-SECTION element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((value (org-remove-indentation
(org-element-property :value quote-section))))
(when value (format "@verbatim\n%s@end verbatim" value))))
;;; Radio Target
(defun org-texinfo-radio-target (radio-target text info)
"Transcode a RADIO-TARGET object from Org to Texinfo.
TEXT is the text of the target. INFO is a plist holding
contextual information."
(format "@anchor{%s}%s"
(org-export-solidify-link-text
(org-element-property :value radio-target))
text))
;;; Section
(defun org-texinfo-section (section contents info)
"Transcode a SECTION element from Org to Texinfo.
CONTENTS holds the contents of the section. INFO is a plist
holding contextual information."
contents)
;;; Special Block
(defun org-texinfo-special-block (special-block contents info)
"Transcode a SPECIAL-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Src Block
(defun org-texinfo-src-block (src-block contents info)
"Transcode a SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((lang (org-element-property :language src-block))
(lisp-p (string-match-p "lisp" lang))
(src-contents (org-texinfo--sanitize-content
(org-export-format-code-default src-block info))))
(cond
;; Case 1. Lisp Block
(lisp-p
(format "@lisp\n%s@end lisp"
src-contents))
;; Case 2. Other blocks
(t
(format "@example\n%s@end example"
src-contents)))))
;;; Statistics Cookie
(defun org-texinfo-statistics-cookie (statistics-cookie contents info)
"Transcode a STATISTICS-COOKIE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(org-element-property :value statistics-cookie))
;;; Subscript
(defun org-texinfo-subscript (subscript contents info)
"Transcode a SUBSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{_%s}" contents))
;;; Superscript
(defun org-texinfo-superscript (superscript contents info)
"Transcode a SUPERSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{^%s}" contents))
;;; Table
;;
;; `org-texinfo-table' is the entry point for table transcoding. It
;; takes care of tables with a "verbatim" attribute. Otherwise, it
;; delegates the job to either `org-texinfo-table--table.el-table' or
;; `org-texinfo-table--org-table' functions, depending of the type of
;; the table.
;;
;; `org-texinfo-table--align-string' is a subroutine used to build
;; alignment string for Org tables.
(defun org-texinfo-table (table contents info)
"Transcode a TABLE element from Org to Texinfo.
CONTENTS is the contents of the table. INFO is a plist holding
contextual information."
(cond
;; Case 1: verbatim table.
((or org-texinfo-tables-verbatim
(let ((attr (mapconcat 'identity
(org-element-property :attr_latex table)
" ")))
(and attr (string-match "\\<verbatim\\>" attr))))
(format "@verbatim \n%s\n@end verbatim"
;; Re-create table, without affiliated keywords.
(org-trim
(org-element-interpret-data
`(table nil ,@(org-element-contents table))))))
;; Case 2: table.el table. Convert it using appropriate tools.
((eq (org-element-property :type table) 'table.el)
(org-texinfo-table--table.el-table table contents info))
;; Case 3: Standard table.
(t (org-texinfo-table--org-table table contents info))))
(defun org-texinfo-table-column-widths (table info)
"Determine the largest table cell in each column to process alignment.
TABLE is the table element to transcode. INFO is a plist used as
a communication channel."
(let* ((rows (org-element-map table 'table-row 'identity info))
(collected (loop for row in rows collect
(org-element-map row 'table-cell 'identity info)))
(number-cells (length (car collected)))
cells counts)
(loop for row in collected do
(push (mapcar (lambda (ref)
(let* ((start (org-element-property :contents-begin ref))
(end (org-element-property :contents-end ref))
(length (- end start)))
length)) row) cells))
(setq cells (org-remove-if 'null cells))
(push (loop for count from 0 to (- number-cells 1) collect
(loop for item in cells collect
(nth count item))) counts)
(mapconcat (lambda (size)
(make-string size ?a)) (mapcar (lambda (ref)
(apply 'max `(,@ref))) (car counts))
"} {")))
(defun org-texinfo-table--org-table (table contents info)
"Return appropriate Texinfo code for an Org table.
TABLE is the table type element to transcode. CONTENTS is its
contents, as a string. INFO is a plist used as a communication
channel.
This function assumes TABLE has `org' as its `:type' attribute."
(let* ((attr (org-export-read-attribute :attr_texinfo table))
(col-width (plist-get attr :columns))
(columns (if col-width
(format "@columnfractions %s"
col-width)
(format "{%s}"
(org-texinfo-table-column-widths
table info)))))
;; Prepare the final format string for the table.
(cond
;; Longtable.
;; Others.
(t (concat
(format "@multitable %s\n%s@end multitable"
columns
contents))))))
(defun org-texinfo-table--table.el-table (table contents info)
"Returns nothing.
Rather than return an invalid table, nothing is returned."
'nil)
;;; Table Cell
(defun org-texinfo-table-cell (table-cell contents info)
"Transcode a TABLE-CELL element from Org to Texinfo.
CONTENTS is the cell contents. INFO is a plist used as
a communication channel."
(concat (if (and contents
org-texinfo-table-scientific-notation
(string-match orgtbl-exp-regexp contents))
;; Use appropriate format string for scientific
;; notation.
(format org-texinfo-table-scientific-notation
(match-string 1 contents)
(match-string 2 contents))
contents)
(when (org-export-get-next-element table-cell info) "\n@tab ")))
;;; Table Row
(defun org-texinfo-table-row (table-row contents info)
"Transcode a TABLE-ROW element from Org to Texinfo.
CONTENTS is the contents of the row. INFO is a plist used as
a communication channel."
;; Rules are ignored since table separators are deduced from
;; borders of the current row.
(when (eq (org-element-property :type table-row) 'standard)
(let ((rowgroup-tag
(cond
;; Case 1: Belongs to second or subsequent rowgroup.
((not (= 1 (org-export-table-row-group table-row info)))
"@item ")
;; Case 2: Row is from first rowgroup. Table has >=1 rowgroups.
((org-export-table-has-header-p
(org-export-get-parent-table table-row) info)
"@headitem ")
;; Case 3: Row is from first and only row group.
(t "@item "))))
(when (eq (org-element-property :type table-row) 'standard)
(concat rowgroup-tag contents "\n")))))
;;; Target
(defun org-texinfo-target (target contents info)
"Transcode a TARGET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@anchor{%s}"
(org-export-solidify-link-text (org-element-property :value target))))
;;; Timestamp
(defun org-texinfo-timestamp (timestamp contents info)
"Transcode a TIMESTAMP object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(let ((value (org-texinfo-plain-text
(org-timestamp-translate timestamp) info)))
(case (org-element-property :type timestamp)
((active active-range)
(format org-texinfo-active-timestamp-format value))
((inactive inactive-range)
(format org-texinfo-inactive-timestamp-format value))
(t (format org-texinfo-diary-timestamp-format value)))))
;;; Verbatim
(defun org-texinfo-verbatim (verbatim contents info)
"Transcode a VERBATIM object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value verbatim) 'verbatim))
;;; Verse Block
(defun org-texinfo-verse-block (verse-block contents info)
"Transcode a VERSE-BLOCK element from Org to Texinfo.
CONTENTS is verse block contents. INFO is a plist holding
contextual information."
;; In a verse environment, add a line break to each newline
;; character and change each white space at beginning of a line
;; into a space of 1 em. Also change each blank line with
;; a vertical space of 1 em.
(progn
(setq contents (replace-regexp-in-string
"^ *\\\\\\\\$" "\\\\vspace*{1em}"
(replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" contents)))
(while (string-match "^[ \t]+" contents)
(let ((new-str (format "\\hspace*{%dem}"
(length (match-string 0 contents)))))
(setq contents (replace-match new-str nil t contents))))
(format "\\begin{verse}\n%s\\end{verse}" contents)))
;;; Interactive functions
(defun org-texinfo-export-to-texinfo
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to a Texinfo file.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
Return output file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist)))
(defun org-texinfo-export-to-info
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to Texinfo then process through to INFO.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
When optional argument PUB-DIR is set, use it as the publishing
directory.
Return INFO file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist
(lambda (file) (org-texinfo-compile file)))))
;;;###autoload
(defun org-texinfo-publish-to-texinfo (plist filename pub-dir)
"Publish an org file to Texinfo.
FILENAME is the filename of the Org file to be published. PLIST
is the property list for the given project. PUB-DIR is the
publishing directory.
Return output file name."
(org-publish-org-to 'texinfo filename ".texi" plist pub-dir))
;;;###autoload
(defun org-texinfo-convert-region-to-texinfo ()
"Assume the current region has org-mode syntax, and convert it to Texinfo.
This can be used in any buffer. For example, you can write an
itemized list in org-mode syntax in an Texinfo buffer and use
this command to convert it."
(interactive)
(org-export-replace-region-by 'texinfo))
(defun org-texinfo-compile (file)
"Compile a texinfo file.
FILE is the name of the file being compiled. Processing is
done through the command specified in `org-texinfo-info-process'.
Return INFO file name or an error if it couldn't be produced."
(let* ((base-name (file-name-sans-extension (file-name-nondirectory file)))
(full-name (file-truename file))
(out-dir (file-name-directory file))
;; Properly set working directory for compilation.
(default-directory (if (file-name-absolute-p file)
(file-name-directory full-name)
default-directory))
errors)
(message (format "Processing Texinfo file %s..." file))
(save-window-excursion
(cond
;; A function is provided: Apply it.
((functionp org-texinfo-info-process)
(funcall org-texinfo-info-process (shell-quote-argument file)))
;; A list is provided: Replace %b, %f and %o with appropriate
;; values in each command before applying it. Output is
;; redirected to "*Org INFO Texinfo Output*" buffer.
((consp org-texinfo-info-process)
(let ((outbuf (get-buffer-create "*Org INFO Texinfo Output*")))
(mapc
(lambda (command)
(shell-command
(replace-regexp-in-string
"%b" (shell-quote-argument base-name)
(replace-regexp-in-string
"%f" (shell-quote-argument full-name)
(replace-regexp-in-string
"%o" (shell-quote-argument out-dir) command t t) t t) t t)
outbuf))
org-texinfo-info-process)
;; Collect standard errors from output buffer.
(setq errors (org-texinfo-collect-errors outbuf))))
(t (error "No valid command to process to Info")))
(let ((infofile (concat out-dir base-name ".info")))
;; Check for process failure. Provide collected errors if
;; possible.
(if (not (file-exists-p infofile))
(error (concat (format "INFO file %s wasn't produced" infofile)
(when errors (concat ": " errors))))
;; Else remove log files, when specified, and signal end of
;; process to user, along with any error encountered.
(when org-texinfo-remove-logfiles
(dolist (ext org-texinfo-logfiles-extensions)
(let ((file (concat out-dir base-name "." ext)))
(when (file-exists-p file) (delete-file file)))))
(message (concat "Process completed"
(if (not errors) "."
(concat " with errors: " errors)))))
;; Return output file name.
infofile))))
(defun org-texinfo-collect-errors (buffer)
"Collect some kind of errors from \"makeinfo\" command output.
BUFFER is the buffer containing output.
Return collected error types as a string, or nil if there was
none."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
;; Find final "makeinfo" run.
(when t
(let ((case-fold-search t)
(errors ""))
(when (save-excursion
(re-search-forward "perhaps incorrect sectioning?" nil t))
(setq errors (concat errors " [incorrect sectioning]")))
(when (save-excursion
(re-search-forward "missing close brace" nil t))
(setq errors (concat errors " [syntax error]")))
(when (save-excursion
(re-search-forward "Unknown command" nil t))
(setq errors (concat errors " [undefined @command]")))
(when (save-excursion
(re-search-forward "No matching @end" nil t))
(setq errors (concat errors " [block incomplete]")))
(when (save-excursion
(re-search-forward "requires a sectioning" nil t))
(setq errors (concat errors " [invalid section command]")))
(when (save-excursion
(re-search-forward "\\[unexpected\]" nil t))
(setq errors (concat errors " [unexpected error]")))
(when (save-excursion
(re-search-forward "misplaced " nil t))
(setq errors (concat errors " [syntax error]")))
(and (org-string-nw-p errors) (org-trim errors)))))))
(provide 'ox-texinfo)
;; Local variables:
;; generated-autoload-file: "org-loaddefs.el"
;; End:
;;; ox-texinfo.el ends here
| true | ;;; ox-texinfo.el --- Texinfo Back-End for Org Export Engine
;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PIathan.leechpepin at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, 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 3 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This library implements a Texinfo back-end for Org generic
;; exporter.
;;
;; To test it, run
;;
;; M-: (org-export-to-buffer 'texinfo "*Test Texinfo*") RET
;;
;; in an Org mode buffer then switch to the buffer to see the Texinfo
;; export. See ox.el for more details on how this exporter works.
;;
;; It introduces nine new buffer keywords: "TEXINFO_CLASS",
;; "TEXINFO_FILENAME", "TEXINFO_HEADER", "TEXINFO_POST_HEADER",
;; "TEXINFO_DIR_CATEGORY", "TEXINFO_DIR_TITLE", "TEXINFO_DIR_DESC"
;; "SUBTITLE" and "SUBAUTHOR".
;;
;; It introduces 1 new headline property keywords:
;; "TEXINFO_MENU_TITLE" for optional menu titles.
;;
;; To include inline code snippets (for example for generating @kbd{}
;; and @key{} commands), the following export-snippet keys are
;; accepted:
;;
;; texinfo
;; info
;;
;; You can add them for export snippets via any of the below:
;;
;; (add-to-list 'org-export-snippet-translation-alist
;; '("info" . "texinfo"))
;;
;;; Code:
(eval-when-compile (require 'cl))
(require 'ox)
(defvar orgtbl-exp-regexp)
;;; Define Back-End
(org-export-define-backend 'texinfo
'((bold . org-texinfo-bold)
(center-block . org-texinfo-center-block)
(clock . org-texinfo-clock)
(code . org-texinfo-code)
(comment . org-texinfo-comment)
(comment-block . org-texinfo-comment-block)
(drawer . org-texinfo-drawer)
(dynamic-block . org-texinfo-dynamic-block)
(entity . org-texinfo-entity)
(example-block . org-texinfo-example-block)
(export-block . org-texinfo-export-block)
(export-snippet . org-texinfo-export-snippet)
(fixed-width . org-texinfo-fixed-width)
(footnote-definition . org-texinfo-footnote-definition)
(footnote-reference . org-texinfo-footnote-reference)
(headline . org-texinfo-headline)
(inline-src-block . org-texinfo-inline-src-block)
(inlinetask . org-texinfo-inlinetask)
(italic . org-texinfo-italic)
(item . org-texinfo-item)
(keyword . org-texinfo-keyword)
(line-break . org-texinfo-line-break)
(link . org-texinfo-link)
(paragraph . org-texinfo-paragraph)
(plain-list . org-texinfo-plain-list)
(plain-text . org-texinfo-plain-text)
(planning . org-texinfo-planning)
(property-drawer . org-texinfo-property-drawer)
(quote-block . org-texinfo-quote-block)
(quote-section . org-texinfo-quote-section)
(radio-target . org-texinfo-radio-target)
(section . org-texinfo-section)
(special-block . org-texinfo-special-block)
(src-block . org-texinfo-src-block)
(statistics-cookie . org-texinfo-statistics-cookie)
(subscript . org-texinfo-subscript)
(superscript . org-texinfo-superscript)
(table . org-texinfo-table)
(table-cell . org-texinfo-table-cell)
(table-row . org-texinfo-table-row)
(target . org-texinfo-target)
(template . org-texinfo-template)
(timestamp . org-texinfo-timestamp)
(verbatim . org-texinfo-verbatim)
(verse-block . org-texinfo-verse-block))
:export-block "TEXINFO"
:filters-alist
'((:filter-headline . org-texinfo-filter-section-blank-lines)
(:filter-section . org-texinfo-filter-section-blank-lines))
:menu-entry
'(?i "Export to Texinfo"
((?t "As TEXI file" org-texinfo-export-to-texinfo)
(?i "As INFO file" org-texinfo-export-to-info)))
:options-alist
'((:texinfo-filename "TEXINFO_FILENAME" nil org-texinfo-filename t)
(:texinfo-class "TEXINFO_CLASS" nil org-texinfo-default-class t)
(:texinfo-header "TEXINFO_HEADER" nil nil newline)
(:texinfo-post-header "TEXINFO_POST_HEADER" nil nil newline)
(:subtitle "SUBTITLE" nil nil newline)
(:subauthor "SUBAUTHOR" nil nil newline)
(:texinfo-dircat "TEXINFO_DIR_CATEGORY" nil nil t)
(:texinfo-dirtitle "TEXINFO_DIR_TITLE" nil nil t)
(:texinfo-dirdesc "TEXINFO_DIR_DESC" nil nil t)))
;;; User Configurable Variables
(defgroup org-export-texinfo nil
"Options for exporting Org mode files to Texinfo."
:tag "Org Export Texinfo"
:version "24.4"
:package-version '(Org . "8.0")
:group 'org-export)
;;; Preamble
(defcustom org-texinfo-filename ""
"Default filename for Texinfo output."
:group 'org-export-texinfo
:type '(string :tag "Export Filename"))
(defcustom org-texinfo-coding-system nil
"Default document encoding for Texinfo output.
If `nil' it will default to `buffer-file-coding-system'."
:group 'org-export-texinfo
:type 'coding-system)
(defcustom org-texinfo-default-class "info"
"The default Texinfo class."
:group 'org-export-texinfo
:type '(string :tag "Texinfo class"))
(defcustom org-texinfo-classes
'(("info"
"\\input texinfo @c -*- texinfo -*-"
("@chapter %s" . "@unnumbered %s")
("@section %s" . "@unnumberedsec %s")
("@subsection %s" . "@unnumberedsubsec %s")
("@subsubsection %s" . "@unnumberedsubsubsec %s")))
"Alist of Texinfo classes and associated header and structure.
If #+Texinfo_CLASS is set in the buffer, use its value and the
associated information. Here is the structure of each cell:
\(class-name
header-string
\(numbered-section . unnumbered-section\)
...\)
The sectioning structure
------------------------
The sectioning structure of the class is given by the elements
following the header string. For each sectioning level, a number
of strings is specified. A %s formatter is mandatory in each
section string and will be replaced by the title of the section.
Instead of a list of sectioning commands, you can also specify
a function name. That function will be called with two
parameters, the \(reduced) level of the headline, and a predicate
non-nil when the headline should be numbered. It must return
a format string in which the section title will be added."
:group 'org-export-texinfo
:type '(repeat
(list (string :tag "Texinfo class")
(string :tag "Texinfo header")
(repeat :tag "Levels" :inline t
(choice
(cons :tag "Heading"
(string :tag " numbered")
(string :tag "unnumbered"))
(function :tag "Hook computing sectioning"))))))
;;; Headline
(defcustom org-texinfo-format-headline-function 'ignore
"Function to format headline text.
This function will be called with 5 arguments:
TODO the todo keyword (string or nil).
TODO-TYPE the type of todo (symbol: `todo', `done', nil)
PRIORITY the priority of the headline (integer or nil)
TEXT the main headline text (string).
TAGS the tags as a list of strings (list of strings or nil).
The function result will be used in the section format string.
As an example, one could set the variable to the following, in
order to reproduce the default set-up:
\(defun org-texinfo-format-headline (todo todo-type priority text tags)
\"Default format function for a headline.\"
\(concat (when todo
\(format \"\\\\textbf{\\\\textsc{\\\\textsf{%s}}} \" todo))
\(when priority
\(format \"\\\\framebox{\\\\#%c} \" priority))
text
\(when tags
\(format \"\\\\hfill{}\\\\textsc{%s}\"
\(mapconcat 'identity tags \":\"))))"
:group 'org-export-texinfo
:type 'function)
;;; Node listing (menu)
(defcustom org-texinfo-node-description-column 32
"Column at which to start the description in the node
listings.
If a node title is greater than this length, the description will
be placed after the end of the title."
:group 'org-export-texinfo
:type 'integer)
;;; Footnotes
;;
;; Footnotes are inserted directly
;;; Timestamps
(defcustom org-texinfo-active-timestamp-format "@emph{%s}"
"A printf format string to be applied to active timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-inactive-timestamp-format "@emph{%s}"
"A printf format string to be applied to inactive timestamps."
:group 'org-export-texinfo
:type 'string)
(defcustom org-texinfo-diary-timestamp-format "@emph{%s}"
"A printf format string to be applied to diary timestamps."
:group 'org-export-texinfo
:type 'string)
;;; Links
(defcustom org-texinfo-link-with-unknown-path-format "@indicateurl{%s}"
"Format string for links with unknown path type."
:group 'org-export-texinfo
:type 'string)
;;; Tables
(defcustom org-texinfo-tables-verbatim nil
"When non-nil, tables are exported verbatim."
:group 'org-export-texinfo
:type 'boolean)
(defcustom org-texinfo-table-scientific-notation "%s\\,(%s)"
"Format string to display numbers in scientific notation.
The format should have \"%s\" twice, for mantissa and exponent
\(i.e. \"%s\\\\times10^{%s}\").
When nil, no transformation is made."
:group 'org-export-texinfo
:type '(choice
(string :tag "Format string")
(const :tag "No formatting")))
(defcustom org-texinfo-def-table-markup "@samp"
"Default setting for @table environments."
:group 'org-export-texinfo
:type 'string)
;;; Text markup
(defcustom org-texinfo-text-markup-alist '((bold . "@strong{%s}")
(code . code)
(italic . "@emph{%s}")
(verbatim . verb)
(comment . "@c %s"))
"Alist of Texinfo expressions to convert text markup.
The key must be a symbol among `bold', `italic' and `comment'.
The value is a formatting string to wrap fontified text with.
Value can also be set to the following symbols: `verb' and
`code'. For the former, Org will use \"@verb\" to
create a format string and select a delimiter character that
isn't in the string. For the latter, Org will use \"@code\"
to typeset and try to protect special characters.
If no association can be found for a given markup, text will be
returned as-is."
:group 'org-export-texinfo
:type 'alist
:options '(bold code italic verbatim comment))
;;; Drawers
(defcustom org-texinfo-format-drawer-function
(lambda (name contents) contents)
"Function called to format a drawer in Texinfo code.
The function must accept two parameters:
NAME the drawer name, like \"LOGBOOK\"
CONTENTS the contents of the drawer.
The function should return the string to be exported.
The default function simply returns the value of CONTENTS."
:group 'org-export-texinfo
:version "24.4"
:package-version '(Org . "8.3")
:type 'function)
;;; Inlinetasks
(defcustom org-texinfo-format-inlinetask-function 'ignore
"Function called to format an inlinetask in Texinfo code.
The function must accept six parameters:
TODO the todo keyword, as a string
TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
PRIORITY the inlinetask priority, as a string
NAME the inlinetask name, as a string.
TAGS the inlinetask tags, as a list of strings.
CONTENTS the contents of the inlinetask, as a string.
The function should return the string to be exported.
For example, the variable could be set to the following function
in order to mimic default behavior:
\(defun org-texinfo-format-inlinetask \(todo type priority name tags contents\)
\"Format an inline task element for Texinfo export.\"
\(let ((full-title
\(concat
\(when todo
\(format \"@strong{%s} \" todo))
\(when priority (format \"#%c \" priority))
title
\(when tags
\(format \":%s:\"
\(mapconcat 'identity tags \":\")))))
\(format (concat \"@center %s\n\n\"
\"%s\"
\"\n\"))
full-title contents))"
:group 'org-export-texinfo
:type 'function)
;;; Src blocks
;;
;; Src Blocks are example blocks, except for LISP
;;; Compilation
(defcustom org-texinfo-info-process
'("makeinfo %f")
"Commands to process a Texinfo file to an INFO file.
This is list of strings, each of them will be given to the shell
as a command. %f in the command will be replaced by the full
file name, %b by the file base name \(i.e without extension) and
%o by the base directory of the file."
:group 'org-export-texinfo
:type '(repeat :tag "Shell command sequence"
(string :tag "Shell command")))
(defcustom org-texinfo-logfiles-extensions
'("aux" "toc" "cp" "fn" "ky" "pg" "tp" "vr")
"The list of file extensions to consider as Texinfo logfiles.
The logfiles will be remove if `org-texinfo-remove-logfiles' is
non-nil."
:group 'org-export-texinfo
:type '(repeat (string :tag "Extension")))
(defcustom org-texinfo-remove-logfiles t
"Non-nil means remove the logfiles produced by compiling a Texinfo file.
By default, logfiles are files with these extensions: .aux, .toc,
.cp, .fn, .ky, .pg and .tp. To define the set of logfiles to remove,
set `org-texinfo-logfiles-extensions'."
:group 'org-export-latex
:type 'boolean)
;;; Constants
(defconst org-texinfo-max-toc-depth 4
"Maximum depth for creation of detailed menu listings. Beyond
this depth Texinfo will not recognize the nodes and will cause
errors. Left as a constant in case this value ever changes.")
(defconst org-texinfo-supported-coding-systems
'("US-ASCII" "UTF-8" "ISO-8859-15" "ISO-8859-1" "ISO-8859-2" "koi8-r" "koi8-u")
"List of coding systems supported by Texinfo, as strings.
Specified coding system will be matched against these strings.
If two strings share the same prefix (e.g. \"ISO-8859-1\" and
\"ISO-8859-15\"), the most specific one has to be listed first.")
;;; Internal Functions
(defun org-texinfo-filter-section-blank-lines (headline back-end info)
"Filter controlling number of blank lines after a section."
(let ((blanks (make-string 2 ?\n)))
(replace-regexp-in-string "\n\\(?:\n[ \t]*\\)*\\'" blanks headline)))
(defun org-texinfo--find-verb-separator (s)
"Return a character not used in string S.
This is used to choose a separator for constructs like \\verb."
(let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
(loop for c across ll
when (not (string-match (regexp-quote (char-to-string c)) s))
return (char-to-string c))))
(defun org-texinfo--make-option-string (options)
"Return a comma separated string of keywords and values.
OPTIONS is an alist where the key is the options keyword as
a string, and the value a list containing the keyword value, or
nil."
(mapconcat (lambda (pair)
(concat (first pair)
(when (> (length (second pair)) 0)
(concat "=" (second pair)))))
options
","))
(defun org-texinfo--text-markup (text markup)
"Format TEXT depending on MARKUP text markup.
See `org-texinfo-text-markup-alist' for details."
(let ((fmt (cdr (assq markup org-texinfo-text-markup-alist))))
(cond
;; No format string: Return raw text.
((not fmt) text)
((eq 'verb fmt)
(let ((separator (org-texinfo--find-verb-separator text)))
(concat "@verb{" separator text separator "}")))
((eq 'code fmt)
(let ((start 0)
(rtn "")
char)
(while (string-match "[@{}]" text)
(setq char (match-string 0 text))
(if (> (match-beginning 0) 0)
(setq rtn (concat rtn (substring text 0 (match-beginning 0)))))
(setq text (substring text (1+ (match-beginning 0))))
(setq char (concat "@" char)
rtn (concat rtn char)))
(setq text (concat rtn text)
fmt "@code{%s}")
(format fmt text)))
;; Else use format string.
(t (format fmt text)))))
(defun org-texinfo--get-node (headline info)
"Return node entry associated to HEADLINE.
INFO is a plist used as a communication channel."
(let ((menu-title (org-export-get-alt-title headline info)))
(org-texinfo--sanitize-menu
(replace-regexp-in-string
"%" "%%"
(if menu-title (org-export-data menu-title info)
(org-texinfo--sanitize-headline
(org-element-property :title headline) info))))))
;;; Headline sanitizing
(defun org-texinfo--sanitize-headline (headline info)
"Remove all formatting from the text of a headline for use in
node and menu listing."
(mapconcat 'identity
(org-texinfo--sanitize-headline-contents headline info) " "))
(defun org-texinfo--sanitize-headline-contents (headline info)
"Retrieve the content of the headline.
Any content that can contain further formatting is checked
recursively, to ensure that nested content is also properly
retrieved."
(loop for contents in headline append
(cond
;; already a string
((stringp contents)
(list (replace-regexp-in-string " $" "" contents)))
;; Is exported as-is (value)
((org-element-map contents '(verbatim code)
(lambda (value) (org-element-property :value value)) info))
;; Has content and recurse into the content
((org-element-contents contents)
(org-texinfo--sanitize-headline-contents
(org-element-contents contents) info)))))
;;; Menu sanitizing
(defun org-texinfo--sanitize-menu (title)
"Remove invalid characters from TITLE for use in menus and
nodes.
Based on Texinfo specifications, the following must be removed:
@ { } ( ) : . ,"
(replace-regexp-in-string "[@{}():,.]" "" title))
;;; Content sanitizing
(defun org-texinfo--sanitize-content (text)
"Ensure characters are properly escaped when used in headlines or blocks.
Escape characters are: @ { }"
(replace-regexp-in-string "\\\([@{}]\\\)" "@\\1" text))
;;; Menu creation
(defun org-texinfo--build-menu (tree level info &optional detailed)
"Create the @menu/@end menu information from TREE at headline
level LEVEL.
TREE contains the parse-tree to work with, either of the entire
document or of a specific parent headline. LEVEL indicates what
level of headlines to look at when generating the menu. INFO is
a plist containing contextual information.
Detailed determines whether to build a single level of menu, or
recurse into all children as well."
(let ((menu (org-texinfo--generate-menu-list tree level info))
output text-menu)
(cond
(detailed
;; Looping is done within the menu generation.
(setq text-menu (org-texinfo--generate-detailed menu level info)))
(t
(setq text-menu (org-texinfo--generate-menu-items menu info))))
(when text-menu
(setq output (org-texinfo--format-menu text-menu))
(mapconcat 'identity output "\n"))))
(defun org-texinfo--generate-detailed (menu level info)
"Generate a detailed listing of all subheadings within MENU starting at LEVEL.
MENU is the parse-tree to work with. LEVEL is the starting level
for the menu headlines and from which recursion occurs. INFO is
a plist containing contextual information."
(when level
(let ((max-depth (min org-texinfo-max-toc-depth
(plist-get info :headline-levels))))
(when (> max-depth level)
(loop for headline in menu append
(let* ((title (org-texinfo--menu-headlines headline info))
;; Create list of menu entries for the next level
(sublist (org-texinfo--generate-menu-list
headline (1+ level) info))
;; Generate the menu items for that level. If
;; there are none omit that heading completely,
;; otherwise join the title to it's related entries.
(submenu (if (org-texinfo--generate-menu-items sublist info)
(append (list title)
(org-texinfo--generate-menu-items sublist info))
'nil))
;; Start the process over the next level down.
(recursion (org-texinfo--generate-detailed sublist (1+ level) info)))
(setq recursion (append submenu recursion))
recursion))))))
(defun org-texinfo--generate-menu-list (tree level info)
"Generate the list of headlines that are within a given level
of the tree for further formatting.
TREE is the parse-tree containing the headlines. LEVEL is the
headline level to generate a list of. INFO is a plist holding
contextual information."
(org-element-map tree 'headline
(lambda (head)
(and (= (org-export-get-relative-level head info) level)
;; Do not take note of footnotes or copying headlines.
(not (org-element-property :COPYING head))
(not (org-element-property :footnote-section-p head))
;; Collect headline.
head))
info))
(defun org-texinfo--generate-menu-items (items info)
"Generate a list of headline information from the listing ITEMS.
ITEMS is a list of the headlines to be converted into entries.
INFO is a plist containing contextual information.
Returns a list containing the following information from each
headline: length, title, description. This is used to format the
menu using `org-texinfo--format-menu'."
(loop for headline in items collect
(let* ((menu-title (org-texinfo--sanitize-menu
(org-export-data
(org-export-get-alt-title headline info)
info)))
(title (org-texinfo--sanitize-menu
(org-texinfo--sanitize-headline
(org-element-property :title headline) info)))
(descr (org-export-data
(org-element-property :DESCRIPTION headline)
info))
(menu-entry (if (string= "" menu-title) title menu-title))
(len (length menu-entry))
(output (list len menu-entry descr)))
output)))
(defun org-texinfo--menu-headlines (headline info)
"Retrieve the title from HEADLINE.
INFO is a plist holding contextual information.
Return the headline as a list of (length title description) with
length of -1 and nil description. This is used in
`org-texinfo--format-menu' to identify headlines as opposed to
entries."
(let ((title (org-export-data
(org-element-property :title headline) info)))
(list -1 title 'nil)))
(defun org-texinfo--format-menu (text-menu)
"Format the TEXT-MENU items to be properly printed in the menu.
Each entry in the menu should be provided as (length title
description).
Headlines in the detailed menu are given length -1 to ensure they
are never confused with other entries. They also have no
description.
Other menu items are output as:
Title:: description
With the spacing between :: and description based on the length
of the longest menu entry."
(let (output)
(setq output
(mapcar (lambda (name)
(let* ((title (nth 1 name))
(desc (nth 2 name))
(length (nth 0 name))
(column (max
;;6 is "* " ":: " for inserted text
length
(-
org-texinfo-node-description-column
6)))
(spacing (- column length)
))
(if (> length -1)
(concat "* " title ":: "
(make-string spacing ?\s)
(if desc
(concat desc)))
(concat "\n" title "\n"))))
text-menu))
output))
;;; Template
(defun org-texinfo-template (contents info)
"Return complete document string after Texinfo conversion.
CONTENTS is the transcoded contents string. INFO is a plist
holding export options."
(let* ((title (org-export-data (plist-get info :title) info))
(info-filename (or (plist-get info :texinfo-filename)
(file-name-nondirectory
(org-export-output-file-name ".info"))))
(author (org-export-data (plist-get info :author) info))
(lang (org-export-data (plist-get info :language) info))
(texinfo-header (plist-get info :texinfo-header))
(texinfo-post-header (plist-get info :texinfo-post-header))
(subtitle (plist-get info :subtitle))
(subauthor (plist-get info :subauthor))
(class (plist-get info :texinfo-class))
(header (nth 1 (assoc class org-texinfo-classes)))
(copying
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (hl) (and (org-element-property :COPYING hl) hl)) info t))
(dircat (plist-get info :texinfo-dircat))
(dirtitle (plist-get info :texinfo-dirtitle))
(dirdesc (plist-get info :texinfo-dirdesc))
;; Spacing to align description (column 32 - 3 for `* ' and
;; `.' in text.
(dirspacing (- 29 (length dirtitle)))
(menu (org-texinfo-make-menu info 'main))
(detail-menu (org-texinfo-make-menu info 'detailed)))
(concat
;; Header
header "\n"
"@c %**start of header\n"
;; Filename and Title
"@setfilename " info-filename "\n"
"@settitle " title "\n"
;; Coding system.
(format
"@documentencoding %s\n"
(catch 'coding-system
(let ((case-fold-search t)
(name (symbol-name (or org-texinfo-coding-system
buffer-file-coding-system))))
(dolist (system org-texinfo-supported-coding-systems "UTF-8")
(when (org-string-match-p (regexp-quote system) name)
(throw 'coding-system system))))))
"\n"
(format "@documentlanguage %s\n" lang)
"\n\n"
"@c Version and Contact Info\n"
"@set AUTHOR " author "\n"
;; Additional Header Options set by `#+TEXINFO_HEADER
(if texinfo-header
(concat "\n"
texinfo-header
"\n"))
"@c %**end of header\n"
"@finalout\n"
"\n\n"
;; Additional Header Options set by #+TEXINFO_POST_HEADER
(if texinfo-post-header
(concat "\n"
texinfo-post-header
"\n"))
;; Copying
"@copying\n"
;; Only export the content of the headline, do not need the
;; initial headline.
(org-export-data (nth 2 copying) info)
"@end copying\n"
"\n\n"
;; Info directory information
;; Only supply if both title and category are provided
(if (and dircat dirtitle)
(concat "@dircategory " dircat "\n"
"@direntry\n"
"* " dirtitle "."
(make-string dirspacing ?\s)
dirdesc "\n"
"@end direntry\n"))
"\n\n"
;; Title
"@titlepage\n"
"@title " title "\n\n"
(if subtitle
(concat "@subtitle " subtitle "\n"))
"@author " author "\n"
(if subauthor
(concat subauthor "\n"))
"\n"
"@c The following two commands start the copyright page.\n"
"@page\n"
"@vskip 0pt plus 1filll\n"
"@insertcopying\n"
"@end titlepage\n\n"
"@c Output the table of contents at the beginning.\n"
"@contents\n\n"
;; Configure Top Node when not for Tex
"@ifnottex\n"
"@node Top\n"
"@top " title " Manual\n"
"@insertcopying\n"
"@end ifnottex\n\n"
;; Do not output menus if they are empty
(if menu
;; Menu
(concat "@menu\n"
menu
"\n\n"
;; Detailed Menu
(if detail-menu
(concat "@detailmenu\n"
" --- The Detailed Node Listing ---\n"
detail-menu
"\n\n"
"@end detailmenu\n"))
"@end menu\n"))
"\n\n"
;; Document's body.
contents
"\n"
;; Creator.
(let ((creator-info (plist-get info :with-creator)))
(cond
((not creator-info) "")
((eq creator-info 'comment)
(format "@c %s\n" (plist-get info :creator)))
(t (concat (plist-get info :creator) "\n"))))
;; Document end.
"\n@bye")))
;;; Transcode Functions
;;; Bold
(defun org-texinfo-bold (bold contents info)
"Transcode BOLD from Org to Texinfo.
CONTENTS is the text with bold markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'bold))
;;; Center Block
(defun org-texinfo-center-block (center-block contents info)
"Transcode a CENTER-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Clock
(defun org-texinfo-clock (clock contents info)
"Transcode a CLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(format "@strong{%s} " org-clock-string)
(format org-texinfo-inactive-timestamp-format
(concat (org-translate-time
(org-element-property :raw-value
(org-element-property :value clock)))
(let ((time (org-element-property :duration clock)))
(and time (format " (%s)" time)))))
"@*"))
;;; Code
(defun org-texinfo-code (code contents info)
"Transcode a CODE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value code) 'code))
;;; Comment
(defun org-texinfo-comment (comment contents info)
"Transcode a COMMENT object from Org to Texinfo.
CONTENTS is the text in the comment. INFO is a plist holding
contextual information."
(org-texinfo--text-markup (org-element-property :value comment) 'comment))
;;; Comment Block
(defun org-texinfo-comment-block (comment-block contents info)
"Transcode a COMMENT-BLOCK object from Org to Texinfo.
CONTENTS is the text within the block. INFO is a plist holding
contextual information."
(format "@ignore\n%s@end ignore" (org-element-property :value comment-block)))
;;; Drawer
(defun org-texinfo-drawer (drawer contents info)
"Transcode a DRAWER element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((name (org-element-property :drawer-name drawer))
(output (funcall org-texinfo-format-drawer-function
name contents)))
output))
;;; Dynamic Block
(defun org-texinfo-dynamic-block (dynamic-block contents info)
"Transcode a DYNAMIC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information. See `org-export-data'."
contents)
;;; Entity
(defun org-texinfo-entity (entity contents info)
"Transcode an ENTITY object from Org to Texinfo.
CONTENTS are the definition itself. INFO is a plist holding
contextual information."
(let ((ent (org-element-property :latex entity)))
(if (org-element-property :latex-math-p entity) (format "@math{%s}" ent) ent)))
;;; Example Block
(defun org-texinfo-example-block (example-block contents info)
"Transcode an EXAMPLE-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@verbatim\n%s@end verbatim"
(org-export-format-code-default example-block info)))
;;; Export Block
(defun org-texinfo-export-block (export-block contents info)
"Transcode a EXPORT-BLOCK element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (string= (org-element-property :type export-block) "TEXINFO")
(org-remove-indentation (org-element-property :value export-block))))
;;; Export Snippet
(defun org-texinfo-export-snippet (export-snippet contents info)
"Transcode a EXPORT-SNIPPET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(when (eq (org-export-snippet-backend export-snippet) 'texinfo)
(org-element-property :value export-snippet)))
;;; Fixed Width
(defun org-texinfo-fixed-width (fixed-width contents info)
"Transcode a FIXED-WIDTH element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(format "@example\n%s\n@end example"
(org-remove-indentation
(org-texinfo--sanitize-content
(org-element-property :value fixed-width)))))
;;; Footnote Reference
;;
(defun org-texinfo-footnote-reference (footnote contents info)
"Create a footnote reference for FOOTNOTE.
FOOTNOTE is the footnote to define. CONTENTS is nil. INFO is a
plist holding contextual information."
(let ((def (org-export-get-footnote-definition footnote info)))
(format "@footnote{%s}"
(org-trim (org-export-data def info)))))
;;; Headline
(defun org-texinfo-headline (headline contents info)
"Transcode a HEADLINE element from Org to Texinfo.
CONTENTS holds the contents of the headline. INFO is a plist
holding contextual information."
(let* ((class (plist-get info :texinfo-class))
(level (org-export-get-relative-level headline info))
(numberedp (org-export-numbered-headline-p headline info))
(class-sectioning (assoc class org-texinfo-classes))
;; Find the index type, if any
(index (org-element-property :INDEX headline))
;; Check if it is an appendix
(appendix (org-element-property :APPENDIX headline))
;; Retrieve headline text
(text (org-texinfo--sanitize-headline
(org-element-property :title headline) info))
;; Create node info, to insert it before section formatting.
;; Use custom menu title if present
(node (format "@node %s\n" (org-texinfo--get-node headline info)))
;; Menus must be generated with first child, otherwise they
;; will not nest properly
(menu (let* ((first (org-export-first-sibling-p headline info))
(parent (org-export-get-parent-headline headline))
(title (org-texinfo--sanitize-headline
(org-element-property :title parent) info))
heading listing
(tree (plist-get info :parse-tree)))
(if first
(org-element-map (plist-get info :parse-tree) 'headline
(lambda (ref)
(if (member title (org-element-property :title ref))
(push ref heading)))
info t))
(setq listing (org-texinfo--build-menu
(car heading) level info))
(if listing
(setq listing (replace-regexp-in-string
"%" "%%" listing)
listing (format
"\n@menu\n%s\n@end menu\n\n" listing))
'nil)))
;; Section formatting will set two placeholders: one for the
;; title and the other for the contents.
(section-fmt
(let ((sec (if (and (symbolp (nth 2 class-sectioning))
(fboundp (nth 2 class-sectioning)))
(funcall (nth 2 class-sectioning) level numberedp)
(nth (1+ level) class-sectioning))))
(cond
;; No section available for that LEVEL.
((not sec) nil)
;; Section format directly returned by a function.
((stringp sec) sec)
;; (numbered-section . unnumbered-section)
((not (consp (cdr sec)))
(cond
;;If an index, always unnumbered
(index
(concat menu node (cdr sec) "\n%s"))
(appendix
(concat menu node (replace-regexp-in-string
"unnumbered"
"appendix"
(cdr sec)) "\n%s"))
;; Otherwise number as needed.
(t
(concat menu node
(funcall
(if numberedp #'car #'cdr) sec) "\n%s")))))))
(todo
(and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword headline)))
(and todo (org-export-data todo info)))))
(todo-type (and todo (org-element-property :todo-type headline)))
(tags (and (plist-get info :with-tags)
(org-export-get-tags headline info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority headline)))
;; Create the headline text along with a no-tag version. The
;; latter is required to remove tags from table of contents.
(full-text (org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text tags)
;; Default formatting.
(concat
(when todo
(format "@strong{%s} " todo))
(when priority (format "@emph{#%s} " priority))
text
(when tags
(format " :%s:"
(mapconcat 'identity tags ":")))))))
(full-text-no-tag
(org-texinfo--sanitize-content
(if (not (eq org-texinfo-format-headline-function 'ignore))
;; User-defined formatting function.
(funcall org-texinfo-format-headline-function
todo todo-type priority text nil)
;; Default formatting.
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "@emph{#%c} " priority))
text))))
(pre-blanks
(make-string (org-element-property :pre-blank headline) 10)))
(cond
;; Case 1: This is a footnote section: ignore it.
((org-element-property :footnote-section-p headline) nil)
;; Case 2: This is the `copying' section: ignore it
;; This is used elsewhere.
((org-element-property :COPYING headline) nil)
;; Case 3: An index. If it matches one of the known indexes,
;; print it as such following the contents, otherwise
;; print the contents and leave the index up to the user.
(index
(format
section-fmt full-text
(concat pre-blanks contents "\n"
(if (member index '("cp" "fn" "ky" "pg" "tp" "vr"))
(concat "@printindex " index)))))
;; Case 4: This is a deep sub-tree: export it as a list item.
;; Also export as items headlines for which no section
;; format has been found.
((or (not section-fmt) (org-export-low-level-p headline info))
;; Build the real contents of the sub-tree.
(let ((low-level-body
(concat
;; If the headline is the first sibling, start a list.
(when (org-export-first-sibling-p headline info)
(format "@%s\n" (if numberedp 'enumerate 'itemize)))
;; Itemize headline
"@item\n" full-text "\n" pre-blanks contents)))
;; If headline is not the last sibling simply return
;; LOW-LEVEL-BODY. Otherwise, also close the list, before any
;; blank line.
(if (not (org-export-last-sibling-p headline info)) low-level-body
(replace-regexp-in-string
"[ \t\n]*\\'"
(format "\n@end %s" (if numberedp 'enumerate 'itemize))
low-level-body))))
;; Case 5: Standard headline. Export it as a section.
(t
(cond
((not (and tags (eq (plist-get info :with-tags) 'not-in-toc)))
;; Regular section. Use specified format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents)))
((string-match "\\`@\\(.*?\\){" section-fmt)
;; If tags should be removed from table of contents, insert
;; title without tags as an alternative heading in sectioning
;; command.
(format (replace-match (concat (match-string 1 section-fmt) "[%s]")
nil nil section-fmt 1)
;; Replace square brackets with parenthesis since
;; square brackets are not supported in optional
;; arguments.
(replace-regexp-in-string
"\\[" "("
(replace-regexp-in-string
"\\]" ")"
full-text-no-tag))
full-text
(concat pre-blanks contents)))
(t
;; Impossible to add an alternative heading. Fallback to
;; regular sectioning format string.
(format (replace-regexp-in-string "%]" "%%]" section-fmt) full-text
(concat pre-blanks contents))))))))
;;; Inline Src Block
(defun org-texinfo-inline-src-block (inline-src-block contents info)
"Transcode an INLINE-SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((code (org-element-property :value inline-src-block))
(separator (org-texinfo--find-verb-separator code)))
(concat "@verb{" separator code separator "}")))
;;; Inlinetask
(defun org-texinfo-inlinetask (inlinetask contents info)
"Transcode an INLINETASK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let ((title (org-export-data (org-element-property :title inlinetask) info))
(todo (and (plist-get info :with-todo-keywords)
(let ((todo (org-element-property :todo-keyword inlinetask)))
(and todo (org-export-data todo info)))))
(todo-type (org-element-property :todo-type inlinetask))
(tags (and (plist-get info :with-tags)
(org-export-get-tags inlinetask info)))
(priority (and (plist-get info :with-priority)
(org-element-property :priority inlinetask))))
;; If `org-texinfo-format-inlinetask-function' is provided, call it
;; with appropriate arguments.
(if (not (eq org-texinfo-format-inlinetask-function 'ignore))
(funcall org-texinfo-format-inlinetask-function
todo todo-type priority title tags contents)
;; Otherwise, use a default template.
(let ((full-title
(concat
(when todo (format "@strong{%s} " todo))
(when priority (format "#%c " priority))
title
(when tags (format ":%s:"
(mapconcat 'identity tags ":"))))))
(format (concat "@center %s\n\n"
"%s"
"\n")
full-title contents)))))
;;; Italic
(defun org-texinfo-italic (italic contents info)
"Transcode ITALIC from Org to Texinfo.
CONTENTS is the text with italic markup. INFO is a plist holding
contextual information."
(org-texinfo--text-markup contents 'italic))
;;; Item
(defun org-texinfo-item (item contents info)
"Transcode an ITEM element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((tag (org-element-property :tag item))
(desc (org-export-data tag info)))
(concat "\n@item " (if tag desc) "\n"
(and contents (org-trim contents)) "\n")))
;;; Keyword
(defun org-texinfo-keyword (keyword contents info)
"Transcode a KEYWORD element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((key (org-element-property :key keyword))
(value (org-element-property :value keyword)))
(cond
((string= key "TEXINFO") value)
((string= key "CINDEX") (format "@cindex %s" value))
((string= key "FINDEX") (format "@findex %s" value))
((string= key "KINDEX") (format "@kindex %s" value))
((string= key "PINDEX") (format "@pindex %s" value))
((string= key "TINDEX") (format "@tindex %s" value))
((string= key "VINDEX") (format "@vindex %s" value)))))
;;; Line Break
(defun org-texinfo-line-break (line-break contents info)
"Transcode a LINE-BREAK object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
"@*\n")
;;; Link
(defun org-texinfo-link (link desc info)
"Transcode a LINK object from Org to Texinfo.
DESC is the description part of the link, or the empty string.
INFO is a plist holding contextual information. See
`org-export-data'."
(let* ((type (org-element-property :type link))
(raw-path (org-element-property :path link))
;; Ensure DESC really exists, or set it to nil.
(desc (and (not (string= desc "")) desc))
(path (cond
((member type '("http" "https" "ftp"))
(concat type ":" raw-path))
((string= type "file")
(if (file-name-absolute-p raw-path)
(concat "file://" (expand-file-name raw-path))
(concat "file://" raw-path)))
(t raw-path)))
(email (if (string= type "mailto")
(let ((text (replace-regexp-in-string
"@" "@@" raw-path)))
(concat text (if desc (concat "," desc))))))
protocol)
(cond
;; Links pointing to a headline: Find destination and build
;; appropriate referencing command.
((member type '("custom-id" "id"))
(let ((destination (org-export-resolve-id-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
((member type '("info"))
(let* ((info-path (split-string path "[:#]"))
(info-manual (car info-path))
(info-node (or (cadr info-path) "top"))
(title (or desc "")))
(format "@ref{%s,%s,,%s,}" info-node title info-manual)))
((member type '("fuzzy"))
(let ((destination (org-export-resolve-fuzzy-link link info)))
(case (org-element-type destination)
;; Id link points to an external file.
(plain-text
(if desc (format "@uref{file://%s,%s}" destination desc)
(format "@uref{file://%s}" destination)))
;; LINK points to a headline. Use the headline as the NODE target
(headline
(format "@ref{%s,%s}"
(org-texinfo--get-node destination info)
(or desc "")))
(otherwise
(let ((path (org-export-solidify-link-text path)))
(if (not desc) (format "@ref{%s}" path)
(format "@ref{%s,,%s}" path desc)))))))
;; Special case for email addresses
(email
(format "@email{%s}" email))
;; External link with a description part.
((and path desc) (format "@uref{%s,%s}" path desc))
;; External link without a description part.
(path (format "@uref{%s}" path))
;; No path, only description. Try to do something useful.
(t (format org-texinfo-link-with-unknown-path-format desc)))))
;;; Menu
(defun org-texinfo-make-menu (info level)
"Create the menu for inclusion in the texifo document.
INFO is the parsed buffer that contains the headlines. LEVEL
determines whether to make the main menu, or the detailed menu.
This is only used for generating the primary menu. In-Node menus
are generated directly."
(let ((parse (plist-get info :parse-tree)))
(cond
;; Generate the main menu
((eq level 'main) (org-texinfo--build-menu parse 1 info))
;; Generate the detailed (recursive) menu
((eq level 'detailed)
;; Requires recursion
;;(org-texinfo--build-detailed-menu parse top info)
(org-texinfo--build-menu parse 1 info 'detailed)))))
;;; Paragraph
(defun org-texinfo-paragraph (paragraph contents info)
"Transcode a PARAGRAPH element from Org to Texinfo.
CONTENTS is the contents of the paragraph, as a string. INFO is
the plist used as a communication channel."
contents)
;;; Plain List
(defun org-texinfo-plain-list (plain-list contents info)
"Transcode a PLAIN-LIST element from Org to Texinfo.
CONTENTS is the contents of the list. INFO is a plist holding
contextual information."
(let* ((attr (org-export-read-attribute :attr_texinfo plain-list))
(indic (or (plist-get attr :indic)
org-texinfo-def-table-markup))
(type (org-element-property :type plain-list))
(table-type (plist-get attr :table-type))
;; Ensure valid texinfo table type.
(table-type (if (member table-type '("ftable" "vtable")) table-type
"table"))
(list-type (cond
((eq type 'ordered) "enumerate")
((eq type 'unordered) "itemize")
((eq type 'descriptive) table-type))))
(format "@%s%s\n@end %s"
(if (eq type 'descriptive)
(concat list-type " " indic)
list-type)
contents
list-type)))
;;; Plain Text
(defun org-texinfo-plain-text (text info)
"Transcode a TEXT string from Org to Texinfo.
TEXT is the string to transcode. INFO is a plist holding
contextual information."
;; First protect @, { and }.
(let ((output (org-texinfo--sanitize-content text)))
;; Activate smart quotes. Be sure to provide original TEXT string
;; since OUTPUT may have been modified.
(when (plist-get info :with-smart-quotes)
(setq output
(org-export-activate-smart-quotes output :texinfo info text)))
;; LaTeX into @LaTeX{} and TeX into @TeX{}
(let ((case-fold-search nil)
(start 0))
(while (string-match "\\(\\(?:La\\)?TeX\\)" output start)
(setq output (replace-match
(format "@%s{}" (match-string 1 output)) nil t output)
start (match-end 0))))
;; Convert special strings.
(when (plist-get info :with-special-strings)
(while (string-match (regexp-quote "...") output)
(setq output (replace-match "@dots{}" nil t output))))
;; Handle break preservation if required.
(when (plist-get info :preserve-breaks)
(setq output (replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " @*\n" output)))
;; Return value.
output))
;;; Planning
(defun org-texinfo-planning (planning contents info)
"Transcode a PLANNING element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(concat
"@noindent"
(mapconcat
'identity
(delq nil
(list
(let ((closed (org-element-property :closed planning)))
(when closed
(concat
(format "@strong{%s} " org-closed-string)
(format org-texinfo-inactive-timestamp-format
(org-translate-time
(org-element-property :raw-value closed))))))
(let ((deadline (org-element-property :deadline planning)))
(when deadline
(concat
(format "@strong{%s} " org-deadline-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value deadline))))))
(let ((scheduled (org-element-property :scheduled planning)))
(when scheduled
(concat
(format "@strong{%s} " org-scheduled-string)
(format org-texinfo-active-timestamp-format
(org-translate-time
(org-element-property :raw-value scheduled))))))))
" ")
"@*"))
;;; Property Drawer
(defun org-texinfo-property-drawer (property-drawer contents info)
"Transcode a PROPERTY-DRAWER element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
;; The property drawer isn't exported but we want separating blank
;; lines nonetheless.
"")
;;; Quote Block
(defun org-texinfo-quote-block (quote-block contents info)
"Transcode a QUOTE-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist
holding contextual information."
(let* ((title (org-element-property :name quote-block))
(start-quote (concat "@quotation"
(if title
(format " %s" title)))))
(format "%s\n%s@end quotation" start-quote contents)))
;;; Quote Section
(defun org-texinfo-quote-section (quote-section contents info)
"Transcode a QUOTE-SECTION element from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(let ((value (org-remove-indentation
(org-element-property :value quote-section))))
(when value (format "@verbatim\n%s@end verbatim" value))))
;;; Radio Target
(defun org-texinfo-radio-target (radio-target text info)
"Transcode a RADIO-TARGET object from Org to Texinfo.
TEXT is the text of the target. INFO is a plist holding
contextual information."
(format "@anchor{%s}%s"
(org-export-solidify-link-text
(org-element-property :value radio-target))
text))
;;; Section
(defun org-texinfo-section (section contents info)
"Transcode a SECTION element from Org to Texinfo.
CONTENTS holds the contents of the section. INFO is a plist
holding contextual information."
contents)
;;; Special Block
(defun org-texinfo-special-block (special-block contents info)
"Transcode a SPECIAL-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the block. INFO is a plist used
as a communication channel."
contents)
;;; Src Block
(defun org-texinfo-src-block (src-block contents info)
"Transcode a SRC-BLOCK element from Org to Texinfo.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information."
(let* ((lang (org-element-property :language src-block))
(lisp-p (string-match-p "lisp" lang))
(src-contents (org-texinfo--sanitize-content
(org-export-format-code-default src-block info))))
(cond
;; Case 1. Lisp Block
(lisp-p
(format "@lisp\n%s@end lisp"
src-contents))
;; Case 2. Other blocks
(t
(format "@example\n%s@end example"
src-contents)))))
;;; Statistics Cookie
(defun org-texinfo-statistics-cookie (statistics-cookie contents info)
"Transcode a STATISTICS-COOKIE object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual information."
(org-element-property :value statistics-cookie))
;;; Subscript
(defun org-texinfo-subscript (subscript contents info)
"Transcode a SUBSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{_%s}" contents))
;;; Superscript
(defun org-texinfo-superscript (superscript contents info)
"Transcode a SUPERSCRIPT object from Org to Texinfo.
CONTENTS is the contents of the object. INFO is a plist holding
contextual information."
(format "@math{^%s}" contents))
;;; Table
;;
;; `org-texinfo-table' is the entry point for table transcoding. It
;; takes care of tables with a "verbatim" attribute. Otherwise, it
;; delegates the job to either `org-texinfo-table--table.el-table' or
;; `org-texinfo-table--org-table' functions, depending of the type of
;; the table.
;;
;; `org-texinfo-table--align-string' is a subroutine used to build
;; alignment string for Org tables.
(defun org-texinfo-table (table contents info)
"Transcode a TABLE element from Org to Texinfo.
CONTENTS is the contents of the table. INFO is a plist holding
contextual information."
(cond
;; Case 1: verbatim table.
((or org-texinfo-tables-verbatim
(let ((attr (mapconcat 'identity
(org-element-property :attr_latex table)
" ")))
(and attr (string-match "\\<verbatim\\>" attr))))
(format "@verbatim \n%s\n@end verbatim"
;; Re-create table, without affiliated keywords.
(org-trim
(org-element-interpret-data
`(table nil ,@(org-element-contents table))))))
;; Case 2: table.el table. Convert it using appropriate tools.
((eq (org-element-property :type table) 'table.el)
(org-texinfo-table--table.el-table table contents info))
;; Case 3: Standard table.
(t (org-texinfo-table--org-table table contents info))))
(defun org-texinfo-table-column-widths (table info)
"Determine the largest table cell in each column to process alignment.
TABLE is the table element to transcode. INFO is a plist used as
a communication channel."
(let* ((rows (org-element-map table 'table-row 'identity info))
(collected (loop for row in rows collect
(org-element-map row 'table-cell 'identity info)))
(number-cells (length (car collected)))
cells counts)
(loop for row in collected do
(push (mapcar (lambda (ref)
(let* ((start (org-element-property :contents-begin ref))
(end (org-element-property :contents-end ref))
(length (- end start)))
length)) row) cells))
(setq cells (org-remove-if 'null cells))
(push (loop for count from 0 to (- number-cells 1) collect
(loop for item in cells collect
(nth count item))) counts)
(mapconcat (lambda (size)
(make-string size ?a)) (mapcar (lambda (ref)
(apply 'max `(,@ref))) (car counts))
"} {")))
(defun org-texinfo-table--org-table (table contents info)
"Return appropriate Texinfo code for an Org table.
TABLE is the table type element to transcode. CONTENTS is its
contents, as a string. INFO is a plist used as a communication
channel.
This function assumes TABLE has `org' as its `:type' attribute."
(let* ((attr (org-export-read-attribute :attr_texinfo table))
(col-width (plist-get attr :columns))
(columns (if col-width
(format "@columnfractions %s"
col-width)
(format "{%s}"
(org-texinfo-table-column-widths
table info)))))
;; Prepare the final format string for the table.
(cond
;; Longtable.
;; Others.
(t (concat
(format "@multitable %s\n%s@end multitable"
columns
contents))))))
(defun org-texinfo-table--table.el-table (table contents info)
"Returns nothing.
Rather than return an invalid table, nothing is returned."
'nil)
;;; Table Cell
(defun org-texinfo-table-cell (table-cell contents info)
"Transcode a TABLE-CELL element from Org to Texinfo.
CONTENTS is the cell contents. INFO is a plist used as
a communication channel."
(concat (if (and contents
org-texinfo-table-scientific-notation
(string-match orgtbl-exp-regexp contents))
;; Use appropriate format string for scientific
;; notation.
(format org-texinfo-table-scientific-notation
(match-string 1 contents)
(match-string 2 contents))
contents)
(when (org-export-get-next-element table-cell info) "\n@tab ")))
;;; Table Row
(defun org-texinfo-table-row (table-row contents info)
"Transcode a TABLE-ROW element from Org to Texinfo.
CONTENTS is the contents of the row. INFO is a plist used as
a communication channel."
;; Rules are ignored since table separators are deduced from
;; borders of the current row.
(when (eq (org-element-property :type table-row) 'standard)
(let ((rowgroup-tag
(cond
;; Case 1: Belongs to second or subsequent rowgroup.
((not (= 1 (org-export-table-row-group table-row info)))
"@item ")
;; Case 2: Row is from first rowgroup. Table has >=1 rowgroups.
((org-export-table-has-header-p
(org-export-get-parent-table table-row) info)
"@headitem ")
;; Case 3: Row is from first and only row group.
(t "@item "))))
(when (eq (org-element-property :type table-row) 'standard)
(concat rowgroup-tag contents "\n")))))
;;; Target
(defun org-texinfo-target (target contents info)
"Transcode a TARGET object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(format "@anchor{%s}"
(org-export-solidify-link-text (org-element-property :value target))))
;;; Timestamp
(defun org-texinfo-timestamp (timestamp contents info)
"Transcode a TIMESTAMP object from Org to Texinfo.
CONTENTS is nil. INFO is a plist holding contextual
information."
(let ((value (org-texinfo-plain-text
(org-timestamp-translate timestamp) info)))
(case (org-element-property :type timestamp)
((active active-range)
(format org-texinfo-active-timestamp-format value))
((inactive inactive-range)
(format org-texinfo-inactive-timestamp-format value))
(t (format org-texinfo-diary-timestamp-format value)))))
;;; Verbatim
(defun org-texinfo-verbatim (verbatim contents info)
"Transcode a VERBATIM object from Org to Texinfo.
CONTENTS is nil. INFO is a plist used as a communication
channel."
(org-texinfo--text-markup (org-element-property :value verbatim) 'verbatim))
;;; Verse Block
(defun org-texinfo-verse-block (verse-block contents info)
"Transcode a VERSE-BLOCK element from Org to Texinfo.
CONTENTS is verse block contents. INFO is a plist holding
contextual information."
;; In a verse environment, add a line break to each newline
;; character and change each white space at beginning of a line
;; into a space of 1 em. Also change each blank line with
;; a vertical space of 1 em.
(progn
(setq contents (replace-regexp-in-string
"^ *\\\\\\\\$" "\\\\vspace*{1em}"
(replace-regexp-in-string
"\\(\\\\\\\\\\)?[ \t]*\n" " \\\\\\\\\n" contents)))
(while (string-match "^[ \t]+" contents)
(let ((new-str (format "\\hspace*{%dem}"
(length (match-string 0 contents)))))
(setq contents (replace-match new-str nil t contents))))
(format "\\begin{verse}\n%s\\end{verse}" contents)))
;;; Interactive functions
(defun org-texinfo-export-to-texinfo
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to a Texinfo file.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
Return output file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist)))
(defun org-texinfo-export-to-info
(&optional async subtreep visible-only body-only ext-plist)
"Export current buffer to Texinfo then process through to INFO.
If narrowing is active in the current buffer, only export its
narrowed part.
If a region is active, export that region.
A non-nil optional argument ASYNC means the process should happen
asynchronously. The resulting file should be accessible through
the `org-export-stack' interface.
When optional argument SUBTREEP is non-nil, export the sub-tree
at point, extracting information from the headline properties
first.
When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.
When optional argument BODY-ONLY is non-nil, only write code
between \"\\begin{document}\" and \"\\end{document}\".
EXT-PLIST, when provided, is a property list with external
parameters overriding Org default settings, but still inferior to
file-local settings.
When optional argument PUB-DIR is set, use it as the publishing
directory.
Return INFO file's name."
(interactive)
(let ((outfile (org-export-output-file-name ".texi" subtreep))
(org-export-coding-system `,org-texinfo-coding-system))
(org-export-to-file 'texinfo outfile
async subtreep visible-only body-only ext-plist
(lambda (file) (org-texinfo-compile file)))))
;;;###autoload
(defun org-texinfo-publish-to-texinfo (plist filename pub-dir)
"Publish an org file to Texinfo.
FILENAME is the filename of the Org file to be published. PLIST
is the property list for the given project. PUB-DIR is the
publishing directory.
Return output file name."
(org-publish-org-to 'texinfo filename ".texi" plist pub-dir))
;;;###autoload
(defun org-texinfo-convert-region-to-texinfo ()
"Assume the current region has org-mode syntax, and convert it to Texinfo.
This can be used in any buffer. For example, you can write an
itemized list in org-mode syntax in an Texinfo buffer and use
this command to convert it."
(interactive)
(org-export-replace-region-by 'texinfo))
(defun org-texinfo-compile (file)
"Compile a texinfo file.
FILE is the name of the file being compiled. Processing is
done through the command specified in `org-texinfo-info-process'.
Return INFO file name or an error if it couldn't be produced."
(let* ((base-name (file-name-sans-extension (file-name-nondirectory file)))
(full-name (file-truename file))
(out-dir (file-name-directory file))
;; Properly set working directory for compilation.
(default-directory (if (file-name-absolute-p file)
(file-name-directory full-name)
default-directory))
errors)
(message (format "Processing Texinfo file %s..." file))
(save-window-excursion
(cond
;; A function is provided: Apply it.
((functionp org-texinfo-info-process)
(funcall org-texinfo-info-process (shell-quote-argument file)))
;; A list is provided: Replace %b, %f and %o with appropriate
;; values in each command before applying it. Output is
;; redirected to "*Org INFO Texinfo Output*" buffer.
((consp org-texinfo-info-process)
(let ((outbuf (get-buffer-create "*Org INFO Texinfo Output*")))
(mapc
(lambda (command)
(shell-command
(replace-regexp-in-string
"%b" (shell-quote-argument base-name)
(replace-regexp-in-string
"%f" (shell-quote-argument full-name)
(replace-regexp-in-string
"%o" (shell-quote-argument out-dir) command t t) t t) t t)
outbuf))
org-texinfo-info-process)
;; Collect standard errors from output buffer.
(setq errors (org-texinfo-collect-errors outbuf))))
(t (error "No valid command to process to Info")))
(let ((infofile (concat out-dir base-name ".info")))
;; Check for process failure. Provide collected errors if
;; possible.
(if (not (file-exists-p infofile))
(error (concat (format "INFO file %s wasn't produced" infofile)
(when errors (concat ": " errors))))
;; Else remove log files, when specified, and signal end of
;; process to user, along with any error encountered.
(when org-texinfo-remove-logfiles
(dolist (ext org-texinfo-logfiles-extensions)
(let ((file (concat out-dir base-name "." ext)))
(when (file-exists-p file) (delete-file file)))))
(message (concat "Process completed"
(if (not errors) "."
(concat " with errors: " errors)))))
;; Return output file name.
infofile))))
(defun org-texinfo-collect-errors (buffer)
"Collect some kind of errors from \"makeinfo\" command output.
BUFFER is the buffer containing output.
Return collected error types as a string, or nil if there was
none."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
;; Find final "makeinfo" run.
(when t
(let ((case-fold-search t)
(errors ""))
(when (save-excursion
(re-search-forward "perhaps incorrect sectioning?" nil t))
(setq errors (concat errors " [incorrect sectioning]")))
(when (save-excursion
(re-search-forward "missing close brace" nil t))
(setq errors (concat errors " [syntax error]")))
(when (save-excursion
(re-search-forward "Unknown command" nil t))
(setq errors (concat errors " [undefined @command]")))
(when (save-excursion
(re-search-forward "No matching @end" nil t))
(setq errors (concat errors " [block incomplete]")))
(when (save-excursion
(re-search-forward "requires a sectioning" nil t))
(setq errors (concat errors " [invalid section command]")))
(when (save-excursion
(re-search-forward "\\[unexpected\]" nil t))
(setq errors (concat errors " [unexpected error]")))
(when (save-excursion
(re-search-forward "misplaced " nil t))
(setq errors (concat errors " [syntax error]")))
(and (org-string-nw-p errors) (org-trim errors)))))))
(provide 'ox-texinfo)
;; Local variables:
;; generated-autoload-file: "org-loaddefs.el"
;; End:
;;; ox-texinfo.el ends here
|
[
{
"context": "urce erlang documentation.\n\n;; Copyright 2012-2013 Thomas Järvstrand <tjarvstrand@gmail.com>\n\n;; Author: Thomas Järvst",
"end": 107,
"score": 0.9998968243598938,
"start": 90,
"tag": "NAME",
"value": "Thomas Järvstrand"
},
{
"context": "ation.\n\n;; Copyright 2012-2013 Thomas Järvstrand <tjarvstrand@gmail.com>\n\n;; Author: Thomas Järvstrand <thomas.jarvstrand",
"end": 130,
"score": 0.9999308586120605,
"start": 109,
"tag": "EMAIL",
"value": "tjarvstrand@gmail.com"
},
{
"context": "mas Järvstrand <tjarvstrand@gmail.com>\n\n;; Author: Thomas Järvstrand <thomas.jarvstrand@gmail.com>\n;; Keywords: erlang",
"end": 161,
"score": 0.9998931884765625,
"start": 144,
"tag": "NAME",
"value": "Thomas Järvstrand"
},
{
"context": "vstrand@gmail.com>\n\n;; Author: Thomas Järvstrand <thomas.jarvstrand@gmail.com>\n;; Keywords: erlang\n;; This file is not part of ",
"end": 190,
"score": 0.999930202960968,
"start": 163,
"tag": "EMAIL",
"value": "thomas.jarvstrand@gmail.com"
}
] | .emacs.d/elpa/edts-20210630.1626/elisp/edts/edts-doc.el | AeroNotix/dotfiles | 5 | ;;; edts-doc.el --- Find and read in-source erlang documentation.
;; Copyright 2012-2013 Thomas Järvstrand <tjarvstrand@gmail.com>
;; Author: Thomas Järvstrand <thomas.jarvstrand@gmail.com>
;; Keywords: erlang
;; This file is not part of GNU Emacs.
;;
;; This file is part of EDTS.
;;
;; EDTS is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; EDTS 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 Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with EDTS. If not, see <http://www.gnu.org/licenses/>.
(require 'dash)
(defun edts-doc-spec-regexp (function arity)
(format
(concat
"^-spec[[:space:]\n]*\\(%s[[:space:]\n]*(%s)[[:space:]\n]*->"
"[[:space:]\n]*[[:ascii:]]+?\\.\\)")
function (edts-argument-regexp arity)))
(defun edts-doc-any-function-regexp ()
"Return a regexp matching the whole function (heads and body) of any
complete function."
(format
"^%s[[:space:]\n]*([[:ascii:]]??*)[[:space:]\n]*->[[:ascii:]]+?*\\."
erlang-atom-regexp))
(defun edts-doc-extract-function-information-from-source (source function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in SOURCE."
(with-temp-buffer
(insert-file-contents source)
(edts-doc-extract-function-information function arity)))
(defun edts-doc-extract-function-information (function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in current buffer."
(save-excursion
(edts-search-function function arity)
(let* ((end (point))
(re (edts-doc-any-function-regexp))
(start (or (and (re-search-backward re nil t) (match-end 0)) 0))
(spec (edts-doc-extract-spec start end function arity))
(doc (edts-doc-extract-doc start end))
(info (s-join "\n\n" (-non-nil (list spec doc)))))
(unless (s-blank? info)
info))))
(defun edts-doc-extract-spec (start end function arity)
"Extract spec for FUNCTION/ARITY from source in current buffer. Search
is bounded by START and END."
(goto-char start)
(when (re-search-forward (edts-doc-spec-regexp function arity) end t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}p\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1)))))
(defun edts-doc-extract-doc (start end)
"Extract documentation from source. Search is bounded by
START and END."
(goto-char start)
(let ((re "^%+\s*@doc\\([[:ascii:]]+?\\)\\(\n[^%]\\|@end\\)"))
(when (re-search-forward re (1+ end) t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1))))))
(provide 'edts-doc)
| 8287 | ;;; edts-doc.el --- Find and read in-source erlang documentation.
;; Copyright 2012-2013 <NAME> <<EMAIL>>
;; Author: <NAME> <<EMAIL>>
;; Keywords: erlang
;; This file is not part of GNU Emacs.
;;
;; This file is part of EDTS.
;;
;; EDTS is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; EDTS 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 Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with EDTS. If not, see <http://www.gnu.org/licenses/>.
(require 'dash)
(defun edts-doc-spec-regexp (function arity)
(format
(concat
"^-spec[[:space:]\n]*\\(%s[[:space:]\n]*(%s)[[:space:]\n]*->"
"[[:space:]\n]*[[:ascii:]]+?\\.\\)")
function (edts-argument-regexp arity)))
(defun edts-doc-any-function-regexp ()
"Return a regexp matching the whole function (heads and body) of any
complete function."
(format
"^%s[[:space:]\n]*([[:ascii:]]??*)[[:space:]\n]*->[[:ascii:]]+?*\\."
erlang-atom-regexp))
(defun edts-doc-extract-function-information-from-source (source function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in SOURCE."
(with-temp-buffer
(insert-file-contents source)
(edts-doc-extract-function-information function arity)))
(defun edts-doc-extract-function-information (function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in current buffer."
(save-excursion
(edts-search-function function arity)
(let* ((end (point))
(re (edts-doc-any-function-regexp))
(start (or (and (re-search-backward re nil t) (match-end 0)) 0))
(spec (edts-doc-extract-spec start end function arity))
(doc (edts-doc-extract-doc start end))
(info (s-join "\n\n" (-non-nil (list spec doc)))))
(unless (s-blank? info)
info))))
(defun edts-doc-extract-spec (start end function arity)
"Extract spec for FUNCTION/ARITY from source in current buffer. Search
is bounded by START and END."
(goto-char start)
(when (re-search-forward (edts-doc-spec-regexp function arity) end t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}p\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1)))))
(defun edts-doc-extract-doc (start end)
"Extract documentation from source. Search is bounded by
START and END."
(goto-char start)
(let ((re "^%+\s*@doc\\([[:ascii:]]+?\\)\\(\n[^%]\\|@end\\)"))
(when (re-search-forward re (1+ end) t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1))))))
(provide 'edts-doc)
| true | ;;; edts-doc.el --- Find and read in-source erlang documentation.
;; Copyright 2012-2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: erlang
;; This file is not part of GNU Emacs.
;;
;; This file is part of EDTS.
;;
;; EDTS is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Lesser General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; EDTS 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 Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with EDTS. If not, see <http://www.gnu.org/licenses/>.
(require 'dash)
(defun edts-doc-spec-regexp (function arity)
(format
(concat
"^-spec[[:space:]\n]*\\(%s[[:space:]\n]*(%s)[[:space:]\n]*->"
"[[:space:]\n]*[[:ascii:]]+?\\.\\)")
function (edts-argument-regexp arity)))
(defun edts-doc-any-function-regexp ()
"Return a regexp matching the whole function (heads and body) of any
complete function."
(format
"^%s[[:space:]\n]*([[:ascii:]]??*)[[:space:]\n]*->[[:ascii:]]+?*\\."
erlang-atom-regexp))
(defun edts-doc-extract-function-information-from-source (source function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in SOURCE."
(with-temp-buffer
(insert-file-contents source)
(edts-doc-extract-function-information function arity)))
(defun edts-doc-extract-function-information (function arity)
"Extract information (spec and comments) about FUNCTION/ARITY from
source in current buffer."
(save-excursion
(edts-search-function function arity)
(let* ((end (point))
(re (edts-doc-any-function-regexp))
(start (or (and (re-search-backward re nil t) (match-end 0)) 0))
(spec (edts-doc-extract-spec start end function arity))
(doc (edts-doc-extract-doc start end))
(info (s-join "\n\n" (-non-nil (list spec doc)))))
(unless (s-blank? info)
info))))
(defun edts-doc-extract-spec (start end function arity)
"Extract spec for FUNCTION/ARITY from source in current buffer. Search
is bounded by START and END."
(goto-char start)
(when (re-search-forward (edts-doc-spec-regexp function arity) end t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}p\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1)))))
(defun edts-doc-extract-doc (start end)
"Extract documentation from source. Search is bounded by
START and END."
(goto-char start)
(let ((re "^%+\s*@doc\\([[:ascii:]]+?\\)\\(\n[^%]\\|@end\\)"))
(when (re-search-forward re (1+ end) t)
(replace-regexp-in-string
"\\([[:space:]]*%*[[:space:]]+\\)\\|\\([[:space:]]\{2,\}\\)+"
" "
(buffer-substring (match-beginning 1) (match-end 1))))))
(provide 'edts-doc)
|
[
{
"context": " If not, see http://magit.vc/authors.\n\n;; Author: Marius Vollmer <marius.vollmer@gmail.com>\n;; Maintainer: Jonas B",
"end": 307,
"score": 0.9998895525932312,
"start": 293,
"tag": "NAME",
"value": "Marius Vollmer"
},
{
"context": "p://magit.vc/authors.\n\n;; Author: Marius Vollmer <marius.vollmer@gmail.com>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li",
"end": 333,
"score": 0.9999314546585083,
"start": 309,
"tag": "EMAIL",
"value": "marius.vollmer@gmail.com"
},
{
"context": " Vollmer <marius.vollmer@gmail.com>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>\n;;\tKyle Meyer <kyle@kyl",
"end": 365,
"score": 0.9998862743377686,
"start": 350,
"tag": "NAME",
"value": "Jonas Bernoulli"
},
{
"context": "ollmer@gmail.com>\n;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>\n;;\tKyle Meyer <kyle@kyleam.com>\n;;\tNoam P",
"end": 383,
"score": 0.9999305009841919,
"start": 367,
"tag": "EMAIL",
"value": "jonas@bernoul.li"
},
{
"context": "Maintainer: Jonas Bernoulli <jonas@bernoul.li>\n;;\tKyle Meyer <kyle@kyleam.com>\n;;\tNoam Postavsky <np",
"end": 398,
"score": 0.9998980760574341,
"start": 388,
"tag": "NAME",
"value": "Kyle Meyer"
},
{
"context": "ernoulli <jonas@bernoul.li>\n;;\tKyle Meyer <kyle@kyleam.com>\n;;\tNoam Postavsky <npostavs@users.sourceforge",
"end": 422,
"score": 0.9999234676361084,
"start": 407,
"tag": "EMAIL",
"value": "kyle@kyleam.com"
},
{
"context": "oul.li>\n;;\tKyle Meyer <kyle@kyleam.com>\n;;\tNoam Postavsky <npostavs@users.sourceforge.net>\n;; Former-Mai",
"end": 441,
"score": 0.9998882412910461,
"start": 427,
"tag": "NAME",
"value": "Noam Postavsky"
},
{
"context": "er <kyle@kyleam.com>\n;;\tNoam Postavsky <npostavs@users.sourceforge.net>\n;; Former-Maintainers:\n;;\tNicolas Dudebout <nic",
"end": 476,
"score": 0.9999321103096008,
"start": 446,
"tag": "EMAIL",
"value": "npostavs@users.sourceforge.net"
},
{
"context": "@users.sourceforge.net>\n;; Former-Maintainers:\n;;\tNicolas Dudebout <nicolas.dudebout@gatech.edu>\n;;\tPeter J. Weisbe",
"end": 520,
"score": 0.9998892545700073,
"start": 504,
"tag": "NAME",
"value": "Nicolas Dudebout"
},
{
"context": "net>\n;; Former-Maintainers:\n;;\tNicolas Dudebout <nicolas.dudebout@gatech.edu>\n;;\tPeter J. Weisberg <pj@irregularexpressions.ne",
"end": 550,
"score": 0.9999354481697083,
"start": 523,
"tag": "EMAIL",
"value": "nicolas.dudebout@gatech.edu"
},
{
"context": "icolas Dudebout <nicolas.dudebout@gatech.edu>\n;;\tPeter J. Weisberg <pj@irregularexpressions.net>\n;;\tPhil Jackson ",
"end": 572,
"score": 0.9998747706413269,
"start": 555,
"tag": "NAME",
"value": "Peter J. Weisberg"
},
{
"context": "icolas.dudebout@gatech.edu>\n;;\tPeter J. Weisberg <pj@irregularexpressions.net>\n;;\tPhil Jackson <phil@shellarchive.co.uk>\n;",
"end": 601,
"score": 0.9999365210533142,
"start": 574,
"tag": "EMAIL",
"value": "pj@irregularexpressions.net"
},
{
"context": "eter J. Weisberg <pj@irregularexpressions.net>\n;;\tPhil Jackson <phil@shellarchive.co.uk>\n;;\tRémi Vanicat ",
"end": 618,
"score": 0.9998750686645508,
"start": 606,
"tag": "NAME",
"value": "Phil Jackson"
},
{
"context": "j@irregularexpressions.net>\n;;\tPhil Jackson <phil@shellarchive.co.uk>\n;;\tRémi Vanicat <vanicat@debian.org>\n;;\tYan",
"end": 648,
"score": 0.9999375939369202,
"start": 625,
"tag": "EMAIL",
"value": "phil@shellarchive.co.uk"
},
{
"context": ";;\tPhil Jackson <phil@shellarchive.co.uk>\n;;\tRémi Vanicat <vanicat@debian.org>\n;;\tYann Hodique <y",
"end": 665,
"score": 0.9998860359191895,
"start": 653,
"tag": "NAME",
"value": "Rémi Vanicat"
},
{
"context": " <phil@shellarchive.co.uk>\n;;\tRémi Vanicat <vanicat@debian.org>\n;;\tYann Hodique <yann.hodique@gmail.com>\n\n;",
"end": 690,
"score": 0.9999326467514038,
"start": 672,
"tag": "EMAIL",
"value": "vanicat@debian.org"
},
{
"context": ".uk>\n;;\tRémi Vanicat <vanicat@debian.org>\n;;\tYann Hodique <yann.hodique@gmail.com>\n\n;; Keywords: git t",
"end": 707,
"score": 0.9998838305473328,
"start": 695,
"tag": "NAME",
"value": "Yann Hodique"
},
{
"context": "t <vanicat@debian.org>\n;;\tYann Hodique <yann.hodique@gmail.com>\n\n;; Keywords: git tools vc\n;; Homepage: https://",
"end": 736,
"score": 0.999932587146759,
"start": 714,
"tag": "EMAIL",
"value": "yann.hodique@gmail.com"
},
{
"context": "nset $GIT_DIR (was %S). See \\\nhttps://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike\" val))\n ",
"end": 22178,
"score": 0.9996325373649597,
"start": 22173,
"tag": "USERNAME",
"value": "magit"
},
{
"context": "GIT_WORK_TREE (was %S). See \\\nhttps://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike\" val))\n ",
"end": 22382,
"score": 0.999643087387085,
"start": 22377,
"tag": "USERNAME",
"value": "magit"
}
] | emacs.d/elpa/magit-20210405.40/magit.el | farynaio/dot-env | 0 | ;;; magit.el --- A Git porcelain inside Emacs -*- lexical-binding: t; coding: utf-8 -*-
;; Copyright (C) 2008-2021 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: Marius Vollmer <marius.vollmer@gmail.com>
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>
;; Kyle Meyer <kyle@kyleam.com>
;; Noam Postavsky <npostavs@users.sourceforge.net>
;; Former-Maintainers:
;; Nicolas Dudebout <nicolas.dudebout@gatech.edu>
;; Peter J. Weisberg <pj@irregularexpressions.net>
;; Phil Jackson <phil@shellarchive.co.uk>
;; Rémi Vanicat <vanicat@debian.org>
;; Yann Hodique <yann.hodique@gmail.com>
;; Keywords: git tools vc
;; Homepage: https://github.com/magit/magit
;; Magit requires at least GNU Emacs 25.1 and Git 2.2.0.
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; Magit is an interface to the version control system Git,
;; implemented as an Emacs package. Magit aspires to be a complete
;; Git porcelain. While we cannot (yet) claim, that Magit wraps and
;; improves upon each and every Git command, it is complete enough to
;; allow even experienced Git users to perform almost all of their
;; daily version control tasks directly from within Emacs. While many
;; fine Git clients exist, only Magit and Git itself deserve to be
;; called porcelains.
;;; Code:
(require 'magit-core)
(require 'magit-diff)
(require 'magit-log)
(require 'magit-wip)
(require 'magit-apply)
(require 'magit-repos)
(require 'git-commit)
(require 'format-spec)
(require 'package nil t) ; used in `magit-version'
(require 'with-editor)
(defconst magit--minimal-git "2.2.0")
(defconst magit--minimal-emacs "25.1")
;;; Faces
(defface magit-header-line
'((t :inherit magit-section-heading))
"Face for the `header-line' in some Magit modes.
Note that some modes, such as `magit-log-select-mode', have their
own faces for the `header-line', or for parts of the
`header-line'."
:group 'magit-faces)
(defface magit-header-line-key
'((t :inherit font-lock-builtin-face))
"Face for keys in the `header-line'."
:group 'magit-faces)
(defface magit-dimmed
'((((class color) (background light)) :foreground "grey50")
(((class color) (background dark)) :foreground "grey50"))
"Face for text that shouldn't stand out."
:group 'magit-faces)
(defface magit-hash
'((((class color) (background light)) :foreground "grey60")
(((class color) (background dark)) :foreground "grey40"))
"Face for the sha1 part of the log output."
:group 'magit-faces)
(defface magit-tag
'((((class color) (background light)) :foreground "Goldenrod4")
(((class color) (background dark)) :foreground "LightGoldenrod2"))
"Face for tag labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote
'((((class color) (background light)) :foreground "DarkOliveGreen4")
(((class color) (background dark)) :foreground "DarkSeaGreen2"))
"Face for remote branch head labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote-head
'((((class color) (background light)) :inherit magit-branch-remote :box t)
(((class color) (background dark)) :inherit magit-branch-remote :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-local
'((((class color) (background light)) :foreground "SkyBlue4")
(((class color) (background dark)) :foreground "LightSkyBlue1"))
"Face for local branches."
:group 'magit-faces)
(defface magit-branch-current
'((((class color) (background light)) :inherit magit-branch-local :box t)
(((class color) (background dark)) :inherit magit-branch-local :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-upstream
'((t :slant italic))
"Face for upstream branch.
This face is only used in logs and it gets combined
with `magit-branch-local', `magit-branch-remote'
and/or `magit-branch-remote-head'."
:group 'magit-faces)
(defface magit-head
'((((class color) (background light)) :inherit magit-branch-local)
(((class color) (background dark)) :inherit magit-branch-local))
"Face for the symbolic ref `HEAD'."
:group 'magit-faces)
(defface magit-refname
'((((class color) (background light)) :foreground "grey30")
(((class color) (background dark)) :foreground "grey80"))
"Face for refnames without a dedicated face."
:group 'magit-faces)
(defface magit-refname-stash
'((t :inherit magit-refname))
"Face for stash refnames."
:group 'magit-faces)
(defface magit-refname-wip
'((t :inherit magit-refname))
"Face for wip refnames."
:group 'magit-faces)
(defface magit-refname-pullreq
'((t :inherit magit-refname))
"Face for pullreq refnames."
:group 'magit-faces)
(defface magit-keyword
'((t :inherit font-lock-string-face))
"Face for parts of commit messages inside brackets."
:group 'magit-faces)
(defface magit-keyword-squash
'((t :inherit font-lock-warning-face))
"Face for squash! and fixup! keywords in commit messages."
:group 'magit-faces)
(defface magit-signature-good
'((t :foreground "green"))
"Face for good signatures."
:group 'magit-faces)
(defface magit-signature-bad
'((t :foreground "red" :weight bold))
"Face for bad signatures."
:group 'magit-faces)
(defface magit-signature-untrusted
'((t :foreground "medium aquamarine"))
"Face for good untrusted signatures."
:group 'magit-faces)
(defface magit-signature-expired
'((t :foreground "orange"))
"Face for signatures that have expired."
:group 'magit-faces)
(defface magit-signature-expired-key
'((t :inherit magit-signature-expired))
"Face for signatures made by an expired key."
:group 'magit-faces)
(defface magit-signature-revoked
'((t :foreground "violet red"))
"Face for signatures made by a revoked key."
:group 'magit-faces)
(defface magit-signature-error
'((t :foreground "light blue"))
"Face for signatures that cannot be checked (e.g. missing key)."
:group 'magit-faces)
(defface magit-cherry-unmatched
'((t :foreground "cyan"))
"Face for unmatched cherry commits."
:group 'magit-faces)
(defface magit-cherry-equivalent
'((t :foreground "magenta"))
"Face for equivalent cherry commits."
:group 'magit-faces)
(defface magit-filename
'((t :weight normal))
"Face for filenames."
:group 'magit-faces)
;;; Global Bindings
;;;###autoload
(define-obsolete-variable-alias 'global-magit-file-mode
'magit-define-global-key-bindings "Magit 3.0.0")
;;;###autoload
(defcustom magit-define-global-key-bindings t
"Whether to bind some Magit commands in the global keymap.
If this variable is non-nil, then the following bindings may
be added to the global keymap. The default is t.
key binding
--- -------
C-x g magit-status
C-x M-g magit-dispatch
C-c M-g magit-file-dispatch
These bindings may be added when `after-init-hook' is called.
Each binding is added if and only if at that time no other key
is bound to the same command and no other command is bound to
the same key. In other words we try to avoid adding bindings
that are unnecessary, as well as bindings that conflict with
other bindings.
Adding the above bindings is delayed until `after-init-hook'
is called to allow users to set the variable anywhere in their
init file (without having to make sure to do so before `magit'
is loaded or autoloaded) and to increase the likelihood that
all the potentially conflicting user bindings have already
been added.
Setting this variable after the hook has already been called
has no effect.
We recommend that you bind \"C-c g\" instead of \"C-c M-g\" to
`magit-file-dispatch'. The former is a much better binding
but the \"C-c <letter>\" namespace is strictly reserved for
users; preventing Magit from using it by default.
Also see info node `(magit)Commands for Buffers Visiting Files'."
:package-version '(magit . "3.0.0")
:group 'magit-essentials
:type 'boolean)
;;;###autoload
(progn
(defun magit-maybe-define-global-key-bindings ()
(when magit-define-global-key-bindings
(let ((map (current-global-map)))
(dolist (elt '(("C-x g" . magit-status)
("C-x M-g" . magit-dispatch)
("C-c M-g" . magit-file-dispatch)))
(let ((key (kbd (car elt)))
(def (cdr elt)))
(unless (or (lookup-key map key)
(where-is-internal def (make-sparse-keymap) t))
(define-key map key def)))))))
(if after-init-time
(magit-maybe-define-global-key-bindings)
(add-hook 'after-init-hook 'magit-maybe-define-global-key-bindings t)))
;;; Dispatch Popup
;;;###autoload (autoload 'magit-dispatch "magit" nil t)
(transient-define-prefix magit-dispatch ()
"Invoke a Magit command from a list of available commands."
:info-manual "(magit)Top"
["Transient and dwim commands"
[("A" "Apply" magit-cherry-pick)
("b" "Branch" magit-branch)
("B" "Bisect" magit-bisect)
("c" "Commit" magit-commit)
("C" "Clone" magit-clone)
("d" "Diff" magit-diff)
("D" "Diff (change)" magit-diff-refresh)
("e" "Ediff (dwim)" magit-ediff-dwim)
("E" "Ediff" magit-ediff)]
[("f" "Fetch" magit-fetch)
("F" "Pull" magit-pull)
("I" "Init" magit-init)
("l" "Log" magit-log)
("L" "Log (change)" magit-log-refresh)
("m" "Merge" magit-merge)
("M" "Remote" magit-remote)
("o" "Submodule" magit-submodule)
("O" "Subtree" magit-subtree)]
[("P" "Push" magit-push)
("r" "Rebase" magit-rebase)
("t" "Tag" magit-tag)
("T" "Note" magit-notes)
("V" "Revert" magit-revert)
("w" "Apply patches" magit-am)
("W" "Format patches" magit-patch)
("X" "Reset" magit-reset)]
[("y" "Show Refs" magit-show-refs)
("Y" "Cherries" magit-cherry)
("z" "Stash" magit-stash)
("!" "Run" magit-run)
("%" "Worktree" magit-worktree)]]
["Applying changes"
:if-derived magit-mode
[("a" "Apply" magit-apply)
("v" "Reverse" magit-reverse)
("k" "Discard" magit-discard)]
[("s" "Stage" magit-stage)
("u" "Unstage" magit-unstage)]
[("S" "Stage all" magit-stage-modified)
("U" "Unstage all" magit-unstage-all)]]
["Essential commands"
:if-derived magit-mode
("g" " refresh current buffer" magit-refresh)
("<tab>" " toggle section at point" magit-section-toggle)
("<return>" "visit thing at point" magit-visit-thing)
("C-h m" " show all key bindings" describe-mode)])
;;; Git Popup
(defcustom magit-shell-command-verbose-prompt t
"Whether to show the working directory when reading a command.
This affects `magit-git-command', `magit-git-command-topdir',
`magit-shell-command', and `magit-shell-command-topdir'."
:package-version '(magit . "2.11.0")
:group 'magit-commands
:type 'boolean)
(defvar magit-git-command-history nil)
;;;###autoload (autoload 'magit-run "magit" nil t)
(transient-define-prefix magit-run ()
"Run git or another command, or launch a graphical utility."
[["Run git subcommand"
("!" "in repository root" magit-git-command-topdir)
("p" "in working directory" magit-git-command)]
["Run shell command"
("s" "in repository root" magit-shell-command-topdir)
("S" "in working directory" magit-shell-command)]
["Launch"
("k" "gitk" magit-run-gitk)
("a" "gitk --all" magit-run-gitk-all)
("b" "gitk --branches" magit-run-gitk-branches)
("g" "git gui" magit-run-git-gui)]])
;;;###autoload
(defun magit-git-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
With a prefix argument COMMAND is run in the top-level directory
of the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command nil "git ")))
(magit--shell-command command))
;;;###autoload
(defun magit-git-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
COMMAND is run in the top-level directory of the current
working tree."
(interactive (list (magit-read-shell-command t "git ")))
(magit--shell-command command (magit-toplevel)))
;;;###autoload
(defun magit-shell-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. With a
prefix argument COMMAND is run in the top-level directory of
the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command)))
(magit--shell-command command))
;;;###autoload
(defun magit-shell-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. COMMAND
is run in the top-level directory of the current working tree."
(interactive (list (magit-read-shell-command t)))
(magit--shell-command command (magit-toplevel)))
(defun magit--shell-command (command &optional directory)
(let ((default-directory (or directory default-directory))
(process-environment process-environment))
(push "GIT_PAGER=cat" process-environment)
(magit-start-process shell-file-name nil
shell-command-switch command))
(magit-process-buffer))
(defun magit-read-shell-command (&optional toplevel initial-input)
(let ((default-directory
(if (or toplevel current-prefix-arg)
(or (magit-toplevel)
(magit--not-inside-repository-error))
default-directory)))
(read-shell-command (if magit-shell-command-verbose-prompt
(format "Async shell command in %s: "
(abbreviate-file-name default-directory))
"Async shell command: ")
initial-input 'magit-git-command-history)))
;;; Font-Lock Keywords
(defconst magit-font-lock-keywords
(eval-when-compile
`((,(concat "(\\(magit-define-section-jumper\\)\\_>"
"[ \t'\(]*"
"\\(\\(?:\\sw\\|\\s_\\)+\\)?")
(1 'font-lock-keyword-face)
(2 'font-lock-function-name-face nil t))
(,(concat "(" (regexp-opt '("magit-insert-section"
"magit-section-case"
"magit-bind-match-strings"
"magit-with-temp-index"
"magit-with-blob"
"magit-with-toplevel") t)
"\\_>")
. 1))))
(font-lock-add-keywords 'emacs-lisp-mode magit-font-lock-keywords)
;;; Version
(defvar magit-version 'undefined
"The version of Magit that you're using.
Use the function by the same name instead of this variable.")
;;;###autoload
(defun magit-version (&optional print-dest)
"Return the version of Magit currently in use.
If optional argument PRINT-DEST is non-nil, output
stream (interactively, the echo area, or the current buffer with
a prefix argument), also print the used versions of Magit, Git,
and Emacs to it."
(interactive (list (if current-prefix-arg (current-buffer) t)))
(let ((magit-git-global-arguments nil)
(toplib (or load-file-name buffer-file-name))
debug)
(unless (and toplib
(equal (file-name-nondirectory toplib) "magit.el"))
(setq toplib (locate-library "magit.el")))
(setq toplib (and toplib (magit--straight-chase-links toplib)))
(push toplib debug)
(when toplib
(let* ((topdir (file-name-directory toplib))
(gitdir (expand-file-name
".git" (file-name-directory
(directory-file-name topdir))))
(static (locate-library "magit-version.el" nil (list topdir)))
(static (and static (magit--straight-chase-links static))))
(or (progn
(push 'repo debug)
(when (and (file-exists-p gitdir)
;; It is a repo, but is it the Magit repo?
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(push t debug)
;; Inside the repo the version file should only exist
;; while running make.
(when (and static (not noninteractive))
(ignore-errors (delete-file static)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "describe"
"--tags" "--dirty" "--always")))))
(progn
(push 'static debug)
(when (and static (file-exists-p static))
(push t debug)
(load-file static)
magit-version))
(when (featurep 'package)
(push 'elpa debug)
(ignore-errors
(--when-let (assq 'magit package-alist)
(push t debug)
(setq magit-version
(and (fboundp 'package-desc-version)
(package-version-join
(package-desc-version (cadr it))))))))
(progn
(push 'dirname debug)
(let ((dirname (file-name-nondirectory
(directory-file-name topdir))))
(when (string-match "\\`magit-\\([0-9].*\\)" dirname)
(setq magit-version (match-string 1 dirname)))))
;; If all else fails, just report the commit hash. It's
;; better than nothing and we cannot do better in the case
;; of e.g. a shallow clone.
(progn
(push 'hash debug)
;; Same check as above to see if it's really the Magit repo.
(when (and (file-exists-p gitdir)
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "rev-parse" "HEAD"))))))))
(if (stringp magit-version)
(when print-dest
(princ (format "Magit %s, Git %s, Emacs %s, %s"
(or magit-version "(unknown)")
(or (let ((magit-git-debug
(lambda (err)
(display-warning '(magit git)
err :error))))
(magit-git-version t))
"(unknown)")
emacs-version
system-type)
print-dest))
(setq debug (reverse debug))
(setq magit-version 'error)
(when magit-version
(push magit-version debug))
(unless (equal (getenv "CI") "true")
;; The repository is a sparse clone.
(message "Cannot determine Magit's version %S" debug)))
magit-version))
;;; Debugging Tools
(defun magit-debug-git-executable ()
"Display a buffer with information about `magit-git-executable'.
See info node `(magit)Debugging Tools' for more information."
(interactive)
(with-current-buffer (get-buffer-create "*magit-git-debug*")
(pop-to-buffer (current-buffer))
(erase-buffer)
(insert (concat
(format "magit-git-executable: %S" magit-git-executable)
(and (not (file-name-absolute-p magit-git-executable))
(format " [%S]" (executable-find magit-git-executable)))
(format " (%s)\n"
(let* ((errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))
(insert (format "exec-path: %S\n" exec-path))
(--when-let (cl-set-difference
(-filter #'file-exists-p (remq nil (parse-colon-path
(getenv "PATH"))))
(-filter #'file-exists-p (remq nil exec-path))
:test #'file-equal-p)
(insert (format " entries in PATH, but not in exec-path: %S\n" it)))
(dolist (execdir exec-path)
(insert (format " %s (%s)\n" execdir (car (file-attributes execdir))))
(when (file-directory-p execdir)
(dolist (exec (directory-files
execdir t (concat
"\\`git" (regexp-opt exec-suffixes) "\\'")))
(insert (format " %s (%s)\n" exec
(let* ((magit-git-executable exec)
(errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))))))
;;; Startup Asserts
(defun magit-startup-asserts ()
(when-let ((val (getenv "GIT_DIR")))
(setenv "GIT_DIR")
(message "Magit unset $GIT_DIR (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(when-let ((val (getenv "GIT_WORK_TREE")))
(setenv "GIT_WORK_TREE")
(message "Magit unset $GIT_WORK_TREE (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(let ((version (magit-git-version)))
(when (and version
(version< version magit--minimal-git)
(not (equal (getenv "CI") "true")))
(display-warning 'magit (format "\
Magit requires Git >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.
If you use Tramp to work inside remote Git repositories, then you
have to make sure a suitable Git is used on the remote machines
too.\n" magit--minimal-git version) :error)))
(when (version< emacs-version magit--minimal-emacs)
(display-warning 'magit (format "\
Magit requires Emacs >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.\n"
magit--minimal-emacs emacs-version)
:error)))
;;; Loading Libraries
(provide 'magit)
(cl-eval-when (load eval)
(require 'magit-status)
(require 'magit-refs)
(require 'magit-files)
(require 'magit-reset)
(require 'magit-branch)
(require 'magit-merge)
(require 'magit-tag)
(require 'magit-worktree)
(require 'magit-notes)
(require 'magit-sequence)
(require 'magit-commit)
(require 'magit-remote)
(require 'magit-clone)
(require 'magit-fetch)
(require 'magit-pull)
(require 'magit-push)
(require 'magit-bisect)
(require 'magit-stash)
(require 'magit-blame)
(require 'magit-obsolete)
(require 'magit-submodule)
(unless (load "magit-autoloads" t t)
(require 'magit-patch)
(require 'magit-subtree)
(require 'magit-ediff)
(require 'magit-gitignore)
(require 'magit-extras)
(require 'git-rebase)
(require 'magit-imenu)
(require 'magit-bookmark)))
(eval-after-load 'bookmark
'(require 'magit-bookmark))
(if after-init-time
(progn (magit-startup-asserts)
(magit-version))
(add-hook 'after-init-hook #'magit-startup-asserts t)
(add-hook 'after-init-hook #'magit-version t))
;;; magit.el ends here
| 34597 | ;;; magit.el --- A Git porcelain inside Emacs -*- lexical-binding: t; coding: utf-8 -*-
;; Copyright (C) 2008-2021 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; Former-Maintainers:
;; <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; Keywords: git tools vc
;; Homepage: https://github.com/magit/magit
;; Magit requires at least GNU Emacs 25.1 and Git 2.2.0.
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; Magit is an interface to the version control system Git,
;; implemented as an Emacs package. Magit aspires to be a complete
;; Git porcelain. While we cannot (yet) claim, that Magit wraps and
;; improves upon each and every Git command, it is complete enough to
;; allow even experienced Git users to perform almost all of their
;; daily version control tasks directly from within Emacs. While many
;; fine Git clients exist, only Magit and Git itself deserve to be
;; called porcelains.
;;; Code:
(require 'magit-core)
(require 'magit-diff)
(require 'magit-log)
(require 'magit-wip)
(require 'magit-apply)
(require 'magit-repos)
(require 'git-commit)
(require 'format-spec)
(require 'package nil t) ; used in `magit-version'
(require 'with-editor)
(defconst magit--minimal-git "2.2.0")
(defconst magit--minimal-emacs "25.1")
;;; Faces
(defface magit-header-line
'((t :inherit magit-section-heading))
"Face for the `header-line' in some Magit modes.
Note that some modes, such as `magit-log-select-mode', have their
own faces for the `header-line', or for parts of the
`header-line'."
:group 'magit-faces)
(defface magit-header-line-key
'((t :inherit font-lock-builtin-face))
"Face for keys in the `header-line'."
:group 'magit-faces)
(defface magit-dimmed
'((((class color) (background light)) :foreground "grey50")
(((class color) (background dark)) :foreground "grey50"))
"Face for text that shouldn't stand out."
:group 'magit-faces)
(defface magit-hash
'((((class color) (background light)) :foreground "grey60")
(((class color) (background dark)) :foreground "grey40"))
"Face for the sha1 part of the log output."
:group 'magit-faces)
(defface magit-tag
'((((class color) (background light)) :foreground "Goldenrod4")
(((class color) (background dark)) :foreground "LightGoldenrod2"))
"Face for tag labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote
'((((class color) (background light)) :foreground "DarkOliveGreen4")
(((class color) (background dark)) :foreground "DarkSeaGreen2"))
"Face for remote branch head labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote-head
'((((class color) (background light)) :inherit magit-branch-remote :box t)
(((class color) (background dark)) :inherit magit-branch-remote :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-local
'((((class color) (background light)) :foreground "SkyBlue4")
(((class color) (background dark)) :foreground "LightSkyBlue1"))
"Face for local branches."
:group 'magit-faces)
(defface magit-branch-current
'((((class color) (background light)) :inherit magit-branch-local :box t)
(((class color) (background dark)) :inherit magit-branch-local :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-upstream
'((t :slant italic))
"Face for upstream branch.
This face is only used in logs and it gets combined
with `magit-branch-local', `magit-branch-remote'
and/or `magit-branch-remote-head'."
:group 'magit-faces)
(defface magit-head
'((((class color) (background light)) :inherit magit-branch-local)
(((class color) (background dark)) :inherit magit-branch-local))
"Face for the symbolic ref `HEAD'."
:group 'magit-faces)
(defface magit-refname
'((((class color) (background light)) :foreground "grey30")
(((class color) (background dark)) :foreground "grey80"))
"Face for refnames without a dedicated face."
:group 'magit-faces)
(defface magit-refname-stash
'((t :inherit magit-refname))
"Face for stash refnames."
:group 'magit-faces)
(defface magit-refname-wip
'((t :inherit magit-refname))
"Face for wip refnames."
:group 'magit-faces)
(defface magit-refname-pullreq
'((t :inherit magit-refname))
"Face for pullreq refnames."
:group 'magit-faces)
(defface magit-keyword
'((t :inherit font-lock-string-face))
"Face for parts of commit messages inside brackets."
:group 'magit-faces)
(defface magit-keyword-squash
'((t :inherit font-lock-warning-face))
"Face for squash! and fixup! keywords in commit messages."
:group 'magit-faces)
(defface magit-signature-good
'((t :foreground "green"))
"Face for good signatures."
:group 'magit-faces)
(defface magit-signature-bad
'((t :foreground "red" :weight bold))
"Face for bad signatures."
:group 'magit-faces)
(defface magit-signature-untrusted
'((t :foreground "medium aquamarine"))
"Face for good untrusted signatures."
:group 'magit-faces)
(defface magit-signature-expired
'((t :foreground "orange"))
"Face for signatures that have expired."
:group 'magit-faces)
(defface magit-signature-expired-key
'((t :inherit magit-signature-expired))
"Face for signatures made by an expired key."
:group 'magit-faces)
(defface magit-signature-revoked
'((t :foreground "violet red"))
"Face for signatures made by a revoked key."
:group 'magit-faces)
(defface magit-signature-error
'((t :foreground "light blue"))
"Face for signatures that cannot be checked (e.g. missing key)."
:group 'magit-faces)
(defface magit-cherry-unmatched
'((t :foreground "cyan"))
"Face for unmatched cherry commits."
:group 'magit-faces)
(defface magit-cherry-equivalent
'((t :foreground "magenta"))
"Face for equivalent cherry commits."
:group 'magit-faces)
(defface magit-filename
'((t :weight normal))
"Face for filenames."
:group 'magit-faces)
;;; Global Bindings
;;;###autoload
(define-obsolete-variable-alias 'global-magit-file-mode
'magit-define-global-key-bindings "Magit 3.0.0")
;;;###autoload
(defcustom magit-define-global-key-bindings t
"Whether to bind some Magit commands in the global keymap.
If this variable is non-nil, then the following bindings may
be added to the global keymap. The default is t.
key binding
--- -------
C-x g magit-status
C-x M-g magit-dispatch
C-c M-g magit-file-dispatch
These bindings may be added when `after-init-hook' is called.
Each binding is added if and only if at that time no other key
is bound to the same command and no other command is bound to
the same key. In other words we try to avoid adding bindings
that are unnecessary, as well as bindings that conflict with
other bindings.
Adding the above bindings is delayed until `after-init-hook'
is called to allow users to set the variable anywhere in their
init file (without having to make sure to do so before `magit'
is loaded or autoloaded) and to increase the likelihood that
all the potentially conflicting user bindings have already
been added.
Setting this variable after the hook has already been called
has no effect.
We recommend that you bind \"C-c g\" instead of \"C-c M-g\" to
`magit-file-dispatch'. The former is a much better binding
but the \"C-c <letter>\" namespace is strictly reserved for
users; preventing Magit from using it by default.
Also see info node `(magit)Commands for Buffers Visiting Files'."
:package-version '(magit . "3.0.0")
:group 'magit-essentials
:type 'boolean)
;;;###autoload
(progn
(defun magit-maybe-define-global-key-bindings ()
(when magit-define-global-key-bindings
(let ((map (current-global-map)))
(dolist (elt '(("C-x g" . magit-status)
("C-x M-g" . magit-dispatch)
("C-c M-g" . magit-file-dispatch)))
(let ((key (kbd (car elt)))
(def (cdr elt)))
(unless (or (lookup-key map key)
(where-is-internal def (make-sparse-keymap) t))
(define-key map key def)))))))
(if after-init-time
(magit-maybe-define-global-key-bindings)
(add-hook 'after-init-hook 'magit-maybe-define-global-key-bindings t)))
;;; Dispatch Popup
;;;###autoload (autoload 'magit-dispatch "magit" nil t)
(transient-define-prefix magit-dispatch ()
"Invoke a Magit command from a list of available commands."
:info-manual "(magit)Top"
["Transient and dwim commands"
[("A" "Apply" magit-cherry-pick)
("b" "Branch" magit-branch)
("B" "Bisect" magit-bisect)
("c" "Commit" magit-commit)
("C" "Clone" magit-clone)
("d" "Diff" magit-diff)
("D" "Diff (change)" magit-diff-refresh)
("e" "Ediff (dwim)" magit-ediff-dwim)
("E" "Ediff" magit-ediff)]
[("f" "Fetch" magit-fetch)
("F" "Pull" magit-pull)
("I" "Init" magit-init)
("l" "Log" magit-log)
("L" "Log (change)" magit-log-refresh)
("m" "Merge" magit-merge)
("M" "Remote" magit-remote)
("o" "Submodule" magit-submodule)
("O" "Subtree" magit-subtree)]
[("P" "Push" magit-push)
("r" "Rebase" magit-rebase)
("t" "Tag" magit-tag)
("T" "Note" magit-notes)
("V" "Revert" magit-revert)
("w" "Apply patches" magit-am)
("W" "Format patches" magit-patch)
("X" "Reset" magit-reset)]
[("y" "Show Refs" magit-show-refs)
("Y" "Cherries" magit-cherry)
("z" "Stash" magit-stash)
("!" "Run" magit-run)
("%" "Worktree" magit-worktree)]]
["Applying changes"
:if-derived magit-mode
[("a" "Apply" magit-apply)
("v" "Reverse" magit-reverse)
("k" "Discard" magit-discard)]
[("s" "Stage" magit-stage)
("u" "Unstage" magit-unstage)]
[("S" "Stage all" magit-stage-modified)
("U" "Unstage all" magit-unstage-all)]]
["Essential commands"
:if-derived magit-mode
("g" " refresh current buffer" magit-refresh)
("<tab>" " toggle section at point" magit-section-toggle)
("<return>" "visit thing at point" magit-visit-thing)
("C-h m" " show all key bindings" describe-mode)])
;;; Git Popup
(defcustom magit-shell-command-verbose-prompt t
"Whether to show the working directory when reading a command.
This affects `magit-git-command', `magit-git-command-topdir',
`magit-shell-command', and `magit-shell-command-topdir'."
:package-version '(magit . "2.11.0")
:group 'magit-commands
:type 'boolean)
(defvar magit-git-command-history nil)
;;;###autoload (autoload 'magit-run "magit" nil t)
(transient-define-prefix magit-run ()
"Run git or another command, or launch a graphical utility."
[["Run git subcommand"
("!" "in repository root" magit-git-command-topdir)
("p" "in working directory" magit-git-command)]
["Run shell command"
("s" "in repository root" magit-shell-command-topdir)
("S" "in working directory" magit-shell-command)]
["Launch"
("k" "gitk" magit-run-gitk)
("a" "gitk --all" magit-run-gitk-all)
("b" "gitk --branches" magit-run-gitk-branches)
("g" "git gui" magit-run-git-gui)]])
;;;###autoload
(defun magit-git-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
With a prefix argument COMMAND is run in the top-level directory
of the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command nil "git ")))
(magit--shell-command command))
;;;###autoload
(defun magit-git-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
COMMAND is run in the top-level directory of the current
working tree."
(interactive (list (magit-read-shell-command t "git ")))
(magit--shell-command command (magit-toplevel)))
;;;###autoload
(defun magit-shell-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. With a
prefix argument COMMAND is run in the top-level directory of
the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command)))
(magit--shell-command command))
;;;###autoload
(defun magit-shell-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. COMMAND
is run in the top-level directory of the current working tree."
(interactive (list (magit-read-shell-command t)))
(magit--shell-command command (magit-toplevel)))
(defun magit--shell-command (command &optional directory)
(let ((default-directory (or directory default-directory))
(process-environment process-environment))
(push "GIT_PAGER=cat" process-environment)
(magit-start-process shell-file-name nil
shell-command-switch command))
(magit-process-buffer))
(defun magit-read-shell-command (&optional toplevel initial-input)
(let ((default-directory
(if (or toplevel current-prefix-arg)
(or (magit-toplevel)
(magit--not-inside-repository-error))
default-directory)))
(read-shell-command (if magit-shell-command-verbose-prompt
(format "Async shell command in %s: "
(abbreviate-file-name default-directory))
"Async shell command: ")
initial-input 'magit-git-command-history)))
;;; Font-Lock Keywords
(defconst magit-font-lock-keywords
(eval-when-compile
`((,(concat "(\\(magit-define-section-jumper\\)\\_>"
"[ \t'\(]*"
"\\(\\(?:\\sw\\|\\s_\\)+\\)?")
(1 'font-lock-keyword-face)
(2 'font-lock-function-name-face nil t))
(,(concat "(" (regexp-opt '("magit-insert-section"
"magit-section-case"
"magit-bind-match-strings"
"magit-with-temp-index"
"magit-with-blob"
"magit-with-toplevel") t)
"\\_>")
. 1))))
(font-lock-add-keywords 'emacs-lisp-mode magit-font-lock-keywords)
;;; Version
(defvar magit-version 'undefined
"The version of Magit that you're using.
Use the function by the same name instead of this variable.")
;;;###autoload
(defun magit-version (&optional print-dest)
"Return the version of Magit currently in use.
If optional argument PRINT-DEST is non-nil, output
stream (interactively, the echo area, or the current buffer with
a prefix argument), also print the used versions of Magit, Git,
and Emacs to it."
(interactive (list (if current-prefix-arg (current-buffer) t)))
(let ((magit-git-global-arguments nil)
(toplib (or load-file-name buffer-file-name))
debug)
(unless (and toplib
(equal (file-name-nondirectory toplib) "magit.el"))
(setq toplib (locate-library "magit.el")))
(setq toplib (and toplib (magit--straight-chase-links toplib)))
(push toplib debug)
(when toplib
(let* ((topdir (file-name-directory toplib))
(gitdir (expand-file-name
".git" (file-name-directory
(directory-file-name topdir))))
(static (locate-library "magit-version.el" nil (list topdir)))
(static (and static (magit--straight-chase-links static))))
(or (progn
(push 'repo debug)
(when (and (file-exists-p gitdir)
;; It is a repo, but is it the Magit repo?
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(push t debug)
;; Inside the repo the version file should only exist
;; while running make.
(when (and static (not noninteractive))
(ignore-errors (delete-file static)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "describe"
"--tags" "--dirty" "--always")))))
(progn
(push 'static debug)
(when (and static (file-exists-p static))
(push t debug)
(load-file static)
magit-version))
(when (featurep 'package)
(push 'elpa debug)
(ignore-errors
(--when-let (assq 'magit package-alist)
(push t debug)
(setq magit-version
(and (fboundp 'package-desc-version)
(package-version-join
(package-desc-version (cadr it))))))))
(progn
(push 'dirname debug)
(let ((dirname (file-name-nondirectory
(directory-file-name topdir))))
(when (string-match "\\`magit-\\([0-9].*\\)" dirname)
(setq magit-version (match-string 1 dirname)))))
;; If all else fails, just report the commit hash. It's
;; better than nothing and we cannot do better in the case
;; of e.g. a shallow clone.
(progn
(push 'hash debug)
;; Same check as above to see if it's really the Magit repo.
(when (and (file-exists-p gitdir)
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "rev-parse" "HEAD"))))))))
(if (stringp magit-version)
(when print-dest
(princ (format "Magit %s, Git %s, Emacs %s, %s"
(or magit-version "(unknown)")
(or (let ((magit-git-debug
(lambda (err)
(display-warning '(magit git)
err :error))))
(magit-git-version t))
"(unknown)")
emacs-version
system-type)
print-dest))
(setq debug (reverse debug))
(setq magit-version 'error)
(when magit-version
(push magit-version debug))
(unless (equal (getenv "CI") "true")
;; The repository is a sparse clone.
(message "Cannot determine Magit's version %S" debug)))
magit-version))
;;; Debugging Tools
(defun magit-debug-git-executable ()
"Display a buffer with information about `magit-git-executable'.
See info node `(magit)Debugging Tools' for more information."
(interactive)
(with-current-buffer (get-buffer-create "*magit-git-debug*")
(pop-to-buffer (current-buffer))
(erase-buffer)
(insert (concat
(format "magit-git-executable: %S" magit-git-executable)
(and (not (file-name-absolute-p magit-git-executable))
(format " [%S]" (executable-find magit-git-executable)))
(format " (%s)\n"
(let* ((errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))
(insert (format "exec-path: %S\n" exec-path))
(--when-let (cl-set-difference
(-filter #'file-exists-p (remq nil (parse-colon-path
(getenv "PATH"))))
(-filter #'file-exists-p (remq nil exec-path))
:test #'file-equal-p)
(insert (format " entries in PATH, but not in exec-path: %S\n" it)))
(dolist (execdir exec-path)
(insert (format " %s (%s)\n" execdir (car (file-attributes execdir))))
(when (file-directory-p execdir)
(dolist (exec (directory-files
execdir t (concat
"\\`git" (regexp-opt exec-suffixes) "\\'")))
(insert (format " %s (%s)\n" exec
(let* ((magit-git-executable exec)
(errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))))))
;;; Startup Asserts
(defun magit-startup-asserts ()
(when-let ((val (getenv "GIT_DIR")))
(setenv "GIT_DIR")
(message "Magit unset $GIT_DIR (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(when-let ((val (getenv "GIT_WORK_TREE")))
(setenv "GIT_WORK_TREE")
(message "Magit unset $GIT_WORK_TREE (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(let ((version (magit-git-version)))
(when (and version
(version< version magit--minimal-git)
(not (equal (getenv "CI") "true")))
(display-warning 'magit (format "\
Magit requires Git >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.
If you use Tramp to work inside remote Git repositories, then you
have to make sure a suitable Git is used on the remote machines
too.\n" magit--minimal-git version) :error)))
(when (version< emacs-version magit--minimal-emacs)
(display-warning 'magit (format "\
Magit requires Emacs >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.\n"
magit--minimal-emacs emacs-version)
:error)))
;;; Loading Libraries
(provide 'magit)
(cl-eval-when (load eval)
(require 'magit-status)
(require 'magit-refs)
(require 'magit-files)
(require 'magit-reset)
(require 'magit-branch)
(require 'magit-merge)
(require 'magit-tag)
(require 'magit-worktree)
(require 'magit-notes)
(require 'magit-sequence)
(require 'magit-commit)
(require 'magit-remote)
(require 'magit-clone)
(require 'magit-fetch)
(require 'magit-pull)
(require 'magit-push)
(require 'magit-bisect)
(require 'magit-stash)
(require 'magit-blame)
(require 'magit-obsolete)
(require 'magit-submodule)
(unless (load "magit-autoloads" t t)
(require 'magit-patch)
(require 'magit-subtree)
(require 'magit-ediff)
(require 'magit-gitignore)
(require 'magit-extras)
(require 'git-rebase)
(require 'magit-imenu)
(require 'magit-bookmark)))
(eval-after-load 'bookmark
'(require 'magit-bookmark))
(if after-init-time
(progn (magit-startup-asserts)
(magit-version))
(add-hook 'after-init-hook #'magit-startup-asserts t)
(add-hook 'after-init-hook #'magit-version t))
;;; magit.el ends here
| true | ;;; magit.el --- A Git porcelain inside Emacs -*- lexical-binding: t; coding: utf-8 -*-
;; Copyright (C) 2008-2021 The Magit Project Contributors
;;
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors. If not, see http://magit.vc/authors.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Former-Maintainers:
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: git tools vc
;; Homepage: https://github.com/magit/magit
;; Magit requires at least GNU Emacs 25.1 and Git 2.2.0.
;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit 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 Magit. If not, see http://www.gnu.org/licenses.
;;; Commentary:
;; Magit is an interface to the version control system Git,
;; implemented as an Emacs package. Magit aspires to be a complete
;; Git porcelain. While we cannot (yet) claim, that Magit wraps and
;; improves upon each and every Git command, it is complete enough to
;; allow even experienced Git users to perform almost all of their
;; daily version control tasks directly from within Emacs. While many
;; fine Git clients exist, only Magit and Git itself deserve to be
;; called porcelains.
;;; Code:
(require 'magit-core)
(require 'magit-diff)
(require 'magit-log)
(require 'magit-wip)
(require 'magit-apply)
(require 'magit-repos)
(require 'git-commit)
(require 'format-spec)
(require 'package nil t) ; used in `magit-version'
(require 'with-editor)
(defconst magit--minimal-git "2.2.0")
(defconst magit--minimal-emacs "25.1")
;;; Faces
(defface magit-header-line
'((t :inherit magit-section-heading))
"Face for the `header-line' in some Magit modes.
Note that some modes, such as `magit-log-select-mode', have their
own faces for the `header-line', or for parts of the
`header-line'."
:group 'magit-faces)
(defface magit-header-line-key
'((t :inherit font-lock-builtin-face))
"Face for keys in the `header-line'."
:group 'magit-faces)
(defface magit-dimmed
'((((class color) (background light)) :foreground "grey50")
(((class color) (background dark)) :foreground "grey50"))
"Face for text that shouldn't stand out."
:group 'magit-faces)
(defface magit-hash
'((((class color) (background light)) :foreground "grey60")
(((class color) (background dark)) :foreground "grey40"))
"Face for the sha1 part of the log output."
:group 'magit-faces)
(defface magit-tag
'((((class color) (background light)) :foreground "Goldenrod4")
(((class color) (background dark)) :foreground "LightGoldenrod2"))
"Face for tag labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote
'((((class color) (background light)) :foreground "DarkOliveGreen4")
(((class color) (background dark)) :foreground "DarkSeaGreen2"))
"Face for remote branch head labels shown in log buffer."
:group 'magit-faces)
(defface magit-branch-remote-head
'((((class color) (background light)) :inherit magit-branch-remote :box t)
(((class color) (background dark)) :inherit magit-branch-remote :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-local
'((((class color) (background light)) :foreground "SkyBlue4")
(((class color) (background dark)) :foreground "LightSkyBlue1"))
"Face for local branches."
:group 'magit-faces)
(defface magit-branch-current
'((((class color) (background light)) :inherit magit-branch-local :box t)
(((class color) (background dark)) :inherit magit-branch-local :box t))
"Face for current branch."
:group 'magit-faces)
(defface magit-branch-upstream
'((t :slant italic))
"Face for upstream branch.
This face is only used in logs and it gets combined
with `magit-branch-local', `magit-branch-remote'
and/or `magit-branch-remote-head'."
:group 'magit-faces)
(defface magit-head
'((((class color) (background light)) :inherit magit-branch-local)
(((class color) (background dark)) :inherit magit-branch-local))
"Face for the symbolic ref `HEAD'."
:group 'magit-faces)
(defface magit-refname
'((((class color) (background light)) :foreground "grey30")
(((class color) (background dark)) :foreground "grey80"))
"Face for refnames without a dedicated face."
:group 'magit-faces)
(defface magit-refname-stash
'((t :inherit magit-refname))
"Face for stash refnames."
:group 'magit-faces)
(defface magit-refname-wip
'((t :inherit magit-refname))
"Face for wip refnames."
:group 'magit-faces)
(defface magit-refname-pullreq
'((t :inherit magit-refname))
"Face for pullreq refnames."
:group 'magit-faces)
(defface magit-keyword
'((t :inherit font-lock-string-face))
"Face for parts of commit messages inside brackets."
:group 'magit-faces)
(defface magit-keyword-squash
'((t :inherit font-lock-warning-face))
"Face for squash! and fixup! keywords in commit messages."
:group 'magit-faces)
(defface magit-signature-good
'((t :foreground "green"))
"Face for good signatures."
:group 'magit-faces)
(defface magit-signature-bad
'((t :foreground "red" :weight bold))
"Face for bad signatures."
:group 'magit-faces)
(defface magit-signature-untrusted
'((t :foreground "medium aquamarine"))
"Face for good untrusted signatures."
:group 'magit-faces)
(defface magit-signature-expired
'((t :foreground "orange"))
"Face for signatures that have expired."
:group 'magit-faces)
(defface magit-signature-expired-key
'((t :inherit magit-signature-expired))
"Face for signatures made by an expired key."
:group 'magit-faces)
(defface magit-signature-revoked
'((t :foreground "violet red"))
"Face for signatures made by a revoked key."
:group 'magit-faces)
(defface magit-signature-error
'((t :foreground "light blue"))
"Face for signatures that cannot be checked (e.g. missing key)."
:group 'magit-faces)
(defface magit-cherry-unmatched
'((t :foreground "cyan"))
"Face for unmatched cherry commits."
:group 'magit-faces)
(defface magit-cherry-equivalent
'((t :foreground "magenta"))
"Face for equivalent cherry commits."
:group 'magit-faces)
(defface magit-filename
'((t :weight normal))
"Face for filenames."
:group 'magit-faces)
;;; Global Bindings
;;;###autoload
(define-obsolete-variable-alias 'global-magit-file-mode
'magit-define-global-key-bindings "Magit 3.0.0")
;;;###autoload
(defcustom magit-define-global-key-bindings t
"Whether to bind some Magit commands in the global keymap.
If this variable is non-nil, then the following bindings may
be added to the global keymap. The default is t.
key binding
--- -------
C-x g magit-status
C-x M-g magit-dispatch
C-c M-g magit-file-dispatch
These bindings may be added when `after-init-hook' is called.
Each binding is added if and only if at that time no other key
is bound to the same command and no other command is bound to
the same key. In other words we try to avoid adding bindings
that are unnecessary, as well as bindings that conflict with
other bindings.
Adding the above bindings is delayed until `after-init-hook'
is called to allow users to set the variable anywhere in their
init file (without having to make sure to do so before `magit'
is loaded or autoloaded) and to increase the likelihood that
all the potentially conflicting user bindings have already
been added.
Setting this variable after the hook has already been called
has no effect.
We recommend that you bind \"C-c g\" instead of \"C-c M-g\" to
`magit-file-dispatch'. The former is a much better binding
but the \"C-c <letter>\" namespace is strictly reserved for
users; preventing Magit from using it by default.
Also see info node `(magit)Commands for Buffers Visiting Files'."
:package-version '(magit . "3.0.0")
:group 'magit-essentials
:type 'boolean)
;;;###autoload
(progn
(defun magit-maybe-define-global-key-bindings ()
(when magit-define-global-key-bindings
(let ((map (current-global-map)))
(dolist (elt '(("C-x g" . magit-status)
("C-x M-g" . magit-dispatch)
("C-c M-g" . magit-file-dispatch)))
(let ((key (kbd (car elt)))
(def (cdr elt)))
(unless (or (lookup-key map key)
(where-is-internal def (make-sparse-keymap) t))
(define-key map key def)))))))
(if after-init-time
(magit-maybe-define-global-key-bindings)
(add-hook 'after-init-hook 'magit-maybe-define-global-key-bindings t)))
;;; Dispatch Popup
;;;###autoload (autoload 'magit-dispatch "magit" nil t)
(transient-define-prefix magit-dispatch ()
"Invoke a Magit command from a list of available commands."
:info-manual "(magit)Top"
["Transient and dwim commands"
[("A" "Apply" magit-cherry-pick)
("b" "Branch" magit-branch)
("B" "Bisect" magit-bisect)
("c" "Commit" magit-commit)
("C" "Clone" magit-clone)
("d" "Diff" magit-diff)
("D" "Diff (change)" magit-diff-refresh)
("e" "Ediff (dwim)" magit-ediff-dwim)
("E" "Ediff" magit-ediff)]
[("f" "Fetch" magit-fetch)
("F" "Pull" magit-pull)
("I" "Init" magit-init)
("l" "Log" magit-log)
("L" "Log (change)" magit-log-refresh)
("m" "Merge" magit-merge)
("M" "Remote" magit-remote)
("o" "Submodule" magit-submodule)
("O" "Subtree" magit-subtree)]
[("P" "Push" magit-push)
("r" "Rebase" magit-rebase)
("t" "Tag" magit-tag)
("T" "Note" magit-notes)
("V" "Revert" magit-revert)
("w" "Apply patches" magit-am)
("W" "Format patches" magit-patch)
("X" "Reset" magit-reset)]
[("y" "Show Refs" magit-show-refs)
("Y" "Cherries" magit-cherry)
("z" "Stash" magit-stash)
("!" "Run" magit-run)
("%" "Worktree" magit-worktree)]]
["Applying changes"
:if-derived magit-mode
[("a" "Apply" magit-apply)
("v" "Reverse" magit-reverse)
("k" "Discard" magit-discard)]
[("s" "Stage" magit-stage)
("u" "Unstage" magit-unstage)]
[("S" "Stage all" magit-stage-modified)
("U" "Unstage all" magit-unstage-all)]]
["Essential commands"
:if-derived magit-mode
("g" " refresh current buffer" magit-refresh)
("<tab>" " toggle section at point" magit-section-toggle)
("<return>" "visit thing at point" magit-visit-thing)
("C-h m" " show all key bindings" describe-mode)])
;;; Git Popup
(defcustom magit-shell-command-verbose-prompt t
"Whether to show the working directory when reading a command.
This affects `magit-git-command', `magit-git-command-topdir',
`magit-shell-command', and `magit-shell-command-topdir'."
:package-version '(magit . "2.11.0")
:group 'magit-commands
:type 'boolean)
(defvar magit-git-command-history nil)
;;;###autoload (autoload 'magit-run "magit" nil t)
(transient-define-prefix magit-run ()
"Run git or another command, or launch a graphical utility."
[["Run git subcommand"
("!" "in repository root" magit-git-command-topdir)
("p" "in working directory" magit-git-command)]
["Run shell command"
("s" "in repository root" magit-shell-command-topdir)
("S" "in working directory" magit-shell-command)]
["Launch"
("k" "gitk" magit-run-gitk)
("a" "gitk --all" magit-run-gitk-all)
("b" "gitk --branches" magit-run-gitk-branches)
("g" "git gui" magit-run-git-gui)]])
;;;###autoload
(defun magit-git-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
With a prefix argument COMMAND is run in the top-level directory
of the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command nil "git ")))
(magit--shell-command command))
;;;###autoload
(defun magit-git-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. \"git \" is
used as initial input, but can be deleted to run another command.
COMMAND is run in the top-level directory of the current
working tree."
(interactive (list (magit-read-shell-command t "git ")))
(magit--shell-command command (magit-toplevel)))
;;;###autoload
(defun magit-shell-command (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. With a
prefix argument COMMAND is run in the top-level directory of
the current working tree, otherwise in `default-directory'."
(interactive (list (magit-read-shell-command)))
(magit--shell-command command))
;;;###autoload
(defun magit-shell-command-topdir (command)
"Execute COMMAND asynchronously; display output.
Interactively, prompt for COMMAND in the minibuffer. COMMAND
is run in the top-level directory of the current working tree."
(interactive (list (magit-read-shell-command t)))
(magit--shell-command command (magit-toplevel)))
(defun magit--shell-command (command &optional directory)
(let ((default-directory (or directory default-directory))
(process-environment process-environment))
(push "GIT_PAGER=cat" process-environment)
(magit-start-process shell-file-name nil
shell-command-switch command))
(magit-process-buffer))
(defun magit-read-shell-command (&optional toplevel initial-input)
(let ((default-directory
(if (or toplevel current-prefix-arg)
(or (magit-toplevel)
(magit--not-inside-repository-error))
default-directory)))
(read-shell-command (if magit-shell-command-verbose-prompt
(format "Async shell command in %s: "
(abbreviate-file-name default-directory))
"Async shell command: ")
initial-input 'magit-git-command-history)))
;;; Font-Lock Keywords
(defconst magit-font-lock-keywords
(eval-when-compile
`((,(concat "(\\(magit-define-section-jumper\\)\\_>"
"[ \t'\(]*"
"\\(\\(?:\\sw\\|\\s_\\)+\\)?")
(1 'font-lock-keyword-face)
(2 'font-lock-function-name-face nil t))
(,(concat "(" (regexp-opt '("magit-insert-section"
"magit-section-case"
"magit-bind-match-strings"
"magit-with-temp-index"
"magit-with-blob"
"magit-with-toplevel") t)
"\\_>")
. 1))))
(font-lock-add-keywords 'emacs-lisp-mode magit-font-lock-keywords)
;;; Version
(defvar magit-version 'undefined
"The version of Magit that you're using.
Use the function by the same name instead of this variable.")
;;;###autoload
(defun magit-version (&optional print-dest)
"Return the version of Magit currently in use.
If optional argument PRINT-DEST is non-nil, output
stream (interactively, the echo area, or the current buffer with
a prefix argument), also print the used versions of Magit, Git,
and Emacs to it."
(interactive (list (if current-prefix-arg (current-buffer) t)))
(let ((magit-git-global-arguments nil)
(toplib (or load-file-name buffer-file-name))
debug)
(unless (and toplib
(equal (file-name-nondirectory toplib) "magit.el"))
(setq toplib (locate-library "magit.el")))
(setq toplib (and toplib (magit--straight-chase-links toplib)))
(push toplib debug)
(when toplib
(let* ((topdir (file-name-directory toplib))
(gitdir (expand-file-name
".git" (file-name-directory
(directory-file-name topdir))))
(static (locate-library "magit-version.el" nil (list topdir)))
(static (and static (magit--straight-chase-links static))))
(or (progn
(push 'repo debug)
(when (and (file-exists-p gitdir)
;; It is a repo, but is it the Magit repo?
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(push t debug)
;; Inside the repo the version file should only exist
;; while running make.
(when (and static (not noninteractive))
(ignore-errors (delete-file static)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "describe"
"--tags" "--dirty" "--always")))))
(progn
(push 'static debug)
(when (and static (file-exists-p static))
(push t debug)
(load-file static)
magit-version))
(when (featurep 'package)
(push 'elpa debug)
(ignore-errors
(--when-let (assq 'magit package-alist)
(push t debug)
(setq magit-version
(and (fboundp 'package-desc-version)
(package-version-join
(package-desc-version (cadr it))))))))
(progn
(push 'dirname debug)
(let ((dirname (file-name-nondirectory
(directory-file-name topdir))))
(when (string-match "\\`magit-\\([0-9].*\\)" dirname)
(setq magit-version (match-string 1 dirname)))))
;; If all else fails, just report the commit hash. It's
;; better than nothing and we cannot do better in the case
;; of e.g. a shallow clone.
(progn
(push 'hash debug)
;; Same check as above to see if it's really the Magit repo.
(when (and (file-exists-p gitdir)
(file-exists-p
(expand-file-name "../lisp/magit.el" gitdir)))
(setq magit-version
(let ((default-directory topdir))
(magit-git-string "rev-parse" "HEAD"))))))))
(if (stringp magit-version)
(when print-dest
(princ (format "Magit %s, Git %s, Emacs %s, %s"
(or magit-version "(unknown)")
(or (let ((magit-git-debug
(lambda (err)
(display-warning '(magit git)
err :error))))
(magit-git-version t))
"(unknown)")
emacs-version
system-type)
print-dest))
(setq debug (reverse debug))
(setq magit-version 'error)
(when magit-version
(push magit-version debug))
(unless (equal (getenv "CI") "true")
;; The repository is a sparse clone.
(message "Cannot determine Magit's version %S" debug)))
magit-version))
;;; Debugging Tools
(defun magit-debug-git-executable ()
"Display a buffer with information about `magit-git-executable'.
See info node `(magit)Debugging Tools' for more information."
(interactive)
(with-current-buffer (get-buffer-create "*magit-git-debug*")
(pop-to-buffer (current-buffer))
(erase-buffer)
(insert (concat
(format "magit-git-executable: %S" magit-git-executable)
(and (not (file-name-absolute-p magit-git-executable))
(format " [%S]" (executable-find magit-git-executable)))
(format " (%s)\n"
(let* ((errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))
(insert (format "exec-path: %S\n" exec-path))
(--when-let (cl-set-difference
(-filter #'file-exists-p (remq nil (parse-colon-path
(getenv "PATH"))))
(-filter #'file-exists-p (remq nil exec-path))
:test #'file-equal-p)
(insert (format " entries in PATH, but not in exec-path: %S\n" it)))
(dolist (execdir exec-path)
(insert (format " %s (%s)\n" execdir (car (file-attributes execdir))))
(when (file-directory-p execdir)
(dolist (exec (directory-files
execdir t (concat
"\\`git" (regexp-opt exec-suffixes) "\\'")))
(insert (format " %s (%s)\n" exec
(let* ((magit-git-executable exec)
(errmsg nil)
(magit-git-debug (lambda (err) (setq errmsg err))))
(or (magit-git-version t) errmsg)))))))))
;;; Startup Asserts
(defun magit-startup-asserts ()
(when-let ((val (getenv "GIT_DIR")))
(setenv "GIT_DIR")
(message "Magit unset $GIT_DIR (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(when-let ((val (getenv "GIT_WORK_TREE")))
(setenv "GIT_WORK_TREE")
(message "Magit unset $GIT_WORK_TREE (was %S). See \
https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike" val))
(let ((version (magit-git-version)))
(when (and version
(version< version magit--minimal-git)
(not (equal (getenv "CI") "true")))
(display-warning 'magit (format "\
Magit requires Git >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.
If you use Tramp to work inside remote Git repositories, then you
have to make sure a suitable Git is used on the remote machines
too.\n" magit--minimal-git version) :error)))
(when (version< emacs-version magit--minimal-emacs)
(display-warning 'magit (format "\
Magit requires Emacs >= %s, you are using %s.
If this comes as a surprise to you, because you do actually have
a newer version installed, then that probably means that the
older version happens to appear earlier on the `$PATH'. If you
always start Emacs from a shell, then that can be fixed in the
shell's init file. If you start Emacs by clicking on an icon,
or using some sort of application launcher, then you probably
have to adjust the environment as seen by graphical interface.
For X11 something like ~/.xinitrc should work.\n"
magit--minimal-emacs emacs-version)
:error)))
;;; Loading Libraries
(provide 'magit)
(cl-eval-when (load eval)
(require 'magit-status)
(require 'magit-refs)
(require 'magit-files)
(require 'magit-reset)
(require 'magit-branch)
(require 'magit-merge)
(require 'magit-tag)
(require 'magit-worktree)
(require 'magit-notes)
(require 'magit-sequence)
(require 'magit-commit)
(require 'magit-remote)
(require 'magit-clone)
(require 'magit-fetch)
(require 'magit-pull)
(require 'magit-push)
(require 'magit-bisect)
(require 'magit-stash)
(require 'magit-blame)
(require 'magit-obsolete)
(require 'magit-submodule)
(unless (load "magit-autoloads" t t)
(require 'magit-patch)
(require 'magit-subtree)
(require 'magit-ediff)
(require 'magit-gitignore)
(require 'magit-extras)
(require 'git-rebase)
(require 'magit-imenu)
(require 'magit-bookmark)))
(eval-after-load 'bookmark
'(require 'magit-bookmark))
(if after-init-time
(progn (magit-startup-asserts)
(magit-version))
(add-hook 'after-init-hook #'magit-startup-asserts t)
(add-hook 'after-init-hook #'magit-version t))
;;; magit.el ends here
|
[
{
"context": " -*- lexical-binding: t -*-\n\n;; Copyright (C) 2017 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <ambrevar@gmail.com>",
"end": 141,
"score": 0.9998461604118347,
"start": 125,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": ";; Copyright (C) 2017 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <ambrevar@gmail.com>\n;; Maintainer: James Nguyen ",
"end": 170,
"score": 0.9998842477798462,
"start": 154,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": "17 Pierre Neidhardt\n\n;; Author: Pierre Neidhardt <ambrevar@gmail.com>\n;; Maintainer: James Nguyen <james@jojojames.com",
"end": 190,
"score": 0.9999347925186157,
"start": 172,
"tag": "EMAIL",
"value": "ambrevar@gmail.com"
},
{
"context": "erre Neidhardt <ambrevar@gmail.com>\n;; Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <ambrev",
"end": 219,
"score": 0.9999014139175415,
"start": 207,
"tag": "NAME",
"value": "James Nguyen"
},
{
"context": "<ambrevar@gmail.com>\n;; Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <ambrevar@gmail.com>\n;; URL:",
"end": 240,
"score": 0.9999344944953918,
"start": 221,
"tag": "EMAIL",
"value": "james@jojojames.com"
},
{
"context": " Maintainer: James Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <ambrevar@gmail.com>\n;; URL: https://github.com/e",
"end": 261,
"score": 0.9998672604560852,
"start": 245,
"tag": "NAME",
"value": "Pierre Neidhardt"
},
{
"context": "Nguyen <james@jojojames.com>\n;; Pierre Neidhardt <ambrevar@gmail.com>\n;; URL: https://github.com/emacs-evil/evil-colle",
"end": 281,
"score": 0.9999346733093262,
"start": 263,
"tag": "EMAIL",
"value": "ambrevar@gmail.com"
}
] | elpa/evil-collection-20180708.2010/evil-collection-image+.el | electricoctopi/dotemacs | 0 | ;;; evil-collection-image+.el --- Evil bindings for image-mode with image+ -*- lexical-binding: t -*-
;; Copyright (C) 2017 Pierre Neidhardt
;; Author: Pierre Neidhardt <ambrevar@gmail.com>
;; Maintainer: James Nguyen <james@jojojames.com>
;; Pierre Neidhardt <ambrevar@gmail.com>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, image, tools
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for image-mode with image+.
;;; Code:
(require 'evil-collection)
(require 'image+ nil t)
(defconst evil-collection-image+-maps '(image-mode-map))
(defun evil-collection-image+-setup ()
"Set up `evil' bindings for `image+'."
(evil-collection-define-key 'normal 'image-mode-map
;; zoom
"+" 'imagex-sticky-zoom-in
"=" 'imagex-sticky-zoom-in
"-" 'imagex-sticky-zoom-out
"O" 'imagex-sticky-restore-original
"M" 'imagex-sticky-maximize
"m" 'imagex-auto-adjust-mode
"S" 'imagex-sticky-save-image
"r" 'imagex-sticky-rotate-right
"R" 'imagex-sticky-rotate-left
"<" 'imagex-sticky-rotate-left ; like sxiv
">" 'imagex-sticky-rotate-right)) ; like sxiv
(provide 'evil-collection-image+)
;;; evil-collection-image+.el ends here
| 28361 | ;;; evil-collection-image+.el --- Evil bindings for image-mode with image+ -*- lexical-binding: t -*-
;; Copyright (C) 2017 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, image, tools
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for image-mode with image+.
;;; Code:
(require 'evil-collection)
(require 'image+ nil t)
(defconst evil-collection-image+-maps '(image-mode-map))
(defun evil-collection-image+-setup ()
"Set up `evil' bindings for `image+'."
(evil-collection-define-key 'normal 'image-mode-map
;; zoom
"+" 'imagex-sticky-zoom-in
"=" 'imagex-sticky-zoom-in
"-" 'imagex-sticky-zoom-out
"O" 'imagex-sticky-restore-original
"M" 'imagex-sticky-maximize
"m" 'imagex-auto-adjust-mode
"S" 'imagex-sticky-save-image
"r" 'imagex-sticky-rotate-right
"R" 'imagex-sticky-rotate-left
"<" 'imagex-sticky-rotate-left ; like sxiv
">" 'imagex-sticky-rotate-right)) ; like sxiv
(provide 'evil-collection-image+)
;;; evil-collection-image+.el ends here
| true | ;;; evil-collection-image+.el --- Evil bindings for image-mode with image+ -*- lexical-binding: t -*-
;; Copyright (C) 2017 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/emacs-evil/evil-collection
;; Version: 0.0.1
;; Package-Requires: ((emacs "25.1"))
;; Keywords: evil, image, tools
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published
;; by the Free Software Foundation; either version 3, or (at your
;; option) any later version.
;;
;; This file 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.
;;
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Evil bindings for image-mode with image+.
;;; Code:
(require 'evil-collection)
(require 'image+ nil t)
(defconst evil-collection-image+-maps '(image-mode-map))
(defun evil-collection-image+-setup ()
"Set up `evil' bindings for `image+'."
(evil-collection-define-key 'normal 'image-mode-map
;; zoom
"+" 'imagex-sticky-zoom-in
"=" 'imagex-sticky-zoom-in
"-" 'imagex-sticky-zoom-out
"O" 'imagex-sticky-restore-original
"M" 'imagex-sticky-maximize
"m" 'imagex-auto-adjust-mode
"S" 'imagex-sticky-save-image
"r" 'imagex-sticky-rotate-right
"R" 'imagex-sticky-rotate-left
"<" 'imagex-sticky-rotate-left ; like sxiv
">" 'imagex-sticky-rotate-right)) ; like sxiv
(provide 'evil-collection-image+)
;;; evil-collection-image+.el ends here
|
[
{
"context": "diting support for AUCTeX\n;;\n;; Copyright (C) 2013 Sean Allred\n;;\n;; Author: Sean Allred (seallred@smcm.edu)\n;; ",
"end": 89,
"score": 0.9998776316642761,
"start": 78,
"tag": "NAME",
"value": "Sean Allred"
},
{
"context": ";;\n;; Copyright (C) 2013 Sean Allred\n;;\n;; Author: Sean Allred (seallred@smcm.edu)\n;; Version: 1.0\n;; Package-Ve",
"end": 115,
"score": 0.9998800754547119,
"start": 104,
"tag": "NAME",
"value": "Sean Allred"
},
{
"context": "t (C) 2013 Sean Allred\n;;\n;; Author: Sean Allred (seallred@smcm.edu)\n;; Version: 1.0\n;; Package-Version: 20151121.810",
"end": 134,
"score": 0.9999304413795471,
"start": 117,
"tag": "EMAIL",
"value": "seallred@smcm.edu"
},
{
"context": " (lua-mode \"20130419\"))\n;; URL: http://github.com/vermiculus/auctex-lua\n;;\n;; This file is NOT part of Emacs.\n",
"end": 283,
"score": 0.9629552960395813,
"start": 273,
"tag": "USERNAME",
"value": "vermiculus"
}
] | elpa/auctex-lua-20151121.810/auctex-lua.el | mlciv/emacs.d | 1 | ;;; auctex-lua.el --- Lua editing support for AUCTeX
;;
;; Copyright (C) 2013 Sean Allred
;;
;; Author: Sean Allred (seallred@smcm.edu)
;; Version: 1.0
;; Package-Version: 20151121.810
;; Package-Requires: ((auctex "11.86") (lua-mode "20130419"))
;; URL: http://github.com/vermiculus/auctex-lua
;;
;; This file is NOT part of Emacs.
;;
;; 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
;; of the License, 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.
;; 51 Franklin Street, Fifth Floor
;; Boston, MA, 02110-1301
;; USA.
;;
;; Keywords: latex, lua
;;
;;; Commentary:
;;
;; This package provides some basic utilities for working with Lua
;; code from within AUCTeX. `LaTeX-edit-Lua-code-start' is the entry
;; point of this package; bind it to your favorite key and use it
;; inside of any environment in `LaTeX-Lua-environments'. To commit
;; your changes to the parent buffer and return to it, simply use
;; `save-buffer' (or whichever key it is bound to). The contents of
;; the parent buffer will be updated and the Lua buffer will be killed.
;;
;; Beware! Editing embedded Lua code is asynchronous. If you kill
;; the buffer that was editing it, your changes will be lost! In a
;; future update I will add a `yes-or-no-p' confirmation to killing
;; the buffer, but I've yet to figure that one out.
;;; Code:
(require 'lua-mode)
(defgroup LaTeX-lua nil
"Lua support in AUCTeX."
:group 'LaTeX)
;;;###autoload
(defcustom LaTeX-Lua-environments '("luacode" "luacode*")
"List of environments that will contain Lua code."
:group 'LaTeX-lua
:type '(repeat (string)))
(defvar LaTeX-edit-Lua-code-parent-buffer)
(defvar LaTeX-edit-Lua-code-parent-buffer-point)
(defun LaTeX-mark-environment-contents ()
"Mark the contents of the innermost LaTeX environment. See
also `LaTeX-find-matching-begin' and `LaTeX-find-matching-end'."
(interactive)
;; Search for the end of the current environment.
(LaTeX-find-matching-end)
;; Then place a mark.
(push-mark (search-backward "\\end"))
;; Search for the beginning of the current environment.
(LaTeX-find-matching-begin)
;; Search for the end of the \begin{...}
(search-forward "}"))
;;;###autoload
(defun LaTeX-edit-Lua-code-start ()
"Place Lua code in a separate buffer in `lua-mode'."
(interactive)
;; If we are in a Lua environment,
(if (member (LaTeX-current-environment) LaTeX-Lua-environments)
;; Make a few notes about where we are and what we're looking at
(let* ((lua-parent-buffer (current-buffer))
(lua-where-edit-started (point))
(lua-buffer-name (format "*%s [Lua]*" (buffer-name)))
(lua-buffer (get-buffer-create lua-buffer-name)) ; prepare buffer
(lua-code (progn (LaTeX-mark-environment-contents) ; get lua code
(buffer-substring-no-properties (point) (mark)))))
;; Switch to the Lua buffer we just created.
(switch-to-buffer-other-window lua-buffer)
;; Record some buffer-local variables
(setq LaTeX-edit-Lua-code-parent-buffer lua-parent-buffer)
(setq LaTeX-edit-Lua-code-parent-buffer-point lua-where-edit-started)
;; and switch this buffer to `lua-mode'
(lua-mode)
;; Set key bindings.
(local-set-key [remap save-buffer] 'LaTeX-edit-Lua-code-finish)
;; Fill the buffer with the Lua code.
(insert lua-code))
(message "Not in a Lua code environment.")))
(defun LaTeX-edit-Lua-code-finish ()
"Dump the contents of the current buffer into the
buffer/environment it was called from, replacing what is
currently in that environment.
Note that this function isn't too smart yet; it does not
intelligently handle a scenario where other editing has taken
place in the parent buffer. If point has moved into a different
environment, that environment will be replaced instead of its
original one. Remember, you can always `undo' your changes. See
`LaTeX-mark-environment-contents'."
(interactive)
;; 'Ensure' this is a Lua code buffer that was made with `LaTeX-edit-Lua-code-start'
(if (bufferp LaTeX-edit-Lua-code-parent-buffer)
;; Grab the Lua code
(let* ((lua-code (progn (widen)
(LaTeX-edit-Lua--chomp
(buffer-substring (point-min)
(point-max))))))
;; Kill the Lua buffer
(kill-buffer-and-window)
;; and switch to its parent
(switch-to-buffer LaTeX-edit-Lua-code-parent-buffer)
(save-excursion
;; Mark the current environment
(LaTeX-mark-environment-contents)
;; and replace it
(delete-region (point) (mark))
;; with the Lua code
(insert lua-code))
;; and return point to its rightful place
(goto-char LaTeX-edit-Lua-code-parent-buffer-point))
(message "%s %s"
"Something went wrong."
"Am I *really* in a buffer created with `LaTeX-edit-Lua-code-finish'?")))
;; Adapted from the Elisp Cookbook:
;; http://www.emacswiki.org/emacs/ElispCookbook#toc6
(defun LaTeX-edit-Lua--chomp (str)
"Chomp leading and tailing whitespace from STR."
(while (string-match "\\s*.*\\s*" str)
(setq str (replace-match "" t t str)))
str)
(provide 'auctex-lua)
;;; auctex-lua.el ends here
| 51688 | ;;; auctex-lua.el --- Lua editing support for AUCTeX
;;
;; Copyright (C) 2013 <NAME>
;;
;; Author: <NAME> (<EMAIL>)
;; Version: 1.0
;; Package-Version: 20151121.810
;; Package-Requires: ((auctex "11.86") (lua-mode "20130419"))
;; URL: http://github.com/vermiculus/auctex-lua
;;
;; This file is NOT part of Emacs.
;;
;; 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
;; of the License, 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.
;; 51 Franklin Street, Fifth Floor
;; Boston, MA, 02110-1301
;; USA.
;;
;; Keywords: latex, lua
;;
;;; Commentary:
;;
;; This package provides some basic utilities for working with Lua
;; code from within AUCTeX. `LaTeX-edit-Lua-code-start' is the entry
;; point of this package; bind it to your favorite key and use it
;; inside of any environment in `LaTeX-Lua-environments'. To commit
;; your changes to the parent buffer and return to it, simply use
;; `save-buffer' (or whichever key it is bound to). The contents of
;; the parent buffer will be updated and the Lua buffer will be killed.
;;
;; Beware! Editing embedded Lua code is asynchronous. If you kill
;; the buffer that was editing it, your changes will be lost! In a
;; future update I will add a `yes-or-no-p' confirmation to killing
;; the buffer, but I've yet to figure that one out.
;;; Code:
(require 'lua-mode)
(defgroup LaTeX-lua nil
"Lua support in AUCTeX."
:group 'LaTeX)
;;;###autoload
(defcustom LaTeX-Lua-environments '("luacode" "luacode*")
"List of environments that will contain Lua code."
:group 'LaTeX-lua
:type '(repeat (string)))
(defvar LaTeX-edit-Lua-code-parent-buffer)
(defvar LaTeX-edit-Lua-code-parent-buffer-point)
(defun LaTeX-mark-environment-contents ()
"Mark the contents of the innermost LaTeX environment. See
also `LaTeX-find-matching-begin' and `LaTeX-find-matching-end'."
(interactive)
;; Search for the end of the current environment.
(LaTeX-find-matching-end)
;; Then place a mark.
(push-mark (search-backward "\\end"))
;; Search for the beginning of the current environment.
(LaTeX-find-matching-begin)
;; Search for the end of the \begin{...}
(search-forward "}"))
;;;###autoload
(defun LaTeX-edit-Lua-code-start ()
"Place Lua code in a separate buffer in `lua-mode'."
(interactive)
;; If we are in a Lua environment,
(if (member (LaTeX-current-environment) LaTeX-Lua-environments)
;; Make a few notes about where we are and what we're looking at
(let* ((lua-parent-buffer (current-buffer))
(lua-where-edit-started (point))
(lua-buffer-name (format "*%s [Lua]*" (buffer-name)))
(lua-buffer (get-buffer-create lua-buffer-name)) ; prepare buffer
(lua-code (progn (LaTeX-mark-environment-contents) ; get lua code
(buffer-substring-no-properties (point) (mark)))))
;; Switch to the Lua buffer we just created.
(switch-to-buffer-other-window lua-buffer)
;; Record some buffer-local variables
(setq LaTeX-edit-Lua-code-parent-buffer lua-parent-buffer)
(setq LaTeX-edit-Lua-code-parent-buffer-point lua-where-edit-started)
;; and switch this buffer to `lua-mode'
(lua-mode)
;; Set key bindings.
(local-set-key [remap save-buffer] 'LaTeX-edit-Lua-code-finish)
;; Fill the buffer with the Lua code.
(insert lua-code))
(message "Not in a Lua code environment.")))
(defun LaTeX-edit-Lua-code-finish ()
"Dump the contents of the current buffer into the
buffer/environment it was called from, replacing what is
currently in that environment.
Note that this function isn't too smart yet; it does not
intelligently handle a scenario where other editing has taken
place in the parent buffer. If point has moved into a different
environment, that environment will be replaced instead of its
original one. Remember, you can always `undo' your changes. See
`LaTeX-mark-environment-contents'."
(interactive)
;; 'Ensure' this is a Lua code buffer that was made with `LaTeX-edit-Lua-code-start'
(if (bufferp LaTeX-edit-Lua-code-parent-buffer)
;; Grab the Lua code
(let* ((lua-code (progn (widen)
(LaTeX-edit-Lua--chomp
(buffer-substring (point-min)
(point-max))))))
;; Kill the Lua buffer
(kill-buffer-and-window)
;; and switch to its parent
(switch-to-buffer LaTeX-edit-Lua-code-parent-buffer)
(save-excursion
;; Mark the current environment
(LaTeX-mark-environment-contents)
;; and replace it
(delete-region (point) (mark))
;; with the Lua code
(insert lua-code))
;; and return point to its rightful place
(goto-char LaTeX-edit-Lua-code-parent-buffer-point))
(message "%s %s"
"Something went wrong."
"Am I *really* in a buffer created with `LaTeX-edit-Lua-code-finish'?")))
;; Adapted from the Elisp Cookbook:
;; http://www.emacswiki.org/emacs/ElispCookbook#toc6
(defun LaTeX-edit-Lua--chomp (str)
"Chomp leading and tailing whitespace from STR."
(while (string-match "\\s*.*\\s*" str)
(setq str (replace-match "" t t str)))
str)
(provide 'auctex-lua)
;;; auctex-lua.el ends here
| true | ;;; auctex-lua.el --- Lua editing support for AUCTeX
;;
;; Copyright (C) 2013 PI:NAME:<NAME>END_PI
;;
;; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;; Version: 1.0
;; Package-Version: 20151121.810
;; Package-Requires: ((auctex "11.86") (lua-mode "20130419"))
;; URL: http://github.com/vermiculus/auctex-lua
;;
;; This file is NOT part of Emacs.
;;
;; 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
;; of the License, 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.
;; 51 Franklin Street, Fifth Floor
;; Boston, MA, 02110-1301
;; USA.
;;
;; Keywords: latex, lua
;;
;;; Commentary:
;;
;; This package provides some basic utilities for working with Lua
;; code from within AUCTeX. `LaTeX-edit-Lua-code-start' is the entry
;; point of this package; bind it to your favorite key and use it
;; inside of any environment in `LaTeX-Lua-environments'. To commit
;; your changes to the parent buffer and return to it, simply use
;; `save-buffer' (or whichever key it is bound to). The contents of
;; the parent buffer will be updated and the Lua buffer will be killed.
;;
;; Beware! Editing embedded Lua code is asynchronous. If you kill
;; the buffer that was editing it, your changes will be lost! In a
;; future update I will add a `yes-or-no-p' confirmation to killing
;; the buffer, but I've yet to figure that one out.
;;; Code:
(require 'lua-mode)
(defgroup LaTeX-lua nil
"Lua support in AUCTeX."
:group 'LaTeX)
;;;###autoload
(defcustom LaTeX-Lua-environments '("luacode" "luacode*")
"List of environments that will contain Lua code."
:group 'LaTeX-lua
:type '(repeat (string)))
(defvar LaTeX-edit-Lua-code-parent-buffer)
(defvar LaTeX-edit-Lua-code-parent-buffer-point)
(defun LaTeX-mark-environment-contents ()
"Mark the contents of the innermost LaTeX environment. See
also `LaTeX-find-matching-begin' and `LaTeX-find-matching-end'."
(interactive)
;; Search for the end of the current environment.
(LaTeX-find-matching-end)
;; Then place a mark.
(push-mark (search-backward "\\end"))
;; Search for the beginning of the current environment.
(LaTeX-find-matching-begin)
;; Search for the end of the \begin{...}
(search-forward "}"))
;;;###autoload
(defun LaTeX-edit-Lua-code-start ()
"Place Lua code in a separate buffer in `lua-mode'."
(interactive)
;; If we are in a Lua environment,
(if (member (LaTeX-current-environment) LaTeX-Lua-environments)
;; Make a few notes about where we are and what we're looking at
(let* ((lua-parent-buffer (current-buffer))
(lua-where-edit-started (point))
(lua-buffer-name (format "*%s [Lua]*" (buffer-name)))
(lua-buffer (get-buffer-create lua-buffer-name)) ; prepare buffer
(lua-code (progn (LaTeX-mark-environment-contents) ; get lua code
(buffer-substring-no-properties (point) (mark)))))
;; Switch to the Lua buffer we just created.
(switch-to-buffer-other-window lua-buffer)
;; Record some buffer-local variables
(setq LaTeX-edit-Lua-code-parent-buffer lua-parent-buffer)
(setq LaTeX-edit-Lua-code-parent-buffer-point lua-where-edit-started)
;; and switch this buffer to `lua-mode'
(lua-mode)
;; Set key bindings.
(local-set-key [remap save-buffer] 'LaTeX-edit-Lua-code-finish)
;; Fill the buffer with the Lua code.
(insert lua-code))
(message "Not in a Lua code environment.")))
(defun LaTeX-edit-Lua-code-finish ()
"Dump the contents of the current buffer into the
buffer/environment it was called from, replacing what is
currently in that environment.
Note that this function isn't too smart yet; it does not
intelligently handle a scenario where other editing has taken
place in the parent buffer. If point has moved into a different
environment, that environment will be replaced instead of its
original one. Remember, you can always `undo' your changes. See
`LaTeX-mark-environment-contents'."
(interactive)
;; 'Ensure' this is a Lua code buffer that was made with `LaTeX-edit-Lua-code-start'
(if (bufferp LaTeX-edit-Lua-code-parent-buffer)
;; Grab the Lua code
(let* ((lua-code (progn (widen)
(LaTeX-edit-Lua--chomp
(buffer-substring (point-min)
(point-max))))))
;; Kill the Lua buffer
(kill-buffer-and-window)
;; and switch to its parent
(switch-to-buffer LaTeX-edit-Lua-code-parent-buffer)
(save-excursion
;; Mark the current environment
(LaTeX-mark-environment-contents)
;; and replace it
(delete-region (point) (mark))
;; with the Lua code
(insert lua-code))
;; and return point to its rightful place
(goto-char LaTeX-edit-Lua-code-parent-buffer-point))
(message "%s %s"
"Something went wrong."
"Am I *really* in a buffer created with `LaTeX-edit-Lua-code-finish'?")))
;; Adapted from the Elisp Cookbook:
;; http://www.emacswiki.org/emacs/ElispCookbook#toc6
(defun LaTeX-edit-Lua--chomp (str)
"Chomp leading and tailing whitespace from STR."
(while (string-match "\\s*.*\\s*" str)
(setq str (replace-match "" t t str)))
str)
(provide 'auctex-lua)
;;; auctex-lua.el ends here
|
[
{
"context": "complete source of racer\n\n;; Copyright (C) 2017 by Syohei YOSHIDA\n\n;; Author: Syohei YOSHIDA <syohex@gmail.com>\n;; ",
"end": 90,
"score": 0.9998133778572083,
"start": 76,
"tag": "NAME",
"value": "Syohei YOSHIDA"
},
{
"context": "; Copyright (C) 2017 by Syohei YOSHIDA\n\n;; Author: Syohei YOSHIDA <syohex@gmail.com>\n;; URL: https://github.com/syo",
"end": 117,
"score": 0.999870777130127,
"start": 103,
"tag": "NAME",
"value": "Syohei YOSHIDA"
},
{
"context": "017 by Syohei YOSHIDA\n\n;; Author: Syohei YOSHIDA <syohex@gmail.com>\n;; URL: https://github.com/syohex/emacs-ac-racer",
"end": 135,
"score": 0.9999256134033203,
"start": 119,
"tag": "EMAIL",
"value": "syohex@gmail.com"
},
{
"context": "IDA <syohex@gmail.com>\n;; URL: https://github.com/syohex/emacs-ac-racer\n;; Package-Version: 20170114.9\n;; ",
"end": 170,
"score": 0.9966378211975098,
"start": 164,
"tag": "USERNAME",
"value": "syohex"
}
] | elpa/ac-racer-20170114.9/ac-racer.el | thuleqaid/emacsd | 1 | ;;; ac-racer.el --- auto-complete source of racer
;; Copyright (C) 2017 by Syohei YOSHIDA
;; Author: Syohei YOSHIDA <syohex@gmail.com>
;; URL: https://github.com/syohex/emacs-ac-racer
;; Package-Version: 20170114.9
;; Version: 0.02
;; Package-Requires: ((emacs "24.3") (auto-complete "1.5.0") (racer "0.0.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; ac-racer.el provides auto-complete source for Rust programming language.
;;; Code:
(require 'auto-complete)
(require 'racer)
(require 'cl-lib)
(defgroup ac-racer nil
"auto-complete source of racer"
:group 'auto-complete)
(defvar ac-racer--tempfile (concat temporary-file-directory "ac-racer-complete"))
(defun ac-racer--collect-candidates ()
(goto-char (point-min))
;; MATCH (1:candidate),line,column,filepath,(2:type),(3:signature)
(let ((re "^MATCH \\([^,]+\\),[^,]+,[^,]+,[^,]+,\\([^,]+\\),\\(.+\\)"))
(cl-loop while (re-search-forward re nil t)
for candidate = (match-string-no-properties 1)
for type = (match-string-no-properties 2)
for signature = (match-string-no-properties 3)
collect
(popup-make-item candidate :document signature :summary type))))
(defun ac-racer--prefix ()
(save-excursion
(skip-syntax-backward "w_")
(point)))
(defun ac-racer--candidates ()
(let ((process-environment (if racer-rust-src-path
(cons (concat "RUST_SRC_PATH=" racer-rust-src-path)
process-environment)
process-environment))
(line (number-to-string (line-number-at-pos)))
(column (number-to-string (current-column)))
(file (or (buffer-file-name) "")))
(write-region (point-min) (point-max) ac-racer--tempfile nil 'no-message)
(with-temp-buffer
(let ((ret (process-file racer-cmd nil t nil
"complete" line column file ac-racer--tempfile)))
(when (zerop ret)
(ac-racer--collect-candidates))))))
;;;###autoload
(defun ac-racer-setup ()
(interactive)
(auto-complete-mode +1)
(add-to-list 'ac-sources 'ac-source-racer))
(ac-define-source racer
'((prefix . ac-racer--prefix)
(candidates . ac-racer--candidates)
(requires . -1)))
(provide 'ac-racer)
;;; ac-racer.el ends here
| 21708 | ;;; ac-racer.el --- auto-complete source of racer
;; Copyright (C) 2017 by <NAME>
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/syohex/emacs-ac-racer
;; Package-Version: 20170114.9
;; Version: 0.02
;; Package-Requires: ((emacs "24.3") (auto-complete "1.5.0") (racer "0.0.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; ac-racer.el provides auto-complete source for Rust programming language.
;;; Code:
(require 'auto-complete)
(require 'racer)
(require 'cl-lib)
(defgroup ac-racer nil
"auto-complete source of racer"
:group 'auto-complete)
(defvar ac-racer--tempfile (concat temporary-file-directory "ac-racer-complete"))
(defun ac-racer--collect-candidates ()
(goto-char (point-min))
;; MATCH (1:candidate),line,column,filepath,(2:type),(3:signature)
(let ((re "^MATCH \\([^,]+\\),[^,]+,[^,]+,[^,]+,\\([^,]+\\),\\(.+\\)"))
(cl-loop while (re-search-forward re nil t)
for candidate = (match-string-no-properties 1)
for type = (match-string-no-properties 2)
for signature = (match-string-no-properties 3)
collect
(popup-make-item candidate :document signature :summary type))))
(defun ac-racer--prefix ()
(save-excursion
(skip-syntax-backward "w_")
(point)))
(defun ac-racer--candidates ()
(let ((process-environment (if racer-rust-src-path
(cons (concat "RUST_SRC_PATH=" racer-rust-src-path)
process-environment)
process-environment))
(line (number-to-string (line-number-at-pos)))
(column (number-to-string (current-column)))
(file (or (buffer-file-name) "")))
(write-region (point-min) (point-max) ac-racer--tempfile nil 'no-message)
(with-temp-buffer
(let ((ret (process-file racer-cmd nil t nil
"complete" line column file ac-racer--tempfile)))
(when (zerop ret)
(ac-racer--collect-candidates))))))
;;;###autoload
(defun ac-racer-setup ()
(interactive)
(auto-complete-mode +1)
(add-to-list 'ac-sources 'ac-source-racer))
(ac-define-source racer
'((prefix . ac-racer--prefix)
(candidates . ac-racer--candidates)
(requires . -1)))
(provide 'ac-racer)
;;; ac-racer.el ends here
| true | ;;; ac-racer.el --- auto-complete source of racer
;; Copyright (C) 2017 by PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/syohex/emacs-ac-racer
;; Package-Version: 20170114.9
;; Version: 0.02
;; Package-Requires: ((emacs "24.3") (auto-complete "1.5.0") (racer "0.0.2"))
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; ac-racer.el provides auto-complete source for Rust programming language.
;;; Code:
(require 'auto-complete)
(require 'racer)
(require 'cl-lib)
(defgroup ac-racer nil
"auto-complete source of racer"
:group 'auto-complete)
(defvar ac-racer--tempfile (concat temporary-file-directory "ac-racer-complete"))
(defun ac-racer--collect-candidates ()
(goto-char (point-min))
;; MATCH (1:candidate),line,column,filepath,(2:type),(3:signature)
(let ((re "^MATCH \\([^,]+\\),[^,]+,[^,]+,[^,]+,\\([^,]+\\),\\(.+\\)"))
(cl-loop while (re-search-forward re nil t)
for candidate = (match-string-no-properties 1)
for type = (match-string-no-properties 2)
for signature = (match-string-no-properties 3)
collect
(popup-make-item candidate :document signature :summary type))))
(defun ac-racer--prefix ()
(save-excursion
(skip-syntax-backward "w_")
(point)))
(defun ac-racer--candidates ()
(let ((process-environment (if racer-rust-src-path
(cons (concat "RUST_SRC_PATH=" racer-rust-src-path)
process-environment)
process-environment))
(line (number-to-string (line-number-at-pos)))
(column (number-to-string (current-column)))
(file (or (buffer-file-name) "")))
(write-region (point-min) (point-max) ac-racer--tempfile nil 'no-message)
(with-temp-buffer
(let ((ret (process-file racer-cmd nil t nil
"complete" line column file ac-racer--tempfile)))
(when (zerop ret)
(ac-racer--collect-candidates))))))
;;;###autoload
(defun ac-racer-setup ()
(interactive)
(auto-complete-mode +1)
(add-to-list 'ac-sources 'ac-source-racer))
(ac-define-source racer
'((prefix . ac-racer--prefix)
(candidates . ac-racer--candidates)
(requires . -1)))
(provide 'ac-racer)
;;; ac-racer.el ends here
|
[
{
"context": "((emacs \"25.1\")\n (dash \"20210826\"))\n :commit \"03f495f351d6e622143e4628681019df1313a5f2\" :authors\n '((\"Jonas Bernoulli\" . \"jonas@bernoul",
"end": 173,
"score": 0.987472653388977,
"start": 133,
"tag": "PASSWORD",
"value": "03f495f351d6e622143e4628681019df1313a5f2"
},
{
"context": "351d6e622143e4628681019df1313a5f2\" :authors\n '((\"Jonas Bernoulli\" . \"jonas@bernoul.li\"))\n :maintainer\n '(\"Jonas ",
"end": 205,
"score": 0.9998311400413513,
"start": 190,
"tag": "NAME",
"value": "Jonas Bernoulli"
},
{
"context": "019df1313a5f2\" :authors\n '((\"Jonas Bernoulli\" . \"jonas@bernoul.li\"))\n :maintainer\n '(\"Jonas Bernoulli\" . \"jonas@b",
"end": 226,
"score": 0.9999260902404785,
"start": 210,
"tag": "EMAIL",
"value": "jonas@bernoul.li"
},
{
"context": "noulli\" . \"jonas@bernoul.li\"))\n :maintainer\n '(\"Jonas Bernoulli\" . \"jonas@bernoul.li\")\n :keywords\n '(\"tools\")\n ",
"end": 264,
"score": 0.9998388886451721,
"start": 249,
"tag": "NAME",
"value": "Jonas Bernoulli"
},
{
"context": "noul.li\"))\n :maintainer\n '(\"Jonas Bernoulli\" . \"jonas@bernoul.li\")\n :keywords\n '(\"tools\")\n :url \"https://github",
"end": 285,
"score": 0.9999259114265442,
"start": 269,
"tag": "EMAIL",
"value": "jonas@bernoul.li"
}
] | elpa/magit-section-20211226.738/magit-section-pkg.el | Wilfred/.emacs.d | 42 | (define-package "magit-section" "20211226.738" "Sections for read-only buffers"
'((emacs "25.1")
(dash "20210826"))
:commit "03f495f351d6e622143e4628681019df1313a5f2" :authors
'(("Jonas Bernoulli" . "jonas@bernoul.li"))
:maintainer
'("Jonas Bernoulli" . "jonas@bernoul.li")
:keywords
'("tools")
:url "https://github.com/magit/magit")
;; Local Variables:
;; no-byte-compile: t
;; End:
| 25992 | (define-package "magit-section" "20211226.738" "Sections for read-only buffers"
'((emacs "25.1")
(dash "20210826"))
:commit "<PASSWORD>" :authors
'(("<NAME>" . "<EMAIL>"))
:maintainer
'("<NAME>" . "<EMAIL>")
:keywords
'("tools")
:url "https://github.com/magit/magit")
;; Local Variables:
;; no-byte-compile: t
;; End:
| true | (define-package "magit-section" "20211226.738" "Sections for read-only buffers"
'((emacs "25.1")
(dash "20210826"))
:commit "PI:PASSWORD:<PASSWORD>END_PI" :authors
'(("PI:NAME:<NAME>END_PI" . "PI:EMAIL:<EMAIL>END_PI"))
:maintainer
'("PI:NAME:<NAME>END_PI" . "PI:EMAIL:<EMAIL>END_PI")
:keywords
'("tools")
:url "https://github.com/magit/magit")
;; Local Variables:
;; no-byte-compile: t
;; End:
|
[
{
"context": "s File for Spacemacs\n;;\n;; Copyright (c) 2012-2018 Sylvain Benner & Contributors\n;;\n;; Author: Tu, Do Hoang <tuhdo1",
"end": 102,
"score": 0.9998863935470581,
"start": 88,
"tag": "NAME",
"value": "Sylvain Benner"
},
{
"context": "2-2018 Sylvain Benner & Contributors\n;;\n;; Author: Tu, Do Hoang <tuhdo1710@gmail.com>\n;; URL: https://github.com/",
"end": 144,
"score": 0.9998776912689209,
"start": 132,
"tag": "NAME",
"value": "Tu, Do Hoang"
},
{
"context": "Benner & Contributors\n;;\n;; Author: Tu, Do Hoang <tuhdo1710@gmail.com>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;",
"end": 165,
"score": 0.9999299645423889,
"start": 146,
"tag": "EMAIL",
"value": "tuhdo1710@gmail.com"
},
{
"context": " <tuhdo1710@gmail.com>\n;; URL: https://github.com/syl20bnr/spacemacs\n;;\n;; This file is not part of GNU Emac",
"end": 202,
"score": 0.9952397346496582,
"start": 194,
"tag": "USERNAME",
"value": "syl20bnr"
}
] | spacemacs/emacs.d/layers/+lang/asm/packages.el | Potpourri/dotfiles | 2 | ;;; packages.el --- Asm Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2018 Sylvain Benner & Contributors
;;
;; Author: Tu, Do Hoang <tuhdo1710@gmail.com>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq asm-packages
'(
;; package names go here
asm-mode
company
electric-indent-mode
ggtags
counsel-gtags
helm-gtags
nasm-mode
x86-lookup
))
(defun asm/init-asm-mode ()
(use-package asm-mode
:init
(spacemacs/set-leader-keys-for-major-mode 'asm-mode "h" 'x86-lookup)
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key asm-mode-map (kbd "C-j") 'newline)
(add-hook 'asm-mode-hook #'asm-generic-setup))))
(defun asm/post-init-electric-indent-mode ()
(spacemacs/add-to-hooks 'asm-electric-indent-local-mode-off
'(asm-mode-hook nasm-mode-hook)))
(defun asm/init-nasm-mode ()
"Setup for built-in `nasm-mode', which could be thought as improved `asm-mode'"
(use-package nasm-mode
:init
(progn
(add-hook 'nasm-mode-hook #'asm-generic-setup)
(add-to-list 'auto-mode-alist '("\\.[n]*\\(asm\\|s\\)\\'" . nasm-mode))
(spacemacs/set-leader-keys-for-major-mode 'nasm-mode "h" 'x86-lookup))
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key nasm-mode-map (kbd "C-j") 'newline)
;; we use the advised `asm-colon' because `nasm-colon indents the whole line, even
;; inside a comment
(define-key nasm-mode-map (kbd ":") 'asm-colon))))
(defun asm/init-x86-lookup ()
(use-package x86-lookup
:init
(progn
;; when a user installed `pdf-tools', use it for viewing PDF document.
(when (package-installed-p 'pdf-tools)
(setq x86-lookup-browse-pdf-function 'x86-lookup-browse-pdf-pdf-tools)))))
(defun asm/post-init-company ()
(spacemacs|add-company-backends :modes asm-mode nasm-mode))
(defun asm/post-init-ggtags ()
(add-hook 'asm-mode-local-vars-hook #'spacemacs/ggtags-mode-enable))
(defun asm/post-init-counsel-gtags ()
(spacemacs/counsel-gtags-define-keys-for-mode 'asm-mode))
(defun asm/post-init-helm-gtags ()
(spacemacs/helm-gtags-define-keys-for-mode 'asm-mode))
| 16602 | ;;; packages.el --- Asm Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2018 <NAME> & Contributors
;;
;; Author: <NAME> <<EMAIL>>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq asm-packages
'(
;; package names go here
asm-mode
company
electric-indent-mode
ggtags
counsel-gtags
helm-gtags
nasm-mode
x86-lookup
))
(defun asm/init-asm-mode ()
(use-package asm-mode
:init
(spacemacs/set-leader-keys-for-major-mode 'asm-mode "h" 'x86-lookup)
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key asm-mode-map (kbd "C-j") 'newline)
(add-hook 'asm-mode-hook #'asm-generic-setup))))
(defun asm/post-init-electric-indent-mode ()
(spacemacs/add-to-hooks 'asm-electric-indent-local-mode-off
'(asm-mode-hook nasm-mode-hook)))
(defun asm/init-nasm-mode ()
"Setup for built-in `nasm-mode', which could be thought as improved `asm-mode'"
(use-package nasm-mode
:init
(progn
(add-hook 'nasm-mode-hook #'asm-generic-setup)
(add-to-list 'auto-mode-alist '("\\.[n]*\\(asm\\|s\\)\\'" . nasm-mode))
(spacemacs/set-leader-keys-for-major-mode 'nasm-mode "h" 'x86-lookup))
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key nasm-mode-map (kbd "C-j") 'newline)
;; we use the advised `asm-colon' because `nasm-colon indents the whole line, even
;; inside a comment
(define-key nasm-mode-map (kbd ":") 'asm-colon))))
(defun asm/init-x86-lookup ()
(use-package x86-lookup
:init
(progn
;; when a user installed `pdf-tools', use it for viewing PDF document.
(when (package-installed-p 'pdf-tools)
(setq x86-lookup-browse-pdf-function 'x86-lookup-browse-pdf-pdf-tools)))))
(defun asm/post-init-company ()
(spacemacs|add-company-backends :modes asm-mode nasm-mode))
(defun asm/post-init-ggtags ()
(add-hook 'asm-mode-local-vars-hook #'spacemacs/ggtags-mode-enable))
(defun asm/post-init-counsel-gtags ()
(spacemacs/counsel-gtags-define-keys-for-mode 'asm-mode))
(defun asm/post-init-helm-gtags ()
(spacemacs/helm-gtags-define-keys-for-mode 'asm-mode))
| true | ;;; packages.el --- Asm Layer packages File for Spacemacs
;;
;; Copyright (c) 2012-2018 PI:NAME:<NAME>END_PI & Contributors
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; URL: https://github.com/syl20bnr/spacemacs
;;
;; This file is not part of GNU Emacs.
;;
;;; License: GPLv3
(setq asm-packages
'(
;; package names go here
asm-mode
company
electric-indent-mode
ggtags
counsel-gtags
helm-gtags
nasm-mode
x86-lookup
))
(defun asm/init-asm-mode ()
(use-package asm-mode
:init
(spacemacs/set-leader-keys-for-major-mode 'asm-mode "h" 'x86-lookup)
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key asm-mode-map (kbd "C-j") 'newline)
(add-hook 'asm-mode-hook #'asm-generic-setup))))
(defun asm/post-init-electric-indent-mode ()
(spacemacs/add-to-hooks 'asm-electric-indent-local-mode-off
'(asm-mode-hook nasm-mode-hook)))
(defun asm/init-nasm-mode ()
"Setup for built-in `nasm-mode', which could be thought as improved `asm-mode'"
(use-package nasm-mode
:init
(progn
(add-hook 'nasm-mode-hook #'asm-generic-setup)
(add-to-list 'auto-mode-alist '("\\.[n]*\\(asm\\|s\\)\\'" . nasm-mode))
(spacemacs/set-leader-keys-for-major-mode 'nasm-mode "h" 'x86-lookup))
:config
(progn
;; We need to insert a non-indented line, otherwise it's annoying
;; everytime we insert a comment for a routine
(define-key nasm-mode-map (kbd "C-j") 'newline)
;; we use the advised `asm-colon' because `nasm-colon indents the whole line, even
;; inside a comment
(define-key nasm-mode-map (kbd ":") 'asm-colon))))
(defun asm/init-x86-lookup ()
(use-package x86-lookup
:init
(progn
;; when a user installed `pdf-tools', use it for viewing PDF document.
(when (package-installed-p 'pdf-tools)
(setq x86-lookup-browse-pdf-function 'x86-lookup-browse-pdf-pdf-tools)))))
(defun asm/post-init-company ()
(spacemacs|add-company-backends :modes asm-mode nasm-mode))
(defun asm/post-init-ggtags ()
(add-hook 'asm-mode-local-vars-hook #'spacemacs/ggtags-mode-enable))
(defun asm/post-init-counsel-gtags ()
(spacemacs/counsel-gtags-define-keys-for-mode 'asm-mode))
(defun asm/post-init-helm-gtags ()
(spacemacs/helm-gtags-define-keys-for-mode 'asm-mode))
|
[
{
"context": "s -*- lexical-binding:t -*-\n\n;; Copyright (c) 2019 Dennis Ogbe\n;; Author: Dennis Ogbe <do@ogbe.net>\n;; Keywords:",
"end": 117,
"score": 0.9998898506164551,
"start": 106,
"tag": "NAME",
"value": "Dennis Ogbe"
},
{
"context": " -*-\n\n;; Copyright (c) 2019 Dennis Ogbe\n;; Author: Dennis Ogbe <do@ogbe.net>\n;; Keywords: languages\n;; Version: ",
"end": 140,
"score": 0.9998900294303894,
"start": 129,
"tag": "NAME",
"value": "Dennis Ogbe"
},
{
"context": "ight (c) 2019 Dennis Ogbe\n;; Author: Dennis Ogbe <do@ogbe.net>\n;; Keywords: languages\n;; Version: 0.1\n;; Packag",
"end": 153,
"score": 0.9999296069145203,
"start": 142,
"tag": "EMAIL",
"value": "do@ogbe.net"
}
] | julia-img-view.el | fcdimitr/julia-img-view | 4 | ;;; julia-img-view.el --- Display julia plots and images -*- lexical-binding:t -*-
;; Copyright (c) 2019 Dennis Ogbe
;; Author: Dennis Ogbe <do@ogbe.net>
;; Keywords: languages
;; Version: 0.1
;; Package-Requires: ((emacs "25") julia-repl)
;;; Usage:
;; The set-up function hooks into all places where it should and together with
;; the julia code given above, inline images should just work.
;;
;; For images in dedicated plot buffers, the package defines
;; julia-img-minor-mode, which gives a key map for controlling the plot
;; windows. The idea behind this package is that at any point in time, zero or
;; one image-mode (in this package aliased to julia-img-view-mode) buffers is
;; considered /active/. In the case that the REPL detects an image and a
;; julia-img-view-mode buffer is active, it displays the image in that
;; buffer. There can be multiple julia-img-view-mode-buffers if you want to
;; open multiple images, but the only buffer updated by the REPL is the
;; currently active one.
;;
;; For more detailed information, please consult the accompanying README.org
;; file.
;;; License:
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to
;; deal in the Software without restriction, including without limitation the
;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;; sell copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;; IN THE SOFTWARE.
;;; Commentary:
;; This package contains a small set of tools meant to enhance the image
;; viewing and plotting experience when using `julia-repl' in Emacs. It
;; contains two main tools:
;; 1. Inline display of images/plots
;; 2. Display of images/plots in dedicated plot buffers
;; See the provided README.org for additional discussion.
;;; Code:
(require 'iimage)
(require 'button)
(require 'julia-repl)
;; customizations, constants, and variables
(defgroup julia-img-view nil
"Display julia plots and images"
:group 'julia)
(defcustom julia-img-view-buffer-prefix "julia-img"
"The default prefix for all image buffers.")
(defvar julia-img-view--active-buffer nil
"Holds the current active image buffer.")
(defconst julia-img-view--img-uri-regexp "juliaimg:\\([-+./_0-9a-zA-Z]+\\)"
"The regular expression that matches julia's image URI output.")
;; interface
(defun julia-img-view-create-buffer (arg)
"Make a new image buffer and mark it as active.
When called with prefix argument ARG, prompt for a custom name
prefix."
(interactive "P")
(let* ((uniquify-buffer-name-style nil)
(prefix (when arg (read-from-minibuffer "Image buffer name prefix: ")))
(buf (generate-new-buffer (or prefix julia-img-view-buffer-prefix))))
(with-current-buffer buf (read-only-mode))
(setq julia-img-view--active-buffer buf)
(display-buffer buf)
(message "Created new julia-img-view buffer %s." buf)))
(defun julia-img-view-active-buffer ()
"Get the active image buffer.
When called interactively, pop to it instead."
(interactive)
(when (buffer-live-p julia-img-view--active-buffer)
(if (called-interactively-p)
(pop-to-buffer julia-img-view--active-buffer)
julia-img-view--active-buffer)))
(defun julia-img-view-disable-buffers ()
"Disable any active image buffers and fall back to inline plotting."
(interactive)
(setq julia-img-view--active-buffer nil)
(message "Disabled julia-img-view buffers."))
(defun julia-img-view-mark-buffer-active ()
"Mark the selected buffer as active."
(interactive)
(let ((buf (current-buffer)))
(if (not (eq major-mode 'julia-img-view-mode))
(message "Buffer %s is not a julia-img-view buffer." buf)
(setq julia-img-view--active-buffer buf)
(message "Set %s as active julia-img-view buffer." buf))))
;; plumbing
(defun julia-img-view--show-buffer (imgdata repl-buf beg end)
"Display the image in IMGDATA in the active plot buffer.
The additional arguments REPL-BUF, BEG, and END give the
originating `julia-repl' buffer and the region of the URI,
respectively."
(unless (julia-img-view-active-buffer)
(julia-img-view-create-buffer))
(save-window-excursion
(let ((inhibit-read-only t)
(inhibit-message t))
;; display the image in the active plot buffer
(with-current-buffer (julia-img-view-active-buffer)
(erase-buffer)
(insert imgdata)
(julia-img-view-mode)
(set-buffer-modified-p nil))
;; replace the text in the REPL buffer with a link to the plot buffer
(with-current-buffer repl-buf
(delete-region beg end)
(goto-char beg)
(insert (format "↪ buffer: %s" (buffer-name (julia-img-view-active-buffer))))
(make-button beg (point)
'action `(lambda (b) (pop-to-buffer ,(julia-img-view-active-buffer)))
'follow-link t
'help-echo "Go to image buffer")))))
(defun julia-img-view--show-inline (imgdata repl-buf beg end)
"Insert the image in IMGDATA into the buffer REPL-BUF as text property between BEG and END."
(with-current-buffer repl-buf
(let* ((inhibit-read-only t)
;; if emacs is compiled with imagemagick, we resize the image to fit
;; comfortably into the smallest window that is visiting the
;; `julia-repl' buffer.
(winlist (get-buffer-window-list (julia-repl-inferior-buffer) nil 'active))
(wd (sort (mapcar (lambda (w) (window-body-width w t)) winlist) #'<))
(ht (sort (mapcar (lambda (w) (window-body-height w t)) winlist) #'<))
(img (when (and wd ht (image-type-available-p 'imagemagick))
(cons 'image `(:type imagemagick
:data ,imgdata
:max-width ,(round (* 0.75 (seq-min wd)))
:max-height ,(round (* 0.8 (seq-min ht))))))))
(add-text-properties beg end `(display ,(if img img (create-image imgdata nil t))
modification-hooks (iimage-modification-hook))))))
(defun julia-img-view--process-output (proc str)
"Addition to julia's process filter that extracts image URIs.
PROC is the sending process, STR is the raw string and is ignored."
(let ((repl-buf (julia-repl--live-buffer)) (file))
(when (and repl-buf (eq (get-buffer-process repl-buf) proc))
(with-current-buffer repl-buf
;; search for image uri, load it, and put image where it should go.
(save-excursion
(goto-char julia-img-view--last-point)
(while (re-search-forward julia-img-view--img-uri-regexp nil t)
(when (and (setq file (match-string 1)) (file-exists-p file))
(let ((imgdata (with-temp-buffer (insert-file-contents file)
(string-to-unibyte (buffer-string))))
(beg (match-beginning 0))
(end (match-end 0)))
(delete-file file) ; done reading image, can delete
(funcall (if (julia-img-view-active-buffer)
#'julia-img-view--show-buffer #'julia-img-view--show-inline)
imgdata repl-buf beg end)))))
;; save point for the next time.
(setq julia-img-view--last-point (point))))))
(defun julia-img-view--enable-advice ()
"Advise the process filter of the `julia-repl' process."
(defvar-local julia-img-view--last-point 0)
(add-function :after (process-filter (get-buffer-process (julia-repl--live-buffer)))
#'julia-img-view--process-output))
;;;###autoload
(defun julia-img-view-setup ()
"Set up the `julia-img-view' tools."
(if (not (display-graphic-p))
(message "No graphical display, not enabling `julia-img-view'")
(add-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(add-hook 'julia-repl-hook #'julia-img-view-minor-mode)))
(defun julia-img-view-unload-function ()
"Deactivate and remove hooks and advice."
(let ((repl-buf (julia-repl--live-buffer)))
(when (buffer-live-p repl-buf)
(remove-function (process-filter (get-buffer-process repl-buf))
#'julia-img-view-process-output)))
(remove-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(remove-hook 'julia-repl-hook #'julia-img-view-minor-mode))
;; mode definitions
;;;###autoload
(define-minor-mode julia-img-view-minor-mode
"Minor mode for showing images and plots inline or in plot buffers." nil nil
`((,(kbd "C-x j i c") . julia-img-view-create-buffer)
(,(kbd "C-x j i a") . julia-img-view-active-buffer)
(,(kbd "C-x j i d") . julia-img-view-disable-buffers)
(,(kbd "C-x j i m") . julia-img-view-mark-buffer-active)))
;;;###autoload
(define-derived-mode julia-img-view-mode image-mode "Julia Image"
"A mode for displaying Julia images. This just aliases `image-mode'"
(julia-img-view-minor-mode))
(provide 'julia-img-view)
;;; julia-img-view.el ends here
| 17088 | ;;; julia-img-view.el --- Display julia plots and images -*- lexical-binding:t -*-
;; Copyright (c) 2019 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Keywords: languages
;; Version: 0.1
;; Package-Requires: ((emacs "25") julia-repl)
;;; Usage:
;; The set-up function hooks into all places where it should and together with
;; the julia code given above, inline images should just work.
;;
;; For images in dedicated plot buffers, the package defines
;; julia-img-minor-mode, which gives a key map for controlling the plot
;; windows. The idea behind this package is that at any point in time, zero or
;; one image-mode (in this package aliased to julia-img-view-mode) buffers is
;; considered /active/. In the case that the REPL detects an image and a
;; julia-img-view-mode buffer is active, it displays the image in that
;; buffer. There can be multiple julia-img-view-mode-buffers if you want to
;; open multiple images, but the only buffer updated by the REPL is the
;; currently active one.
;;
;; For more detailed information, please consult the accompanying README.org
;; file.
;;; License:
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to
;; deal in the Software without restriction, including without limitation the
;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;; sell copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;; IN THE SOFTWARE.
;;; Commentary:
;; This package contains a small set of tools meant to enhance the image
;; viewing and plotting experience when using `julia-repl' in Emacs. It
;; contains two main tools:
;; 1. Inline display of images/plots
;; 2. Display of images/plots in dedicated plot buffers
;; See the provided README.org for additional discussion.
;;; Code:
(require 'iimage)
(require 'button)
(require 'julia-repl)
;; customizations, constants, and variables
(defgroup julia-img-view nil
"Display julia plots and images"
:group 'julia)
(defcustom julia-img-view-buffer-prefix "julia-img"
"The default prefix for all image buffers.")
(defvar julia-img-view--active-buffer nil
"Holds the current active image buffer.")
(defconst julia-img-view--img-uri-regexp "juliaimg:\\([-+./_0-9a-zA-Z]+\\)"
"The regular expression that matches julia's image URI output.")
;; interface
(defun julia-img-view-create-buffer (arg)
"Make a new image buffer and mark it as active.
When called with prefix argument ARG, prompt for a custom name
prefix."
(interactive "P")
(let* ((uniquify-buffer-name-style nil)
(prefix (when arg (read-from-minibuffer "Image buffer name prefix: ")))
(buf (generate-new-buffer (or prefix julia-img-view-buffer-prefix))))
(with-current-buffer buf (read-only-mode))
(setq julia-img-view--active-buffer buf)
(display-buffer buf)
(message "Created new julia-img-view buffer %s." buf)))
(defun julia-img-view-active-buffer ()
"Get the active image buffer.
When called interactively, pop to it instead."
(interactive)
(when (buffer-live-p julia-img-view--active-buffer)
(if (called-interactively-p)
(pop-to-buffer julia-img-view--active-buffer)
julia-img-view--active-buffer)))
(defun julia-img-view-disable-buffers ()
"Disable any active image buffers and fall back to inline plotting."
(interactive)
(setq julia-img-view--active-buffer nil)
(message "Disabled julia-img-view buffers."))
(defun julia-img-view-mark-buffer-active ()
"Mark the selected buffer as active."
(interactive)
(let ((buf (current-buffer)))
(if (not (eq major-mode 'julia-img-view-mode))
(message "Buffer %s is not a julia-img-view buffer." buf)
(setq julia-img-view--active-buffer buf)
(message "Set %s as active julia-img-view buffer." buf))))
;; plumbing
(defun julia-img-view--show-buffer (imgdata repl-buf beg end)
"Display the image in IMGDATA in the active plot buffer.
The additional arguments REPL-BUF, BEG, and END give the
originating `julia-repl' buffer and the region of the URI,
respectively."
(unless (julia-img-view-active-buffer)
(julia-img-view-create-buffer))
(save-window-excursion
(let ((inhibit-read-only t)
(inhibit-message t))
;; display the image in the active plot buffer
(with-current-buffer (julia-img-view-active-buffer)
(erase-buffer)
(insert imgdata)
(julia-img-view-mode)
(set-buffer-modified-p nil))
;; replace the text in the REPL buffer with a link to the plot buffer
(with-current-buffer repl-buf
(delete-region beg end)
(goto-char beg)
(insert (format "↪ buffer: %s" (buffer-name (julia-img-view-active-buffer))))
(make-button beg (point)
'action `(lambda (b) (pop-to-buffer ,(julia-img-view-active-buffer)))
'follow-link t
'help-echo "Go to image buffer")))))
(defun julia-img-view--show-inline (imgdata repl-buf beg end)
"Insert the image in IMGDATA into the buffer REPL-BUF as text property between BEG and END."
(with-current-buffer repl-buf
(let* ((inhibit-read-only t)
;; if emacs is compiled with imagemagick, we resize the image to fit
;; comfortably into the smallest window that is visiting the
;; `julia-repl' buffer.
(winlist (get-buffer-window-list (julia-repl-inferior-buffer) nil 'active))
(wd (sort (mapcar (lambda (w) (window-body-width w t)) winlist) #'<))
(ht (sort (mapcar (lambda (w) (window-body-height w t)) winlist) #'<))
(img (when (and wd ht (image-type-available-p 'imagemagick))
(cons 'image `(:type imagemagick
:data ,imgdata
:max-width ,(round (* 0.75 (seq-min wd)))
:max-height ,(round (* 0.8 (seq-min ht))))))))
(add-text-properties beg end `(display ,(if img img (create-image imgdata nil t))
modification-hooks (iimage-modification-hook))))))
(defun julia-img-view--process-output (proc str)
"Addition to julia's process filter that extracts image URIs.
PROC is the sending process, STR is the raw string and is ignored."
(let ((repl-buf (julia-repl--live-buffer)) (file))
(when (and repl-buf (eq (get-buffer-process repl-buf) proc))
(with-current-buffer repl-buf
;; search for image uri, load it, and put image where it should go.
(save-excursion
(goto-char julia-img-view--last-point)
(while (re-search-forward julia-img-view--img-uri-regexp nil t)
(when (and (setq file (match-string 1)) (file-exists-p file))
(let ((imgdata (with-temp-buffer (insert-file-contents file)
(string-to-unibyte (buffer-string))))
(beg (match-beginning 0))
(end (match-end 0)))
(delete-file file) ; done reading image, can delete
(funcall (if (julia-img-view-active-buffer)
#'julia-img-view--show-buffer #'julia-img-view--show-inline)
imgdata repl-buf beg end)))))
;; save point for the next time.
(setq julia-img-view--last-point (point))))))
(defun julia-img-view--enable-advice ()
"Advise the process filter of the `julia-repl' process."
(defvar-local julia-img-view--last-point 0)
(add-function :after (process-filter (get-buffer-process (julia-repl--live-buffer)))
#'julia-img-view--process-output))
;;;###autoload
(defun julia-img-view-setup ()
"Set up the `julia-img-view' tools."
(if (not (display-graphic-p))
(message "No graphical display, not enabling `julia-img-view'")
(add-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(add-hook 'julia-repl-hook #'julia-img-view-minor-mode)))
(defun julia-img-view-unload-function ()
"Deactivate and remove hooks and advice."
(let ((repl-buf (julia-repl--live-buffer)))
(when (buffer-live-p repl-buf)
(remove-function (process-filter (get-buffer-process repl-buf))
#'julia-img-view-process-output)))
(remove-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(remove-hook 'julia-repl-hook #'julia-img-view-minor-mode))
;; mode definitions
;;;###autoload
(define-minor-mode julia-img-view-minor-mode
"Minor mode for showing images and plots inline or in plot buffers." nil nil
`((,(kbd "C-x j i c") . julia-img-view-create-buffer)
(,(kbd "C-x j i a") . julia-img-view-active-buffer)
(,(kbd "C-x j i d") . julia-img-view-disable-buffers)
(,(kbd "C-x j i m") . julia-img-view-mark-buffer-active)))
;;;###autoload
(define-derived-mode julia-img-view-mode image-mode "Julia Image"
"A mode for displaying Julia images. This just aliases `image-mode'"
(julia-img-view-minor-mode))
(provide 'julia-img-view)
;;; julia-img-view.el ends here
| true | ;;; julia-img-view.el --- Display julia plots and images -*- lexical-binding:t -*-
;; Copyright (c) 2019 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Keywords: languages
;; Version: 0.1
;; Package-Requires: ((emacs "25") julia-repl)
;;; Usage:
;; The set-up function hooks into all places where it should and together with
;; the julia code given above, inline images should just work.
;;
;; For images in dedicated plot buffers, the package defines
;; julia-img-minor-mode, which gives a key map for controlling the plot
;; windows. The idea behind this package is that at any point in time, zero or
;; one image-mode (in this package aliased to julia-img-view-mode) buffers is
;; considered /active/. In the case that the REPL detects an image and a
;; julia-img-view-mode buffer is active, it displays the image in that
;; buffer. There can be multiple julia-img-view-mode-buffers if you want to
;; open multiple images, but the only buffer updated by the REPL is the
;; currently active one.
;;
;; For more detailed information, please consult the accompanying README.org
;; file.
;;; License:
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to
;; deal in the Software without restriction, including without limitation the
;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;; sell copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;; IN THE SOFTWARE.
;;; Commentary:
;; This package contains a small set of tools meant to enhance the image
;; viewing and plotting experience when using `julia-repl' in Emacs. It
;; contains two main tools:
;; 1. Inline display of images/plots
;; 2. Display of images/plots in dedicated plot buffers
;; See the provided README.org for additional discussion.
;;; Code:
(require 'iimage)
(require 'button)
(require 'julia-repl)
;; customizations, constants, and variables
(defgroup julia-img-view nil
"Display julia plots and images"
:group 'julia)
(defcustom julia-img-view-buffer-prefix "julia-img"
"The default prefix for all image buffers.")
(defvar julia-img-view--active-buffer nil
"Holds the current active image buffer.")
(defconst julia-img-view--img-uri-regexp "juliaimg:\\([-+./_0-9a-zA-Z]+\\)"
"The regular expression that matches julia's image URI output.")
;; interface
(defun julia-img-view-create-buffer (arg)
"Make a new image buffer and mark it as active.
When called with prefix argument ARG, prompt for a custom name
prefix."
(interactive "P")
(let* ((uniquify-buffer-name-style nil)
(prefix (when arg (read-from-minibuffer "Image buffer name prefix: ")))
(buf (generate-new-buffer (or prefix julia-img-view-buffer-prefix))))
(with-current-buffer buf (read-only-mode))
(setq julia-img-view--active-buffer buf)
(display-buffer buf)
(message "Created new julia-img-view buffer %s." buf)))
(defun julia-img-view-active-buffer ()
"Get the active image buffer.
When called interactively, pop to it instead."
(interactive)
(when (buffer-live-p julia-img-view--active-buffer)
(if (called-interactively-p)
(pop-to-buffer julia-img-view--active-buffer)
julia-img-view--active-buffer)))
(defun julia-img-view-disable-buffers ()
"Disable any active image buffers and fall back to inline plotting."
(interactive)
(setq julia-img-view--active-buffer nil)
(message "Disabled julia-img-view buffers."))
(defun julia-img-view-mark-buffer-active ()
"Mark the selected buffer as active."
(interactive)
(let ((buf (current-buffer)))
(if (not (eq major-mode 'julia-img-view-mode))
(message "Buffer %s is not a julia-img-view buffer." buf)
(setq julia-img-view--active-buffer buf)
(message "Set %s as active julia-img-view buffer." buf))))
;; plumbing
(defun julia-img-view--show-buffer (imgdata repl-buf beg end)
"Display the image in IMGDATA in the active plot buffer.
The additional arguments REPL-BUF, BEG, and END give the
originating `julia-repl' buffer and the region of the URI,
respectively."
(unless (julia-img-view-active-buffer)
(julia-img-view-create-buffer))
(save-window-excursion
(let ((inhibit-read-only t)
(inhibit-message t))
;; display the image in the active plot buffer
(with-current-buffer (julia-img-view-active-buffer)
(erase-buffer)
(insert imgdata)
(julia-img-view-mode)
(set-buffer-modified-p nil))
;; replace the text in the REPL buffer with a link to the plot buffer
(with-current-buffer repl-buf
(delete-region beg end)
(goto-char beg)
(insert (format "↪ buffer: %s" (buffer-name (julia-img-view-active-buffer))))
(make-button beg (point)
'action `(lambda (b) (pop-to-buffer ,(julia-img-view-active-buffer)))
'follow-link t
'help-echo "Go to image buffer")))))
(defun julia-img-view--show-inline (imgdata repl-buf beg end)
"Insert the image in IMGDATA into the buffer REPL-BUF as text property between BEG and END."
(with-current-buffer repl-buf
(let* ((inhibit-read-only t)
;; if emacs is compiled with imagemagick, we resize the image to fit
;; comfortably into the smallest window that is visiting the
;; `julia-repl' buffer.
(winlist (get-buffer-window-list (julia-repl-inferior-buffer) nil 'active))
(wd (sort (mapcar (lambda (w) (window-body-width w t)) winlist) #'<))
(ht (sort (mapcar (lambda (w) (window-body-height w t)) winlist) #'<))
(img (when (and wd ht (image-type-available-p 'imagemagick))
(cons 'image `(:type imagemagick
:data ,imgdata
:max-width ,(round (* 0.75 (seq-min wd)))
:max-height ,(round (* 0.8 (seq-min ht))))))))
(add-text-properties beg end `(display ,(if img img (create-image imgdata nil t))
modification-hooks (iimage-modification-hook))))))
(defun julia-img-view--process-output (proc str)
"Addition to julia's process filter that extracts image URIs.
PROC is the sending process, STR is the raw string and is ignored."
(let ((repl-buf (julia-repl--live-buffer)) (file))
(when (and repl-buf (eq (get-buffer-process repl-buf) proc))
(with-current-buffer repl-buf
;; search for image uri, load it, and put image where it should go.
(save-excursion
(goto-char julia-img-view--last-point)
(while (re-search-forward julia-img-view--img-uri-regexp nil t)
(when (and (setq file (match-string 1)) (file-exists-p file))
(let ((imgdata (with-temp-buffer (insert-file-contents file)
(string-to-unibyte (buffer-string))))
(beg (match-beginning 0))
(end (match-end 0)))
(delete-file file) ; done reading image, can delete
(funcall (if (julia-img-view-active-buffer)
#'julia-img-view--show-buffer #'julia-img-view--show-inline)
imgdata repl-buf beg end)))))
;; save point for the next time.
(setq julia-img-view--last-point (point))))))
(defun julia-img-view--enable-advice ()
"Advise the process filter of the `julia-repl' process."
(defvar-local julia-img-view--last-point 0)
(add-function :after (process-filter (get-buffer-process (julia-repl--live-buffer)))
#'julia-img-view--process-output))
;;;###autoload
(defun julia-img-view-setup ()
"Set up the `julia-img-view' tools."
(if (not (display-graphic-p))
(message "No graphical display, not enabling `julia-img-view'")
(add-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(add-hook 'julia-repl-hook #'julia-img-view-minor-mode)))
(defun julia-img-view-unload-function ()
"Deactivate and remove hooks and advice."
(let ((repl-buf (julia-repl--live-buffer)))
(when (buffer-live-p repl-buf)
(remove-function (process-filter (get-buffer-process repl-buf))
#'julia-img-view-process-output)))
(remove-hook 'julia-repl-hook #'julia-img-view--enable-advice)
(remove-hook 'julia-repl-hook #'julia-img-view-minor-mode))
;; mode definitions
;;;###autoload
(define-minor-mode julia-img-view-minor-mode
"Minor mode for showing images and plots inline or in plot buffers." nil nil
`((,(kbd "C-x j i c") . julia-img-view-create-buffer)
(,(kbd "C-x j i a") . julia-img-view-active-buffer)
(,(kbd "C-x j i d") . julia-img-view-disable-buffers)
(,(kbd "C-x j i m") . julia-img-view-mark-buffer-active)))
;;;###autoload
(define-derived-mode julia-img-view-mode image-mode "Julia Image"
"A mode for displaying Julia images. This just aliases `image-mode'"
(julia-img-view-minor-mode))
(provide 'julia-img-view)
;;; julia-img-view.el ends here
|
[
{
"context": "e\n\n;;; Commentary:\n;; Base16: (https://github.com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: @Schnouki, based",
"end": 109,
"score": 0.9996447563171387,
"start": 97,
"tag": "USERNAME",
"value": "chriskempson"
},
{
"context": ".com/chriskempson/base16)\n\n;;; Authors:\n;; Scheme: @Schnouki, based on the Tango Desktop Project\n;; Template: ",
"end": 152,
"score": 0.997967541217804,
"start": 143,
"tag": "USERNAME",
"value": "@Schnouki"
},
{
"context": "i, based on the Tango Desktop Project\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-the",
"end": 214,
"score": 0.9998981952667236,
"start": 202,
"tag": "NAME",
"value": "Kaleb Elwert"
},
{
"context": " Tango Desktop Project\n;; Template: Kaleb Elwert <belak@coded.io>\n\n;;; Code:\n\n(require 'base16-theme)\n\n(defvar bas",
"end": 230,
"score": 0.9999299645423889,
"start": 216,
"tag": "EMAIL",
"value": "belak@coded.io"
}
] | elpa/base16-theme-20210805.1401/base16-tango-theme.el | ik314/.emacs.d | 257 | ;; base16-tango-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: @Schnouki, based on the Tango Desktop Project
;; Template: Kaleb Elwert <belak@coded.io>
;;; Code:
(require 'base16-theme)
(defvar base16-tango-colors
'(:base00 "#2e3436"
:base01 "#8ae234"
:base02 "#fce94f"
:base03 "#555753"
:base04 "#729fcf"
:base05 "#d3d7cf"
:base06 "#ad7fa8"
:base07 "#eeeeec"
:base08 "#cc0000"
:base09 "#ef2929"
:base0A "#c4a000"
:base0B "#4e9a06"
:base0C "#06989a"
:base0D "#3465a4"
:base0E "#75507b"
:base0F "#34e2e2")
"All colors for Base16 Tango are defined here.")
;; Define the theme
(deftheme base16-tango)
;; Add all the faces to the theme
(base16-theme-define 'base16-tango base16-tango-colors)
;; Mark the theme as provided
(provide-theme 'base16-tango)
(provide 'base16-tango-theme)
;;; base16-tango-theme.el ends here
| 16864 | ;; base16-tango-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: @Schnouki, based on the Tango Desktop Project
;; Template: <NAME> <<EMAIL>>
;;; Code:
(require 'base16-theme)
(defvar base16-tango-colors
'(:base00 "#2e3436"
:base01 "#8ae234"
:base02 "#fce94f"
:base03 "#555753"
:base04 "#729fcf"
:base05 "#d3d7cf"
:base06 "#ad7fa8"
:base07 "#eeeeec"
:base08 "#cc0000"
:base09 "#ef2929"
:base0A "#c4a000"
:base0B "#4e9a06"
:base0C "#06989a"
:base0D "#3465a4"
:base0E "#75507b"
:base0F "#34e2e2")
"All colors for Base16 Tango are defined here.")
;; Define the theme
(deftheme base16-tango)
;; Add all the faces to the theme
(base16-theme-define 'base16-tango base16-tango-colors)
;; Mark the theme as provided
(provide-theme 'base16-tango)
(provide 'base16-tango-theme)
;;; base16-tango-theme.el ends here
| true | ;; base16-tango-theme.el -- A base16 colorscheme
;;; Commentary:
;; Base16: (https://github.com/chriskempson/base16)
;;; Authors:
;; Scheme: @Schnouki, based on the Tango Desktop Project
;; Template: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;; Code:
(require 'base16-theme)
(defvar base16-tango-colors
'(:base00 "#2e3436"
:base01 "#8ae234"
:base02 "#fce94f"
:base03 "#555753"
:base04 "#729fcf"
:base05 "#d3d7cf"
:base06 "#ad7fa8"
:base07 "#eeeeec"
:base08 "#cc0000"
:base09 "#ef2929"
:base0A "#c4a000"
:base0B "#4e9a06"
:base0C "#06989a"
:base0D "#3465a4"
:base0E "#75507b"
:base0F "#34e2e2")
"All colors for Base16 Tango are defined here.")
;; Define the theme
(deftheme base16-tango)
;; Add all the faces to the theme
(base16-theme-define 'base16-tango base16-tango-colors)
;; Mark the theme as provided
(provide-theme 'base16-tango)
(provide 'base16-tango-theme)
;;; base16-tango-theme.el ends here
|
[
{
"context": ";;;;;;;;;;;;\n;;;\n;;; ghc-check.el\n;;;\n\n;; Author: Kazu Yamamoto <Kazu@Mew.org>\n;; Created: Mar 9, 2014\n;; Licens",
"end": 116,
"score": 0.9998190999031067,
"start": 103,
"tag": "NAME",
"value": "Kazu Yamamoto"
},
{
"context": "\n;;; ghc-check.el\n;;;\n\n;; Author: Kazu Yamamoto <Kazu@Mew.org>\n;; Created: Mar 9, 2014\n;; License: BSD-3-claus",
"end": 130,
"score": 0.999932587146759,
"start": 118,
"tag": "EMAIL",
"value": "Kazu@Mew.org"
}
] | _archive/.emacs.d.old/elpa/ghc-20180121.418/ghc-check.el | ahmedalsudani/config | 1 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ghc-check.el
;;;
;; Author: Kazu Yamamoto <Kazu@Mew.org>
;; Created: Mar 9, 2014
;; License: BSD-3-clause
;;; Code:
(require 'ghc-func)
(require 'ghc-process)
(require 'button)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; stolen from flymake.el
(defface ghc-face-error
'((((supports :underline (:style wave)))
:underline (:style wave :color "orangered"))
(t
:inherit error))
"Face used for error lines."
:group 'ghc)
(defface ghc-face-warn
'((((supports :underline (:style wave)))
:underline (:style wave :color "gold"))
(t
:inherit warning))
"Face used for warning lines."
:group 'ghc)
(defface ghc-face-hole
'((((supports :underline (:style wave)))
:underline (:style wave :color "purple"))
(t
:inherit warning))
"Face used for hole lines."
:group 'ghc)
(defvar ghc-check-error-fringe (propertize "!" 'display '(left-fringe exclamation-mark)))
(defvar ghc-check-warning-fringe (propertize "?" 'display '(left-fringe question-mark)))
(defvar ghc-check-hole-fringe (propertize "_" 'display '(left-fringe horizontal-bar)))
(defvar ghc-display-error nil
"*How to display errors/warnings when using 'M-n' and 'M-p':
nil do not display errors/warnings.
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in a new buffer.
")
(defvar ghc-display-hole 'other-buffer
"*How to display hole information when using 'C-c C-j' and 'C-c C-h'
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in the a new buffer"
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-syntax ()
(interactive)
;; Only check syntax of visible buffers
(when (and (buffer-file-name)
(file-exists-p (buffer-file-name)))
(ghc-with-process (ghc-check-send)
'ghc-check-callback
(lambda () (setq mode-line-process " -:-")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ghc-defstruct hilit-info file line msg err hole coln)
(defun ghc-check-send ()
(let ((file (buffer-file-name)))
(if ghc-check-command
(let ((opts (ghc-haskell-list-of-string ghc-hlint-options)))
(if opts
(format "lint %s %s\n" opts file)
(format "lint %s\n" file)))
(format "check %s\n" file))))
(defun ghc-haskell-list-of-string (los)
(when los
(concat "["
(mapconcat (lambda (x) (concat "\"" x "\"")) los ", ")
"]")))
(defun ghc-check-callback (status)
(cond
((eq status 'ok)
(let* ((errs (ghc-read-lisp-this-buffer))
(infos (ghc-to-info errs)))
(cond
(infos
(let ((file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos)))
(t
(ghc-with-current-buffer ghc-process-original-buffer
(remove-overlays (point-min) (point-max) 'ghc-check t))))
(ghc-with-current-buffer ghc-process-original-buffer
(let ((len (length infos)))
(if (= len 0)
(setq mode-line-process "")
(let* ((errs (ghc-filter 'ghc-hilit-info-get-err infos))
(elen (length errs))
(wlen (- len elen)))
(setq mode-line-process (format " %d:%d" elen wlen)))))
(force-mode-line-update))))
(t
(let* ((err (ghc-unescape-string (buffer-substring-no-properties (+ (point) 3) (point-max))))
(info (ghc-make-hilit-info
:file "Fail errors:"
:line 0
:coln 0
:msg err
:err t
:hole nil))
(infos (list info))
(file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos))
(ghc-with-current-buffer ghc-process-original-buffer
(setq mode-line-process " failed")
(force-mode-line-update)))))
(defun ghc-to-info (errs)
;; [^\t] to include \n.
(let ((regex "^\\([^\n]*\\):\\([0-9]+\\):\\([0-9]+\\): *\\([^\t]+\\)")
infos)
(dolist (err errs (nreverse infos))
(when (string-match regex err)
(let* ((file (expand-file-name (match-string 1 err) ghc-process-root)) ;; for Windows
(line (string-to-number (match-string 2 err)))
(coln (string-to-number (match-string 3 err)))
(msg (match-string 4 err))
(wrn (string-match "^Warning" msg))
(hole (save-match-data
(when (string-match "Found hole .\\(_[_[:alnum:]]*\\)." msg)
(match-string 1 msg))))
(info (ghc-make-hilit-info
:file file
:line line
:coln coln
:msg msg
:err (and (not wrn) (not hole))
:hole hole)))
(unless (member info infos)
(ghc-add infos info)))))))
(defun ghc-check-highlight-original-buffer (ofile buf infos)
(ghc-with-current-buffer buf
(remove-overlays (point-min) (point-max) 'ghc-check t)
(save-excursion
(goto-char (point-min))
(dolist (info infos)
(let ((line (ghc-hilit-info-get-line info))
(msg (ghc-hilit-info-get-msg info))
(file (ghc-hilit-info-get-file info))
(err (ghc-hilit-info-get-err info))
(hole (ghc-hilit-info-get-hole info))
(coln (ghc-hilit-info-get-coln info))
beg end ovl)
;; FIXME: This is the Shlemiel painter's algorithm.
;; If this is a bottleneck for a large code, let's fix.
(goto-char (point-min))
(cond
((file-equal-p ofile file)
(if hole
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-char (length hole))
(setq end (point)))
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-sexp)
;; (skip-chars-forward "^[:space:]" (line-end-position))
(setq end (point)))))
(t
(setq beg (point))
(forward-line)
(setq end (point))))
(setq ovl (make-overlay beg end))
(overlay-put ovl 'ghc-check t)
(overlay-put ovl 'ghc-file file)
(overlay-put ovl 'ghc-msg msg)
(overlay-put ovl 'help-echo msg)
(overlay-put ovl 'ghc-hole hole)
(let ((fringe (if err ghc-check-error-fringe (if hole ghc-check-hole-fringe ghc-check-warning-fringe)))
(face (if err 'ghc-face-error (if hole 'ghc-face-hole 'ghc-face-warn))))
(overlay-put ovl 'before-string fringe)
(overlay-put ovl 'face face)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-overlay-p (ovl)
(overlay-get ovl 'ghc-check))
(defun ghc-check-overlay-at (p)
(ghc-filter 'ghc-overlay-p (overlays-at p)))
(ghc-defstruct file-msgs file msgs)
(defun ghc-get-errors-over-warnings ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
errs wrns)
(dolist (msg msgs)
(if (string-match "^Warning" msg)
(ghc-add wrns msg)
(ghc-add errs msg)))
(ghc-make-file-msgs :file file :msgs (nconc errs wrns))))))
(defun ghc-display-errors ()
(interactive)
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(insert file "\n\n")
(mapc (lambda (x) (insert x "\n\n")) msgs)))))))
(defun ghc-display-errors-to-minibuf ()
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
(defun ghc-get-only-holes ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
holes)
(dolist (msg msgs)
(if (string-match "Found hole" msg)
(ghc-add holes msg)
nil))
(ghc-make-file-msgs :file file :msgs holes)))))
;; Based on http://superuser.com/questions/331895/how-to-get-emacs-to-highlight-and-link-file-paths
(defun find-file-button (button)
(let ((text (buffer-substring (button-start button) (button-end button))))
(when (string-match "\\(/[^:]*\\):\\([[:digit:]]+\\):\\([[:digit:]]+\\)" text)
(let* ((file (match-string 1 text))
(line (string-to-number (match-string 2 text)))
(coln (string-to-number (match-string 3 text)))
(buf (find-file file)))
(with-current-buffer buf
(let* ((this-line (line-number-at-pos))
(diff (- line this-line)))
(beginning-of-line)
(forward-line diff)
(forward-char (1- coln))))))))
(define-button-type 'find-file-button
'follow-link t
'help-echo "mouse-2, RET: Go to definition"
'action #'find-file-button)
(defun buttonize-buffer ()
"turn all file paths into buttons"
(save-excursion
(goto-char (point-min))
(while (re-search-forward "/[^ \t:]*:[[:digit:]]+:[[:digit:]]+" nil t)
(make-button (match-beginning 0) (match-end 0) :type 'find-file-button))))
(defun ghc-display-holes ()
(interactive)
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let ((msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(progn
(mapc (lambda (x) (insert x "\n\n")) msgs)
(buttonize-buffer))))))))
(defun ghc-display-holes-to-minibuf ()
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-goto-prev-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-next-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-prev-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
(defun ghc-goto-next-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-insert-from-warning ()
(interactive)
(let ((ret t))
(dolist (data (delete-dups (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) (ghc-check-overlay-at (point)))) ret)
(save-excursion
(cond
((string-match "Inferred type: \\|no type signature:" data)
(beginning-of-line)
(insert-before-markers (ghc-extract-type data) "\n"))
((string-match "lacks an accompanying binding" data)
(beginning-of-line)
(when (looking-at "^\\([^ ]+\\) *::")
(save-match-data
(forward-line)
(if (not (bolp)) (insert "\n")))
(insert (match-string 1) " = undefined\n")))
;; GHC 7.8 uses Unicode for single-quotes.
((string-match "Not in scope: type constructor or class .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "Not in scope: data constructor .\\([^\n]+\\)." data)
;; if the type of data constructor, it would be nice.
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "\n[ ]+.\\([^ ]+\\). is a data constructor of .\\([^\n]+\\).\n" data)
(let* ((old (match-string 1 data))
(type-const (match-string 2 data))
(new (format "%s(%s)" type-const old)))
(ghc-check-replace old new)))
((string-match "Not in scope: .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(if (or (string-match "\\." sym) ;; qualified
(y-or-n-p (format "Import module for %s?" sym)))
(ghc-ins-mod sym)
(unless (re-search-forward "^$" nil t)
(goto-char (point-max))
(insert "\n"))
(insert "\n" (ghc-enclose sym) " = undefined\n"))))
((string-match "Pattern match(es) are non-exhaustive" data)
(let* ((fn (ghc-get-function-name))
(arity (ghc-get-function-arity fn)))
(ghc-insert-underscore fn arity)))
((string-match "Found:\n[ ]+\\([^\t]+\\)\nWhy not:\n[ ]+\\([^\t]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
((string-match "Found hole .\\(_[_[:alnum:]]*\\). with type: \\([^\t\n]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
(t
(setq ret nil)))))))
(defun ghc-check-replace (old new)
(beginning-of-line)
(when (search-forward old nil t)
(let ((end (point)))
(search-backward old nil t)
(delete-region (point) end))
(insert new)))
(defun ghc-extract-type (str)
(with-temp-buffer
(insert str)
(goto-char (point-min))
(when (re-search-forward "Inferred type: \\|no type signature:\\( \\|\n +\\)?" nil t)
(delete-region (point-min) (point)))
(when (re-search-forward " forall [^.]+\\." nil t)
(replace-match ""))
(while (re-search-forward "\n +" nil t)
(replace-match " "))
(goto-char (point-min))
(while (re-search-forward "\\[Char\\]" nil t)
(replace-match "String"))
(buffer-substring-no-properties (point-min) (point-max))))
(defun ghc-get-function-name ()
(save-excursion
(beginning-of-line)
(when (looking-at "\\([^ ]+\\) ")
(match-string 1))))
(defun ghc-get-function-arity (fn)
(when fn
(save-excursion
(let ((regex (format "^%s *::" (regexp-quote fn))))
(when (re-search-backward regex nil t)
(ghc-get-function-arity0))))))
(defun ghc-get-function-arity0 ()
(let ((end (save-excursion (end-of-line) (point)))
(arity 0))
(while (search-forward "->" end t)
(setq arity (1+ arity)))
arity))
(defun ghc-insert-underscore (fn ar)
(when fn
(let ((arity (or ar 1)))
(save-excursion
(goto-char (point-max))
(re-search-backward (format "^%s *::" (regexp-quote fn)))
(forward-line)
(re-search-forward "^$" nil t)
(insert fn)
(dotimes (_i arity)
(insert " _"))
(insert " = error \"" fn "\"\n")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-jump-file ()
(interactive)
(let* ((ovl (car (ghc-check-overlay-at 1)))
(file (if ovl (overlay-get ovl 'ghc-file))))
(if file (find-file file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar ghc-hlint-options nil "*Hlint options")
(defvar ghc-check-command nil)
(defun ghc-toggle-check-command ()
(interactive)
(setq ghc-check-command (not ghc-check-command))
(if ghc-check-command
(message "Syntax check with hlint")
(message "Syntax check with GHC")))
(provide 'ghc-check)
| 3039 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ghc-check.el
;;;
;; Author: <NAME> <<EMAIL>>
;; Created: Mar 9, 2014
;; License: BSD-3-clause
;;; Code:
(require 'ghc-func)
(require 'ghc-process)
(require 'button)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; stolen from flymake.el
(defface ghc-face-error
'((((supports :underline (:style wave)))
:underline (:style wave :color "orangered"))
(t
:inherit error))
"Face used for error lines."
:group 'ghc)
(defface ghc-face-warn
'((((supports :underline (:style wave)))
:underline (:style wave :color "gold"))
(t
:inherit warning))
"Face used for warning lines."
:group 'ghc)
(defface ghc-face-hole
'((((supports :underline (:style wave)))
:underline (:style wave :color "purple"))
(t
:inherit warning))
"Face used for hole lines."
:group 'ghc)
(defvar ghc-check-error-fringe (propertize "!" 'display '(left-fringe exclamation-mark)))
(defvar ghc-check-warning-fringe (propertize "?" 'display '(left-fringe question-mark)))
(defvar ghc-check-hole-fringe (propertize "_" 'display '(left-fringe horizontal-bar)))
(defvar ghc-display-error nil
"*How to display errors/warnings when using 'M-n' and 'M-p':
nil do not display errors/warnings.
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in a new buffer.
")
(defvar ghc-display-hole 'other-buffer
"*How to display hole information when using 'C-c C-j' and 'C-c C-h'
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in the a new buffer"
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-syntax ()
(interactive)
;; Only check syntax of visible buffers
(when (and (buffer-file-name)
(file-exists-p (buffer-file-name)))
(ghc-with-process (ghc-check-send)
'ghc-check-callback
(lambda () (setq mode-line-process " -:-")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ghc-defstruct hilit-info file line msg err hole coln)
(defun ghc-check-send ()
(let ((file (buffer-file-name)))
(if ghc-check-command
(let ((opts (ghc-haskell-list-of-string ghc-hlint-options)))
(if opts
(format "lint %s %s\n" opts file)
(format "lint %s\n" file)))
(format "check %s\n" file))))
(defun ghc-haskell-list-of-string (los)
(when los
(concat "["
(mapconcat (lambda (x) (concat "\"" x "\"")) los ", ")
"]")))
(defun ghc-check-callback (status)
(cond
((eq status 'ok)
(let* ((errs (ghc-read-lisp-this-buffer))
(infos (ghc-to-info errs)))
(cond
(infos
(let ((file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos)))
(t
(ghc-with-current-buffer ghc-process-original-buffer
(remove-overlays (point-min) (point-max) 'ghc-check t))))
(ghc-with-current-buffer ghc-process-original-buffer
(let ((len (length infos)))
(if (= len 0)
(setq mode-line-process "")
(let* ((errs (ghc-filter 'ghc-hilit-info-get-err infos))
(elen (length errs))
(wlen (- len elen)))
(setq mode-line-process (format " %d:%d" elen wlen)))))
(force-mode-line-update))))
(t
(let* ((err (ghc-unescape-string (buffer-substring-no-properties (+ (point) 3) (point-max))))
(info (ghc-make-hilit-info
:file "Fail errors:"
:line 0
:coln 0
:msg err
:err t
:hole nil))
(infos (list info))
(file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos))
(ghc-with-current-buffer ghc-process-original-buffer
(setq mode-line-process " failed")
(force-mode-line-update)))))
(defun ghc-to-info (errs)
;; [^\t] to include \n.
(let ((regex "^\\([^\n]*\\):\\([0-9]+\\):\\([0-9]+\\): *\\([^\t]+\\)")
infos)
(dolist (err errs (nreverse infos))
(when (string-match regex err)
(let* ((file (expand-file-name (match-string 1 err) ghc-process-root)) ;; for Windows
(line (string-to-number (match-string 2 err)))
(coln (string-to-number (match-string 3 err)))
(msg (match-string 4 err))
(wrn (string-match "^Warning" msg))
(hole (save-match-data
(when (string-match "Found hole .\\(_[_[:alnum:]]*\\)." msg)
(match-string 1 msg))))
(info (ghc-make-hilit-info
:file file
:line line
:coln coln
:msg msg
:err (and (not wrn) (not hole))
:hole hole)))
(unless (member info infos)
(ghc-add infos info)))))))
(defun ghc-check-highlight-original-buffer (ofile buf infos)
(ghc-with-current-buffer buf
(remove-overlays (point-min) (point-max) 'ghc-check t)
(save-excursion
(goto-char (point-min))
(dolist (info infos)
(let ((line (ghc-hilit-info-get-line info))
(msg (ghc-hilit-info-get-msg info))
(file (ghc-hilit-info-get-file info))
(err (ghc-hilit-info-get-err info))
(hole (ghc-hilit-info-get-hole info))
(coln (ghc-hilit-info-get-coln info))
beg end ovl)
;; FIXME: This is the Shlemiel painter's algorithm.
;; If this is a bottleneck for a large code, let's fix.
(goto-char (point-min))
(cond
((file-equal-p ofile file)
(if hole
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-char (length hole))
(setq end (point)))
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-sexp)
;; (skip-chars-forward "^[:space:]" (line-end-position))
(setq end (point)))))
(t
(setq beg (point))
(forward-line)
(setq end (point))))
(setq ovl (make-overlay beg end))
(overlay-put ovl 'ghc-check t)
(overlay-put ovl 'ghc-file file)
(overlay-put ovl 'ghc-msg msg)
(overlay-put ovl 'help-echo msg)
(overlay-put ovl 'ghc-hole hole)
(let ((fringe (if err ghc-check-error-fringe (if hole ghc-check-hole-fringe ghc-check-warning-fringe)))
(face (if err 'ghc-face-error (if hole 'ghc-face-hole 'ghc-face-warn))))
(overlay-put ovl 'before-string fringe)
(overlay-put ovl 'face face)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-overlay-p (ovl)
(overlay-get ovl 'ghc-check))
(defun ghc-check-overlay-at (p)
(ghc-filter 'ghc-overlay-p (overlays-at p)))
(ghc-defstruct file-msgs file msgs)
(defun ghc-get-errors-over-warnings ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
errs wrns)
(dolist (msg msgs)
(if (string-match "^Warning" msg)
(ghc-add wrns msg)
(ghc-add errs msg)))
(ghc-make-file-msgs :file file :msgs (nconc errs wrns))))))
(defun ghc-display-errors ()
(interactive)
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(insert file "\n\n")
(mapc (lambda (x) (insert x "\n\n")) msgs)))))))
(defun ghc-display-errors-to-minibuf ()
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
(defun ghc-get-only-holes ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
holes)
(dolist (msg msgs)
(if (string-match "Found hole" msg)
(ghc-add holes msg)
nil))
(ghc-make-file-msgs :file file :msgs holes)))))
;; Based on http://superuser.com/questions/331895/how-to-get-emacs-to-highlight-and-link-file-paths
(defun find-file-button (button)
(let ((text (buffer-substring (button-start button) (button-end button))))
(when (string-match "\\(/[^:]*\\):\\([[:digit:]]+\\):\\([[:digit:]]+\\)" text)
(let* ((file (match-string 1 text))
(line (string-to-number (match-string 2 text)))
(coln (string-to-number (match-string 3 text)))
(buf (find-file file)))
(with-current-buffer buf
(let* ((this-line (line-number-at-pos))
(diff (- line this-line)))
(beginning-of-line)
(forward-line diff)
(forward-char (1- coln))))))))
(define-button-type 'find-file-button
'follow-link t
'help-echo "mouse-2, RET: Go to definition"
'action #'find-file-button)
(defun buttonize-buffer ()
"turn all file paths into buttons"
(save-excursion
(goto-char (point-min))
(while (re-search-forward "/[^ \t:]*:[[:digit:]]+:[[:digit:]]+" nil t)
(make-button (match-beginning 0) (match-end 0) :type 'find-file-button))))
(defun ghc-display-holes ()
(interactive)
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let ((msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(progn
(mapc (lambda (x) (insert x "\n\n")) msgs)
(buttonize-buffer))))))))
(defun ghc-display-holes-to-minibuf ()
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-goto-prev-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-next-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-prev-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
(defun ghc-goto-next-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-insert-from-warning ()
(interactive)
(let ((ret t))
(dolist (data (delete-dups (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) (ghc-check-overlay-at (point)))) ret)
(save-excursion
(cond
((string-match "Inferred type: \\|no type signature:" data)
(beginning-of-line)
(insert-before-markers (ghc-extract-type data) "\n"))
((string-match "lacks an accompanying binding" data)
(beginning-of-line)
(when (looking-at "^\\([^ ]+\\) *::")
(save-match-data
(forward-line)
(if (not (bolp)) (insert "\n")))
(insert (match-string 1) " = undefined\n")))
;; GHC 7.8 uses Unicode for single-quotes.
((string-match "Not in scope: type constructor or class .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "Not in scope: data constructor .\\([^\n]+\\)." data)
;; if the type of data constructor, it would be nice.
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "\n[ ]+.\\([^ ]+\\). is a data constructor of .\\([^\n]+\\).\n" data)
(let* ((old (match-string 1 data))
(type-const (match-string 2 data))
(new (format "%s(%s)" type-const old)))
(ghc-check-replace old new)))
((string-match "Not in scope: .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(if (or (string-match "\\." sym) ;; qualified
(y-or-n-p (format "Import module for %s?" sym)))
(ghc-ins-mod sym)
(unless (re-search-forward "^$" nil t)
(goto-char (point-max))
(insert "\n"))
(insert "\n" (ghc-enclose sym) " = undefined\n"))))
((string-match "Pattern match(es) are non-exhaustive" data)
(let* ((fn (ghc-get-function-name))
(arity (ghc-get-function-arity fn)))
(ghc-insert-underscore fn arity)))
((string-match "Found:\n[ ]+\\([^\t]+\\)\nWhy not:\n[ ]+\\([^\t]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
((string-match "Found hole .\\(_[_[:alnum:]]*\\). with type: \\([^\t\n]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
(t
(setq ret nil)))))))
(defun ghc-check-replace (old new)
(beginning-of-line)
(when (search-forward old nil t)
(let ((end (point)))
(search-backward old nil t)
(delete-region (point) end))
(insert new)))
(defun ghc-extract-type (str)
(with-temp-buffer
(insert str)
(goto-char (point-min))
(when (re-search-forward "Inferred type: \\|no type signature:\\( \\|\n +\\)?" nil t)
(delete-region (point-min) (point)))
(when (re-search-forward " forall [^.]+\\." nil t)
(replace-match ""))
(while (re-search-forward "\n +" nil t)
(replace-match " "))
(goto-char (point-min))
(while (re-search-forward "\\[Char\\]" nil t)
(replace-match "String"))
(buffer-substring-no-properties (point-min) (point-max))))
(defun ghc-get-function-name ()
(save-excursion
(beginning-of-line)
(when (looking-at "\\([^ ]+\\) ")
(match-string 1))))
(defun ghc-get-function-arity (fn)
(when fn
(save-excursion
(let ((regex (format "^%s *::" (regexp-quote fn))))
(when (re-search-backward regex nil t)
(ghc-get-function-arity0))))))
(defun ghc-get-function-arity0 ()
(let ((end (save-excursion (end-of-line) (point)))
(arity 0))
(while (search-forward "->" end t)
(setq arity (1+ arity)))
arity))
(defun ghc-insert-underscore (fn ar)
(when fn
(let ((arity (or ar 1)))
(save-excursion
(goto-char (point-max))
(re-search-backward (format "^%s *::" (regexp-quote fn)))
(forward-line)
(re-search-forward "^$" nil t)
(insert fn)
(dotimes (_i arity)
(insert " _"))
(insert " = error \"" fn "\"\n")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-jump-file ()
(interactive)
(let* ((ovl (car (ghc-check-overlay-at 1)))
(file (if ovl (overlay-get ovl 'ghc-file))))
(if file (find-file file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar ghc-hlint-options nil "*Hlint options")
(defvar ghc-check-command nil)
(defun ghc-toggle-check-command ()
(interactive)
(setq ghc-check-command (not ghc-check-command))
(if ghc-check-command
(message "Syntax check with hlint")
(message "Syntax check with GHC")))
(provide 'ghc-check)
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ghc-check.el
;;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: Mar 9, 2014
;; License: BSD-3-clause
;;; Code:
(require 'ghc-func)
(require 'ghc-process)
(require 'button)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; stolen from flymake.el
(defface ghc-face-error
'((((supports :underline (:style wave)))
:underline (:style wave :color "orangered"))
(t
:inherit error))
"Face used for error lines."
:group 'ghc)
(defface ghc-face-warn
'((((supports :underline (:style wave)))
:underline (:style wave :color "gold"))
(t
:inherit warning))
"Face used for warning lines."
:group 'ghc)
(defface ghc-face-hole
'((((supports :underline (:style wave)))
:underline (:style wave :color "purple"))
(t
:inherit warning))
"Face used for hole lines."
:group 'ghc)
(defvar ghc-check-error-fringe (propertize "!" 'display '(left-fringe exclamation-mark)))
(defvar ghc-check-warning-fringe (propertize "?" 'display '(left-fringe question-mark)))
(defvar ghc-check-hole-fringe (propertize "_" 'display '(left-fringe horizontal-bar)))
(defvar ghc-display-error nil
"*How to display errors/warnings when using 'M-n' and 'M-p':
nil do not display errors/warnings.
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in a new buffer.
")
(defvar ghc-display-hole 'other-buffer
"*How to display hole information when using 'C-c C-j' and 'C-c C-h'
'minibuffer display errors/warnings in the minibuffer.
'other-buffer display errors/warnings in the a new buffer"
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-syntax ()
(interactive)
;; Only check syntax of visible buffers
(when (and (buffer-file-name)
(file-exists-p (buffer-file-name)))
(ghc-with-process (ghc-check-send)
'ghc-check-callback
(lambda () (setq mode-line-process " -:-")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ghc-defstruct hilit-info file line msg err hole coln)
(defun ghc-check-send ()
(let ((file (buffer-file-name)))
(if ghc-check-command
(let ((opts (ghc-haskell-list-of-string ghc-hlint-options)))
(if opts
(format "lint %s %s\n" opts file)
(format "lint %s\n" file)))
(format "check %s\n" file))))
(defun ghc-haskell-list-of-string (los)
(when los
(concat "["
(mapconcat (lambda (x) (concat "\"" x "\"")) los ", ")
"]")))
(defun ghc-check-callback (status)
(cond
((eq status 'ok)
(let* ((errs (ghc-read-lisp-this-buffer))
(infos (ghc-to-info errs)))
(cond
(infos
(let ((file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos)))
(t
(ghc-with-current-buffer ghc-process-original-buffer
(remove-overlays (point-min) (point-max) 'ghc-check t))))
(ghc-with-current-buffer ghc-process-original-buffer
(let ((len (length infos)))
(if (= len 0)
(setq mode-line-process "")
(let* ((errs (ghc-filter 'ghc-hilit-info-get-err infos))
(elen (length errs))
(wlen (- len elen)))
(setq mode-line-process (format " %d:%d" elen wlen)))))
(force-mode-line-update))))
(t
(let* ((err (ghc-unescape-string (buffer-substring-no-properties (+ (point) 3) (point-max))))
(info (ghc-make-hilit-info
:file "Fail errors:"
:line 0
:coln 0
:msg err
:err t
:hole nil))
(infos (list info))
(file ghc-process-original-file)
(buf ghc-process-original-buffer))
(ghc-check-highlight-original-buffer file buf infos))
(ghc-with-current-buffer ghc-process-original-buffer
(setq mode-line-process " failed")
(force-mode-line-update)))))
(defun ghc-to-info (errs)
;; [^\t] to include \n.
(let ((regex "^\\([^\n]*\\):\\([0-9]+\\):\\([0-9]+\\): *\\([^\t]+\\)")
infos)
(dolist (err errs (nreverse infos))
(when (string-match regex err)
(let* ((file (expand-file-name (match-string 1 err) ghc-process-root)) ;; for Windows
(line (string-to-number (match-string 2 err)))
(coln (string-to-number (match-string 3 err)))
(msg (match-string 4 err))
(wrn (string-match "^Warning" msg))
(hole (save-match-data
(when (string-match "Found hole .\\(_[_[:alnum:]]*\\)." msg)
(match-string 1 msg))))
(info (ghc-make-hilit-info
:file file
:line line
:coln coln
:msg msg
:err (and (not wrn) (not hole))
:hole hole)))
(unless (member info infos)
(ghc-add infos info)))))))
(defun ghc-check-highlight-original-buffer (ofile buf infos)
(ghc-with-current-buffer buf
(remove-overlays (point-min) (point-max) 'ghc-check t)
(save-excursion
(goto-char (point-min))
(dolist (info infos)
(let ((line (ghc-hilit-info-get-line info))
(msg (ghc-hilit-info-get-msg info))
(file (ghc-hilit-info-get-file info))
(err (ghc-hilit-info-get-err info))
(hole (ghc-hilit-info-get-hole info))
(coln (ghc-hilit-info-get-coln info))
beg end ovl)
;; FIXME: This is the Shlemiel painter's algorithm.
;; If this is a bottleneck for a large code, let's fix.
(goto-char (point-min))
(cond
((file-equal-p ofile file)
(if hole
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-char (length hole))
(setq end (point)))
(progn
(forward-line (1- line))
(forward-char (1- coln))
(setq beg (point))
(forward-sexp)
;; (skip-chars-forward "^[:space:]" (line-end-position))
(setq end (point)))))
(t
(setq beg (point))
(forward-line)
(setq end (point))))
(setq ovl (make-overlay beg end))
(overlay-put ovl 'ghc-check t)
(overlay-put ovl 'ghc-file file)
(overlay-put ovl 'ghc-msg msg)
(overlay-put ovl 'help-echo msg)
(overlay-put ovl 'ghc-hole hole)
(let ((fringe (if err ghc-check-error-fringe (if hole ghc-check-hole-fringe ghc-check-warning-fringe)))
(face (if err 'ghc-face-error (if hole 'ghc-face-hole 'ghc-face-warn))))
(overlay-put ovl 'before-string fringe)
(overlay-put ovl 'face face)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-overlay-p (ovl)
(overlay-get ovl 'ghc-check))
(defun ghc-check-overlay-at (p)
(ghc-filter 'ghc-overlay-p (overlays-at p)))
(ghc-defstruct file-msgs file msgs)
(defun ghc-get-errors-over-warnings ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
errs wrns)
(dolist (msg msgs)
(if (string-match "^Warning" msg)
(ghc-add wrns msg)
(ghc-add errs msg)))
(ghc-make-file-msgs :file file :msgs (nconc errs wrns))))))
(defun ghc-display-errors ()
(interactive)
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(insert file "\n\n")
(mapc (lambda (x) (insert x "\n\n")) msgs)))))))
(defun ghc-display-errors-to-minibuf ()
(let ((file-msgs (ghc-get-errors-over-warnings)))
(if (null file-msgs)
(message "No errors or warnings")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
(defun ghc-get-only-holes ()
(let ((ovls (ghc-check-overlay-at (point))))
(when ovls
(let ((msgs (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) ovls))
(file (overlay-get (car ovls) 'ghc-file))
holes)
(dolist (msg msgs)
(if (string-match "Found hole" msg)
(ghc-add holes msg)
nil))
(ghc-make-file-msgs :file file :msgs holes)))))
;; Based on http://superuser.com/questions/331895/how-to-get-emacs-to-highlight-and-link-file-paths
(defun find-file-button (button)
(let ((text (buffer-substring (button-start button) (button-end button))))
(when (string-match "\\(/[^:]*\\):\\([[:digit:]]+\\):\\([[:digit:]]+\\)" text)
(let* ((file (match-string 1 text))
(line (string-to-number (match-string 2 text)))
(coln (string-to-number (match-string 3 text)))
(buf (find-file file)))
(with-current-buffer buf
(let* ((this-line (line-number-at-pos))
(diff (- line this-line)))
(beginning-of-line)
(forward-line diff)
(forward-char (1- coln))))))))
(define-button-type 'find-file-button
'follow-link t
'help-echo "mouse-2, RET: Go to definition"
'action #'find-file-button)
(defun buttonize-buffer ()
"turn all file paths into buttons"
(save-excursion
(goto-char (point-min))
(while (re-search-forward "/[^ \t:]*:[[:digit:]]+:[[:digit:]]+" nil t)
(make-button (match-beginning 0) (match-end 0) :type 'find-file-button))))
(defun ghc-display-holes ()
(interactive)
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let ((msgs (ghc-file-msgs-get-msgs file-msgs)))
(ghc-display
nil
(lambda ()
(progn
(mapc (lambda (x) (insert x "\n\n")) msgs)
(buttonize-buffer))))))))
(defun ghc-display-holes-to-minibuf ()
(let ((file-msgs (ghc-get-only-holes)))
(if (null file-msgs)
(message "No holes")
(let* ((file (ghc-file-msgs-get-file file-msgs))
(msgs (ghc-file-msgs-get-msgs file-msgs))
(errmsg (mapconcat 'identity msgs "\n"))
(buffile buffer-file-name))
(if (string-equal buffile file)
(message "%s" errmsg)
(message "%s\n\n%s" file errmsg))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-goto-prev-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-next-error ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(pnts (mapcar 'overlay-start ovls2)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-error 'minibuffer) (ghc-display-errors-to-minibuf))
((eq ghc-display-error 'other-buffer) (ghc-display-errors))))
(defun ghc-goto-prev-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(end (if ovls0 (overlay-start (car ovls0)) here))
(ovls1 (overlays-in (point-min) end))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'max pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
(defun ghc-goto-next-hole ()
(interactive)
(let* ((here (point))
(ovls0 (ghc-check-overlay-at here))
(beg (if ovls0 (overlay-end (car ovls0)) here))
(ovls1 (overlays-in beg (point-max)))
(ovls2 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-check)) ovls1))
(ovls3 (ghc-filter (lambda (ovl) (overlay-get ovl 'ghc-hole)) ovls2))
(pnts (mapcar 'overlay-start ovls3)))
(if pnts (goto-char (apply 'min pnts))))
(cond
((eq ghc-display-hole 'minibuffer) (ghc-display-holes-to-minibuf))
((eq ghc-display-hole 'other-buffer) (ghc-display-holes))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-check-insert-from-warning ()
(interactive)
(let ((ret t))
(dolist (data (delete-dups (mapcar (lambda (ovl) (overlay-get ovl 'ghc-msg)) (ghc-check-overlay-at (point)))) ret)
(save-excursion
(cond
((string-match "Inferred type: \\|no type signature:" data)
(beginning-of-line)
(insert-before-markers (ghc-extract-type data) "\n"))
((string-match "lacks an accompanying binding" data)
(beginning-of-line)
(when (looking-at "^\\([^ ]+\\) *::")
(save-match-data
(forward-line)
(if (not (bolp)) (insert "\n")))
(insert (match-string 1) " = undefined\n")))
;; GHC 7.8 uses Unicode for single-quotes.
((string-match "Not in scope: type constructor or class .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "Not in scope: data constructor .\\([^\n]+\\)." data)
;; if the type of data constructor, it would be nice.
(let ((sym (match-string 1 data)))
(ghc-ins-mod sym)))
((string-match "\n[ ]+.\\([^ ]+\\). is a data constructor of .\\([^\n]+\\).\n" data)
(let* ((old (match-string 1 data))
(type-const (match-string 2 data))
(new (format "%s(%s)" type-const old)))
(ghc-check-replace old new)))
((string-match "Not in scope: .\\([^\n]+\\)." data)
(let ((sym (match-string 1 data)))
(if (or (string-match "\\." sym) ;; qualified
(y-or-n-p (format "Import module for %s?" sym)))
(ghc-ins-mod sym)
(unless (re-search-forward "^$" nil t)
(goto-char (point-max))
(insert "\n"))
(insert "\n" (ghc-enclose sym) " = undefined\n"))))
((string-match "Pattern match(es) are non-exhaustive" data)
(let* ((fn (ghc-get-function-name))
(arity (ghc-get-function-arity fn)))
(ghc-insert-underscore fn arity)))
((string-match "Found:\n[ ]+\\([^\t]+\\)\nWhy not:\n[ ]+\\([^\t]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
((string-match "Found hole .\\(_[_[:alnum:]]*\\). with type: \\([^\t\n]+\\)" data)
(let ((old (match-string 1 data))
(new (match-string 2 data)))
(ghc-check-replace old new)))
(t
(setq ret nil)))))))
(defun ghc-check-replace (old new)
(beginning-of-line)
(when (search-forward old nil t)
(let ((end (point)))
(search-backward old nil t)
(delete-region (point) end))
(insert new)))
(defun ghc-extract-type (str)
(with-temp-buffer
(insert str)
(goto-char (point-min))
(when (re-search-forward "Inferred type: \\|no type signature:\\( \\|\n +\\)?" nil t)
(delete-region (point-min) (point)))
(when (re-search-forward " forall [^.]+\\." nil t)
(replace-match ""))
(while (re-search-forward "\n +" nil t)
(replace-match " "))
(goto-char (point-min))
(while (re-search-forward "\\[Char\\]" nil t)
(replace-match "String"))
(buffer-substring-no-properties (point-min) (point-max))))
(defun ghc-get-function-name ()
(save-excursion
(beginning-of-line)
(when (looking-at "\\([^ ]+\\) ")
(match-string 1))))
(defun ghc-get-function-arity (fn)
(when fn
(save-excursion
(let ((regex (format "^%s *::" (regexp-quote fn))))
(when (re-search-backward regex nil t)
(ghc-get-function-arity0))))))
(defun ghc-get-function-arity0 ()
(let ((end (save-excursion (end-of-line) (point)))
(arity 0))
(while (search-forward "->" end t)
(setq arity (1+ arity)))
arity))
(defun ghc-insert-underscore (fn ar)
(when fn
(let ((arity (or ar 1)))
(save-excursion
(goto-char (point-max))
(re-search-backward (format "^%s *::" (regexp-quote fn)))
(forward-line)
(re-search-forward "^$" nil t)
(insert fn)
(dotimes (_i arity)
(insert " _"))
(insert " = error \"" fn "\"\n")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun ghc-jump-file ()
(interactive)
(let* ((ovl (car (ghc-check-overlay-at 1)))
(file (if ovl (overlay-get ovl 'ghc-file))))
(if file (find-file file))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar ghc-hlint-options nil "*Hlint options")
(defvar ghc-check-command nil)
(defun ghc-toggle-check-command ()
(interactive)
(setq ghc-check-command (not ghc-check-command))
(if ghc-check-command
(message "Syntax check with hlint")
(message "Syntax check with GHC")))
(provide 'ghc-check)
|
[
{
"context": "lexical-binding: t -*-\n\n;; Copyright (C) 2011-2020 Dirk-Jan C. Binnema\n\n;; Author: Dirk-Jan C. Binnema <djcb@djcbsoftwar",
"end": 132,
"score": 0.9998738765716553,
"start": 113,
"tag": "NAME",
"value": "Dirk-Jan C. Binnema"
},
{
"context": "ight (C) 2011-2020 Dirk-Jan C. Binnema\n\n;; Author: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>\n;; Maintainer: Dirk-Jan C.",
"end": 164,
"score": 0.9998836517333984,
"start": 145,
"tag": "NAME",
"value": "Dirk-Jan C. Binnema"
},
{
"context": "k-Jan C. Binnema\n\n;; Author: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>\n;; Maintainer: Dirk-Jan C. Binnema <djcb@djcbsof",
"end": 186,
"score": 0.9999291896820068,
"start": 166,
"tag": "EMAIL",
"value": "djcb@djcbsoftware.nl"
},
{
"context": "n C. Binnema <djcb@djcbsoftware.nl>\n;; Maintainer: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>\n\n;; This file is not part ",
"end": 222,
"score": 0.9998757839202881,
"start": 203,
"tag": "NAME",
"value": "Dirk-Jan C. Binnema"
},
{
"context": "bsoftware.nl>\n;; Maintainer: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>\n\n;; This file is not part of GNU Emacs.\n\n;; mu4e",
"end": 244,
"score": 0.9999244213104248,
"start": 224,
"tag": "EMAIL",
"value": "djcb@djcbsoftware.nl"
}
] | lisp/mu4e/mu4e-utils.el | timmli/emacs-settings | 0 | ;;; mu4e-utils.el -- part of mu4e, the mu mail user agent -*- lexical-binding: t -*-
;; Copyright (C) 2011-2020 Dirk-Jan C. Binnema
;; Author: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
;; Maintainer: Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
;; This file is not part of GNU Emacs.
;; mu4e is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; mu4e 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 mu4e. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Utility functions used in the mu4e
;;; Code:
(require 'org)
(require 'cl-lib)
(require 'cl-seq nil 'noerror)
(require 'mu4e-vars)
(require 'mu4e-message)
(require 'mu4e-meta)
(require 'mu4e-lists)
(require 'doc-view)
;; keep the byte-compiler happy
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-ping "mu4e-proc")
(declare-function mu4e~proc-contacts "mu4e-proc")
(declare-function mu4e~proc-kill "mu4e-proc")
(declare-function mu4e~proc-index "mu4e-proc")
(declare-function mu4e~proc-add "mu4e-proc")
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e-message-field-at-point "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e~main-view "mu4e-main")
(declare-function mu4e~context-autoswitch "mu4e-context")
(declare-function mu4e-context-determine "mu4e-context")
(declare-function mu4e-context-vars "mu4e-context")
(declare-function mu4e-context-current "mu4e-context")
(declare-function show-all "org")
;;; Various
(defun mu4e-copy-message-path ()
"Copy the message-path of message at point to the kill-ring."
(interactive)
(let ((path (mu4e-message-field-at-point :path)))
(kill-new path)
(mu4e-message "Saved '%s' to kill-ring" path)))
(defun mu4e-personal-address-p (addr)
"Is ADDR a personal address?
Evaluate to nil if ADDR matches any of the personal addresses.
Uses (mu4e-personal-addresses) for the addresses with both the plain
addresses and /regular expressions/."
(when addr
(seq-find
(lambda (m)
(if (string-match "/\\(.*\\)/" m)
(let ((rx (match-string 1 m))
(case-fold-search t))
(if (string-match rx addr) t nil))
(eq t (compare-strings addr nil nil m nil nil 'case-insensitive))))
(mu4e-personal-addresses))))
(define-obsolete-function-alias 'mu4e-user-mail-address-p
'mu4e-personal-address-p "1.5.5")
(defmacro with~mu4e-context-vars (context &rest body)
"Evaluate BODY, with variables let-bound for CONTEXT (if any).
`funcall'."
(declare (indent 2))
`(let* ((vars (and ,context (mu4e-context-vars ,context))))
(cl-progv ;; XXX: perhaps use eval's lexical environment instead of progv?
(mapcar (lambda(cell) (car cell)) vars)
(mapcar (lambda(cell) (cdr cell)) vars)
(eval ,@body))))
;;; Folders (1/2)
;; the standard folders can be functions too
(defun mu4e~get-folder (foldervar msg)
"Within the mu-context of MSG, get message folder FOLDERVAR.
If FOLDER is a string, return it, if it is a function, evaluate
this function with MSG as parameter (which may be `nil'), and
return the result."
(unless (member foldervar
'(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder mu4e-refile-folder))
(mu4e-error "Folder must be one of mu4e-(sent|drafts|trash|refile)-folder"))
;; get the value with the vars for the relevants context let-bound
(with~mu4e-context-vars (mu4e-context-determine msg nil)
(let* ((folder (symbol-value foldervar))
(val
(cond
((stringp folder) folder)
((functionp folder) (funcall folder msg))
(t (mu4e-error "unsupported type for %S" folder)))))
(or val (mu4e-error "%S evaluates to nil" foldervar)))))
(defun mu4e-get-drafts-folder (&optional msg)
"Get the sent folder. See `mu4e-drafts-folder'."
(mu4e~get-folder 'mu4e-drafts-folder msg))
(defun mu4e-get-refile-folder (&optional msg)
"Get the folder for refiling. See `mu4e-refile-folder'."
(mu4e~get-folder 'mu4e-refile-folder msg))
(defun mu4e-get-sent-folder (&optional msg)
"Get the sent folder. See `mu4e-sent-folder'."
(mu4e~get-folder 'mu4e-sent-folder msg))
(defun mu4e-get-trash-folder (&optional msg)
"Get the sent folder. See `mu4e-trash-folder'."
(mu4e~get-folder 'mu4e-trash-folder msg))
;;; Self-destructing files
(defun mu4e-remove-file-later (filename)
"Remove FILENAME in a few seconds."
(run-at-time "30 sec" nil
(lambda () (ignore-errors (delete-file filename)))))
(defun mu4e-make-temp-file (ext)
"Create a temporary file with extension EXT. The file will
self-destruct in a few seconds, enough to open it in another
program."
(let ((tmpfile (make-temp-file "mu4e-" nil (concat "." ext))))
(mu4e-remove-file-later tmpfile)
tmpfile))
;;; Folders (2/2)
;;
;; mu4e-attachment-dir is either a string or a function that takes a
;; filename and the mime-type as argument, either (or both) which can
;; be nil
(defun mu4e~get-attachment-dir (&optional fname mimetype)
"Get the directory for saving attachments from
`mu4e-attachment-dir' (which can be either a string or a function,
see its docstring)."
(let
((dir
(cond
((stringp mu4e-attachment-dir)
mu4e-attachment-dir)
((functionp mu4e-attachment-dir)
(funcall mu4e-attachment-dir fname mimetype))
(t
(mu4e-error "unsupported type for mu4e-attachment-dir" )))))
(if dir
(expand-file-name dir)
(mu4e-error "mu4e-attachment-dir evaluates to nil"))))
;;; Maildir (1/2)
(defun mu4e~guess-maildir (path)
"Guess the maildir for some path, or nil if cannot find it."
(let ((idx (string-match (mu4e-root-maildir) path)))
(when (and idx (zerop idx))
(replace-regexp-in-string
(mu4e-root-maildir)
""
(expand-file-name
(concat path "/../.."))))))
(defun mu4e-create-maildir-maybe (dir)
"Offer to create maildir DIR if it does not exist yet.
Return t if the dir already existed, or an attempt has been made to
create it -- we cannot be sure creation succeeded here, since this
is done asynchronously. Otherwise, return nil. NOte, DIR has to be
an absolute path."
(if (and (file-exists-p dir) (not (file-directory-p dir)))
(mu4e-error "%s exists, but is not a directory." dir))
(cond
((file-directory-p dir) t)
((yes-or-no-p (mu4e-format "%s does not exist yet. Create now?" dir))
(mu4e~proc-mkdir dir) t)
(t nil)))
;;; Messages, warnings and errors
(defun mu4e-format (frm &rest args)
"Create [mu4e]-prefixed string based on format FRM and ARGS."
(concat
"[" (propertize "mu4e" 'face 'mu4e-title-face) "] "
(apply 'format frm
(mapcar (lambda (x)
(if (stringp x)
(decode-coding-string x 'utf-8)
x))
args))))
(defun mu4e-message (frm &rest args)
"Like `message', but prefixed with mu4e.
If we're waiting for user-input or if there's some message in the
echo area, don't show anything."
(unless (or (active-minibuffer-window))
(message "%s" (apply 'mu4e-format frm args))))
(defun mu4e-index-message (frm &rest args)
"Like `mu4e-message', but specifically for
index-messages. Doesn't display anything if
`mu4e-hide-index-messages' is non-nil. "
(unless mu4e-hide-index-messages
(apply 'mu4e-message frm args)))
(defun mu4e-error (frm &rest args)
"Create [mu4e]-prefixed error based on format FRM and ARGS.
Does a local-exit and does not return, and raises a
debuggable (backtrace) error."
(mu4e-log 'error (apply 'mu4e-format frm args))
(error "%s" (apply 'mu4e-format frm args)))
;; the user-error function is only available in emacs-trunk
(unless (fboundp 'user-error)
(defalias 'user-error 'error))
(defun mu4e-warn (frm &rest args)
"Create [mu4e]-prefixed warning based on format FRM and ARGS.
Does a local-exit and does not return. In emacs versions below
24.2, the functions is the same as `mu4e-error'."
(mu4e-log 'error (apply 'mu4e-format frm args))
(user-error "%s" (apply 'mu4e-format frm args)))
;;; Reading user input
(defun mu4e~read-char-choice (prompt choices)
"Read and return one of CHOICES, prompting for PROMPT.
Any input that is not one of CHOICES is ignored. This mu4e's
version of `read-char-choice', that becomes case-insentive after
trying an exact match."
(let ((choice) (chosen) (inhibit-quit nil))
(while (not chosen)
(message nil);; this seems needed...
(setq choice (read-char-exclusive prompt))
(if (eq choice 27) (keyboard-quit)) ;; quit if ESC is pressed
(setq chosen (or (member choice choices)
(member (downcase choice) choices)
(member (upcase choice) choices))))
(car chosen)))
(defun mu4e-read-option (prompt options)
"Ask user for an option from a list on the input area.
PROMPT describes a multiple-choice question to the user.
OPTIONS describe the options, and is a list of cells describing
particular options. Cells have the following structure:
(OPTIONSTRING . RESULT)
where OPTIONSTRING is a non-empty string describing the
option. The first character of OPTIONSTRING is used as the
shortcut, and obviously all shortcuts must be different, so you
can prefix the string with an uniquifying character.
The options are provided as a list for the user to choose from;
user can then choose by typing CHAR. Example:
(mu4e-read-option \"Choose an animal: \"
'((\"Monkey\" . monkey) (\"Gnu\" . gnu) (\"xMoose\" . moose)))
User now will be presented with a list: \"Choose an animal:
[M]onkey, [G]nu, [x]Moose\".
Function will return the cdr of the list element."
(let* ((prompt (mu4e-format "%s" prompt))
(optionsstr
(mapconcat
(lambda (option)
;; try to detect old-style options, and warn
(when (characterp (car-safe (cdr-safe option)))
(mu4e-error
(concat "Please use the new format for options/actions; "
"see the manual")))
(let ((kar (substring (car option) 0 1)))
(concat
"[" (propertize kar 'face 'mu4e-highlight-face) "]"
(substring (car option) 1))))
options ", "))
(response
(mu4e~read-char-choice
(concat prompt optionsstr
" [" (propertize "C-g" 'face 'mu4e-highlight-face)
" to cancel]")
;; the allowable chars
(cl-map 'list (lambda(elm) (string-to-char (car elm))) options)))
(chosen
(cl-find-if
(lambda (option) (eq response (string-to-char (car option))))
options)))
(if chosen
(cdr chosen)
(mu4e-warn "Unknown shortcut '%c'" response))))
;;; Maildir (1/2)
(defun mu4e~get-maildirs-1 (path mdir)
"Get maildirs under path, recursively, as a list of relative paths."
(let ((dirs)
(dentries
(ignore-errors
(directory-files-and-attributes
(concat path mdir) nil
"^[^.]\\|\\.[^.][^.]" t))))
(dolist (dentry dentries)
(when (and (booleanp (cadr dentry)) (cadr dentry))
(if (file-accessible-directory-p
(concat (mu4e-root-maildir) "/" mdir "/" (car dentry) "/cur"))
(setq dirs (cons (concat mdir (car dentry)) dirs)))
(unless (member (car dentry) '("cur" "new" "tmp"))
(setq dirs (append dirs (mu4e~get-maildirs-1 path
(concat mdir (car dentry) "/")))))))
dirs))
(defvar mu4e-cache-maildir-list nil
"Whether to cache the list of maildirs; set it to t if you find
that generating the list on the fly is too slow. If you do, you
can set `(mu4e-root-maildir)-list' to nil to force regenerating the
cache the next time `mu4e-get-maildirs' gets called.")
(defvar mu4e-maildir-list nil
"Cached list of maildirs.")
(defun mu4e-get-maildirs ()
"Get maildirs under `mu4e-maildir', recursively, as a list of
relative paths (ie., /archive, /sent etc.). Most of the work is
done in `mu4e~get-maildirs-1'. Note, these results are /cached/
if `mu4e-cache-maildir-list' is customized to non-nil. In that case,
the list of maildirs will not change until you restart mu4e."
(unless (and mu4e-maildir-list mu4e-cache-maildir-list)
(setq mu4e-maildir-list
(sort
(append
(when (file-accessible-directory-p
(concat (mu4e-root-maildir) "/cur")) '("/"))
(mu4e~get-maildirs-1 (mu4e-root-maildir) "/"))
(lambda (s1 s2) (string< (downcase s1) (downcase s2))))))
mu4e-maildir-list)
(defun mu4e-ask-maildir (prompt)
"Ask the user for a shortcut (using PROMPT) as per
(mu4e-maildir-shortcuts), then return the corresponding folder
name. If the special shortcut 'o' (for _o_ther) is used, or if
`(mu4e-maildir-shortcuts)' evaluates to nil, let user choose from
all maildirs under `mu4e-maildir'."
(let ((prompt (mu4e-format "%s" prompt)))
(if (not (mu4e-maildir-shortcuts))
(substring-no-properties
(funcall mu4e-completing-read-function prompt (mu4e-get-maildirs)))
(let* ((mlist (append (mu4e-maildir-shortcuts)
'((:maildir "ther" :key ?o))))
(fnames
(mapconcat
(lambda (item)
(concat
"["
(propertize (make-string 1 (plist-get item :key))
'face 'mu4e-highlight-face)
"]"
(plist-get item :maildir)))
mlist ", "))
(kar (read-char (concat prompt fnames))))
(if (member kar '(?/ ?o)) ;; user chose 'other'?
(substring-no-properties
(funcall mu4e-completing-read-function prompt
(mu4e-get-maildirs) nil nil "/"))
(or (plist-get
(cl-find-if (lambda (item) (= kar (plist-get item :key)))
(mu4e-maildir-shortcuts)) :maildir)
(mu4e-warn "Unknown shortcut '%c'" kar)))))))
(defun mu4e-ask-maildir-check-exists (prompt)
"Like `mu4e-ask-maildir', but check for existence of the maildir,
and offer to create it if it does not exist yet."
(let* ((mdir (mu4e-ask-maildir prompt))
(fullpath (concat (mu4e-root-maildir) mdir)))
(unless (file-directory-p fullpath)
(and (yes-or-no-p
(mu4e-format "%s does not exist. Create now?" fullpath))
(mu4e~proc-mkdir fullpath)))
mdir))
;;; Bookmarks
(defun mu4e-ask-bookmark (prompt)
"Ask the user for a bookmark (using PROMPT) as defined in
`mu4e-bookmarks', then return the corresponding query."
(unless (mu4e-bookmarks) (mu4e-error "No bookmarks defined"))
(let* ((prompt (mu4e-format "%s" prompt))
(bmarks
(mapconcat
(lambda (bm)
(concat
"[" (propertize (make-string 1 (plist-get bm :key))
'face 'mu4e-highlight-face)
"]"
(plist-get bm :name))) (mu4e-bookmarks) ", "))
(kar (read-char (concat prompt bmarks))))
(mu4e-get-bookmark-query kar)))
(defun mu4e-get-bookmark-query (kar)
"Get the corresponding bookmarked query for shortcut character
KAR, or raise an error if none is found."
(let* ((chosen-bm
(or (cl-find-if
(lambda (bm)
(= kar (plist-get bm :key)))
(mu4e-bookmarks))
(mu4e-warn "Unknown shortcut '%c'" kar)))
(expr (plist-get chosen-bm :query))
(expr (if (not (functionp expr)) expr
(funcall expr)))
(query (eval expr)))
(if (stringp query)
query
(mu4e-warn "Expression must evaluate to query string ('%S')" expr))))
(defun mu4e-bookmark-define (query name key)
"Define a bookmark for QUERY with name NAME and
shortcut-character KEY in the list of `mu4e-bookmarks'. This
replaces any existing bookmark with KEY."
(setq mu4e-bookmarks
(cl-remove-if
(lambda (bm)
(= (plist-get bm :key) key))
(mu4e-bookmarks)))
(cl-pushnew `(:name ,name
:query ,query
:key ,key)
mu4e-bookmarks :test 'equal))
;;; Converting flags->string and vice-versa
(defun mu4e~flags-to-string-raw (flags)
"Convert a list of flags into a string as seen in Maildir
message files; flags are symbols draft, flagged, new, passed,
replied, seen, trashed and the string is the concatenation of the
uppercased first letters of these flags, as per [1]. Other flags
than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html"
(when flags
(let ((kar (cl-case (car flags)
('draft ?D)
('flagged ?F)
('new ?N)
('passed ?P)
('replied ?R)
('seen ?S)
('trashed ?T)
('attach ?a)
('encrypted ?x)
('signed ?s)
('unread ?u))))
(concat (and kar (string kar))
(mu4e~flags-to-string-raw (cdr flags))))))
(defun mu4e-flags-to-string (flags)
"Remove duplicates and sort the output of `mu4e~flags-to-string-raw'."
(concat
(sort (cl-remove-duplicates
(append (mu4e~flags-to-string-raw flags) nil)) '>)))
(defun mu4e~string-to-flags-1 (str)
"Convert a string with message flags as seen in Maildir
messages into a list of flags in; flags are symbols draft,
flagged, new, passed, replied, seen, trashed and the string is
the concatenation of the uppercased first letters of these flags,
as per [1]. Other letters than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html."
(when (/= 0 (length str))
(let ((flag
(cl-case (string-to-char str)
(?D 'draft)
(?F 'flagged)
(?P 'passed)
(?R 'replied)
(?S 'seen)
(?T 'trashed))))
(append (when flag (list flag))
(mu4e~string-to-flags-1 (substring str 1))))))
(defun mu4e-string-to-flags (str)
"Convert a string with message flags as seen in Maildir messages
into a list of flags in; flags are symbols draft, flagged, new,
passed, replied, seen, trashed and the string is the concatenation
of the uppercased first letters of these flags, as per [1]. Other
letters than the ones listed here are ignored. Also see
`mu4e-flags-to-string'. \[1\]:
http://cr.yp.to/proto/maildir.html "
;; "Remove duplicates from the output of `mu4e~string-to-flags-1'"
(cl-remove-duplicates (mu4e~string-to-flags-1 str)))
;;; Various
(defun mu4e-display-size (size)
"Get a string representation of SIZE (in bytes)."
(cond
((>= size 1000000) (format "%2.1fM" (/ size 1000000.0)))
((and (>= size 1000) (< size 1000000))
(format "%2.1fK" (/ size 1000.0)))
((< size 1000) (format "%d" size))
(t (propertize "?" 'face 'mu4e-system-face))))
(defun mu4e-display-manual ()
"Display the mu4e manual page for the current mode.
Or go to the top level if there is none."
(interactive)
(info (cl-case major-mode
('mu4e-main-mode "(mu4e)Main view")
('mu4e-headers-mode "(mu4e)Headers view")
('mu4e-view-mode "(mu4e)Message view")
(t "mu4e"))))
;;; Misc
(defun mu4e-last-query ()
"Get the most recent query or nil if there is none."
(when (buffer-live-p (mu4e-get-headers-buffer))
(with-current-buffer (mu4e-get-headers-buffer)
mu4e~headers-last-query)))
(defvar gnus-article-buffer) ;; Fix byte-compiler warning.
(defun mu4e-get-view-buffer ()
"Get the view buffer, if any."
(get-buffer
(if mu4e-view-use-old
mu4e~view-buffer-name
gnus-article-buffer)))
(defun mu4e-get-headers-buffer ()
(get-buffer mu4e~headers-buffer-name))
(defun mu4e-select-other-view ()
"When the headers view is selected, select the message view (if
that has a live window), and vice versa."
(interactive)
(let* ((other-buf
(cond
((eq major-mode 'mu4e-headers-mode)
(mu4e-get-view-buffer))
((eq major-mode 'mu4e-view-mode)
(mu4e-get-headers-buffer))))
(other-win (and other-buf (get-buffer-window other-buf))))
(if (window-live-p other-win)
(select-window other-win)
(mu4e-message "No window to switch to"))))
(defconst mu4e-output-buffer-name "*mu4e-output*"
"*internal* Name of the mu4e output buffer.")
(defun mu4e-process-file-through-pipe (path pipecmd)
"Process file at PATH through a pipe with PIPECMD."
(let ((buf (get-buffer-create mu4e-output-buffer-name)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(call-process-shell-command pipecmd path t t)
(view-mode)))
(switch-to-buffer buf)))
(defvar mu4e~lists-hash nil
"Hashtable of mailing-list-id => shortname, based on
`mu4e~mailing-lists' and `mu4e-user-mailing-lists'.")
(defun mu4e-get-mailing-list-shortname (list-id)
"Get the shortname for a mailing-list with list-id LIST-ID. based
on `mu4e~mailing-lists', `mu4e-user-mailing-lists', and
`mu4e-mailing-list-patterns'."
(unless mu4e~lists-hash
(setq mu4e~lists-hash (make-hash-table :test 'equal))
(dolist (cell mu4e~mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash))
(dolist (cell mu4e-user-mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash)))
(or
(gethash list-id mu4e~lists-hash)
(and (boundp 'mu4e-mailing-list-patterns)
(cl-member-if
(lambda (pattern)
(string-match pattern list-id))
mu4e-mailing-list-patterns)
(match-string 1 list-id))
;; if it's not in the db, take the part until the first dot if there is one;
;; otherwise just return the whole thing
(if (string-match "\\([^.]*\\)\\." list-id)
(match-string 1 list-id)
list-id)))
(defvar mu4e-index-updated-hook nil
"Hook run when the indexing process had one or more updated messages.
This can be used as a simple way to invoke some action when new
messages appear, but note that an update in the index does not
necessarily mean a new message.")
(defvar mu4e-message-changed-hook nil
"Hook run when there is a message changed in db. For new
messages, it depends on `mu4e-index-updated-hook'. This can be
used as a simple way to invoke some action when a message
changed.")
(make-obsolete-variable 'mu4e-msg-changed-hook
'mu4e-message-changed-hook "0.9.19")
(defvar mu4e~contacts-tstamp "0"
"Timestamp for the most recent contacts update." )
;;; Some handler functions for server messages
(defun mu4e-info-handler (info)
"Handler function for (:info ...) sexps received from the server
process."
(let* ((type (plist-get info :info))
(processed (plist-get info :processed))
(updated (plist-get info :updated))
(cleaned-up (plist-get info :cleaned-up))
(mainbuf (get-buffer mu4e-main-buffer-name)))
(cond
((eq type 'add) t) ;; do nothing
((eq type 'index)
(if (eq (plist-get info :status) 'running)
(mu4e-index-message
"Indexing... processed %d, updated %d" processed updated)
(progn
(mu4e-index-message
"%s completed; processed %d, updated %d, cleaned-up %d"
(if mu4e-index-lazy-check "Lazy indexing" "Indexing")
processed updated cleaned-up)
;; call the updated hook if anything changed.
(unless (zerop (+ updated cleaned-up))
(run-hooks 'mu4e-index-updated-hook))
(unless (and (not (string= mu4e~contacts-tstamp "0"))
(zerop (plist-get info :updated)))
(mu4e~request-contacts-maybe))
(when (and (buffer-live-p mainbuf) (get-buffer-window mainbuf))
(save-window-excursion
(select-window (get-buffer-window mainbuf))
(mu4e~main-view 'refresh))))))
((plist-get info :message)
(mu4e-index-message "%s" (plist-get info :message))))))
(defun mu4e-error-handler (errcode errmsg)
"Handler function for showing an error."
;; don't use mu4e-error here; it's running in the process filter context
(cl-case errcode
(4 (user-error "No matches for this search query."))
(110 (display-warning 'mu4e errmsg :error)) ;; schema version.
(t (error "Error %d: %s" errcode errmsg))))
;;; Contacts
(defun mu4e~update-contacts (contacts &optional tstamp)
"Receive a sorted list of CONTACTS.
Each of the contacts has the form
(FULL_EMAIL_ADDRESS . RANK) and fill `mu4e~contacts-hash' with
it, with each contact mapped to an integer for their ranking.
This is used by the completion function in mu4e-compose."
;; We have our nicely sorted list, map them to a list
;; of increasing integers. We use that map in the composer
;; to sort them there. It would have been so much easier if emacs
;; allowed us to use the sorted-list as-is, but no such luck.
(let ((n 0))
(unless mu4e~contacts-hash
(setq mu4e~contacts-hash (make-hash-table :test 'equal :weakness nil
:size (length contacts))))
(dolist (contact contacts)
(cl-incf n)
(let* ((address (plist-get contact :address))
(address
(if (functionp mu4e-contact-process-function)
(funcall mu4e-contact-process-function address)
address)))
(when address ;; note the explicit deccode; the strings we get are utf-8,
;; but emacs doesn't know yet.
(puthash (decode-coding-string address 'utf-8)
(plist-get contact :rank) mu4e~contacts-hash))))
(setq mu4e~contacts-tstamp (or tstamp "0"))
(unless (zerop n)
(mu4e-index-message "Contacts updated: %d; total %d"
n (hash-table-count mu4e~contacts-hash)))))
(defun mu4e-contacts-info ()
"Display information about the cache used for contacts
completion; for testing/debugging."
(interactive)
(with-current-buffer (get-buffer-create "*mu4e-contacts-info*")
(erase-buffer)
(insert (format "complete addresses: %s\n"
(if mu4e-compose-complete-addresses "yes" "no")))
(insert (format "only personal addresses: %s\n"
(if mu4e-compose-complete-only-personal "yes" "no")))
(insert (format "only addresses seen after: %s\n"
(or mu4e-compose-complete-only-after "no restrictions")))
(when mu4e~contacts-hash
(insert (format "number of contacts cached: %d\n\n"
(hash-table-count mu4e~contacts-hash)))
(let ((contacts))
(maphash (lambda (addr rank)
(setq contacts (cons (cons rank addr) contacts)))
mu4e~contacts-hash)
(setq contacts (sort contacts
(lambda(cell1 cell2) (< (car cell1) (car cell2)))))
(dolist (contact contacts)
(insert (format "%s\n" (cdr contact))))))
(pop-to-buffer "*mu4e-contacts-info*")))
(defun mu4e~check-requirements ()
"Check for the settings required for running mu4e."
(unless (>= emacs-major-version 25)
(mu4e-error "Emacs >= 25.x is required for mu4e"))
(when mu4e~server-props
(unless (string= (mu4e-server-version) mu4e-mu-version)
(mu4e-error "mu server has version %s, but we need %s"
(mu4e-server-version) mu4e-mu-version)))
(unless (and mu4e-mu-binary (file-executable-p mu4e-mu-binary))
(mu4e-error "Please set `mu4e-mu-binary' to the full path to the mu
binary."))
(dolist (var '(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder))
(unless (and (boundp var) (symbol-value var))
(mu4e-error "Please set %S" var))
(unless (functionp (symbol-value var)) ;; functions are okay, too
(let* ((dir (symbol-value var))
(path (concat (mu4e-root-maildir) dir)))
(unless (string= (substring dir 0 1) "/")
(mu4e-error "%S must start with a '/'" dir))
(unless (mu4e-create-maildir-maybe path)
(mu4e-error "%s (%S) does not exist" path var))))))
(defun mu4e-running-p ()
"Whether mu4e is running.
Checks whether the server process is live."
(mu4e~proc-running-p))
;;; Starting / getting mail / updating the index
(defvar mu4e~update-timer nil
"The mu4e update timer.")
(defconst mu4e~update-name " *mu4e-update*"
"Name of the process and buffer to update mail.")
(defconst mu4e~update-buffer-height 8
"Height of the mu4e message retrieval/update buffer.")
(defvar mu4e~get-mail-ask-password "mu4e get-mail: Enter password: "
"Query string for `mu4e-get-mail-command' password.")
(defvar mu4e~get-mail-password-regexp "^Remote: Enter password: $"
"Regexp to match a password query in the `mu4e-get-mail-command' output.")
(defun mu4e~request-contacts-maybe ()
"If `mu4e-compose-complete-addresses' is non-nil, get/update
the list of contacts we use for autocompletion; otherwise, do
nothing."
(when mu4e-compose-complete-addresses
(setq mu4e-contacts-func 'mu4e~update-contacts)
(mu4e~proc-contacts
mu4e-compose-complete-only-personal
mu4e-compose-complete-only-after
mu4e~contacts-tstamp)))
(defun mu4e~pong-handler (data func)
"Handle 'pong' responses from the mu server."
(setq mu4e~server-props (plist-get data :props)) ;; save info from the server
(let ((doccount (plist-get mu4e~server-props :doccount)))
(mu4e~check-requirements)
(when func (funcall func))
(when (zerop doccount)
(mu4e-message "Store is empty; (re)indexing. This may take a while.") ;
(mu4e-update-index))
(when (and mu4e-update-interval (null mu4e~update-timer))
(setq mu4e~update-timer
(run-at-time 0 mu4e-update-interval
(lambda () (mu4e-update-mail-and-index
mu4e-index-update-in-background)))))))
(defun mu4e-last-query-results ()
"Get the results (counts) of the last cached queries.
The cached queries are the bookmark / maildir queries that are
used to populated the read/unread counts in the main view. They
are refreshed when calling `(mu4e)', i.e., when going to the main
view.
The results are a list of elements of the form
(:query \"query string\"
:count <total number matching count>
:unread <number of unread messages in count>)"
(plist-get mu4e~server-props :queries))
(defun mu4e-last-query-result (query)
"Get the last result for some cached query, as per
`mu4e-bookmark-query-results' or nil if not found."
(cl-find-if
(lambda (elm) (string= (plist-get elm :query) query))
(mu4e-last-query-results)))
(defun mu4e~start (&optional func)
"If `mu4e-contexts' have been defined, but we don't have a
context yet, switch to the matching one, or none matches, the
first. If mu4e is already running, execute function FUNC (if
non-nil). Otherwise, check various requireme`'nts, then start mu4e.
When successful, call FUNC (if non-nil) afterwards."
(unless (mu4e-context-current)
(mu4e~context-autoswitch nil mu4e-context-policy))
(setq mu4e-pong-func (lambda (info) (mu4e~pong-handler info func)))
(mu4e~proc-ping
(mapcar ;; send it a list of queries we'd like to see read/unread info for
(lambda (bm)
(funcall (or mu4e-query-rewrite-function #'identity)
(plist-get bm :query)))
;; exclude bookmarks that are not strings, and with certain flags
(seq-filter (lambda (bm)
(and (stringp (plist-get bm :query))
(not (or (plist-get bm :hide) (plist-get bm :hide-unread)))))
(append (mu4e-bookmarks)
(mu4e~maildirs-with-query)))))
;; maybe request the list of contacts, automatically refreshed after
;; reindexing
(unless mu4e~contacts-hash (mu4e~request-contacts-maybe)))
(defun mu4e-clear-caches ()
"Clear any cached resources."
(setq
mu4e-maildir-list nil
mu4e~contacts-hash nil
mu4e~contacts-tstamp "0"))
(defun mu4e~stop ()
"Stop the mu4e session."
(when mu4e~update-timer
(cancel-timer mu4e~update-timer)
(setq mu4e~update-timer nil))
(mu4e-clear-caches)
(mu4e~proc-kill)
;; kill all mu4e buffers
(mapc
(lambda (buf)
;; When using the Gnus-based viewer, the view buffer has the
;; kill-buffer-hook function mu4e~view-kill-buffer-hook-fn which kills the
;; mm-* buffers created by Gnus' article mode. Those have been returned by
;; `buffer-list' but might already be deleted in case the view buffer has
;; been killed first. So we need a `buffer-live-p' check here.
(when (buffer-live-p buf)
(with-current-buffer buf
(when (member major-mode
'(mu4e-headers-mode mu4e-view-mode mu4e-main-mode))
(kill-buffer)))))
(buffer-list)))
(defun mu4e~maildirs-with-query ()
"Return a copy of `mu4e-maildirs-shortcuts' with :query populated.
This is meant to be the exact same data structure as
`mu4e-bookmarks'."
(cl-mapcar
(lambda (m)
(append
;; we want to change the :maildir key to :name, and add a :query key
(list :name (plist-get m :maildir)
:query (format "maildir:\"%s\"" (plist-get m :maildir)))
;; next we want to append any other keys to our previous list (e.g. :hide,
;; :key, etc) but skipping :maildir (since it's renamed to :name)
(cl-loop for (key value) on m by 'cddr
when (not (equal key :maildir))
append (list key value))))
(mu4e-maildir-shortcuts)))
(defun mu4e~longest-of-maildirs-and-bookmarks ()
"Return the length of longest name of bookmarks and maildirs."
(cl-loop for b in (append (mu4e-bookmarks)
(mu4e~maildirs-with-query))
maximize (string-width (plist-get b :name))))
;;; Indexing & Updating
(defvar mu4e~progress-reporter nil
"Internal, the progress reporter object.")
(defun mu4e~get-mail-process-filter (proc msg)
"Filter the output of `mu4e-get-mail-command'.
Currently the filter only checks if the command asks for a password
by matching the output against `mu4e~get-mail-password-regexp'.
The messages are inserted into the process buffer.
Also scrolls to the final line, and update the progress throbber."
(when mu4e~progress-reporter
(progress-reporter-update mu4e~progress-reporter))
(when (string-match mu4e~get-mail-password-regexp msg)
(if (process-get proc 'x-interactive)
(process-send-string proc
(concat (read-passwd mu4e~get-mail-ask-password)
"\n"))
;; TODO kill process?
(mu4e-error "Unrecognized password request")))
(when (process-buffer proc)
(let ((inhibit-read-only t)
(procwin (get-buffer-window (process-buffer proc))))
;; Insert at end of buffer. Leave point alone.
(with-current-buffer (process-buffer proc)
(goto-char (point-max))
(if (string-match ".*\r\\(.*\\)" msg)
(progn
;; kill even with \r
(end-of-line)
(let ((end (point)))
(beginning-of-line)
(delete-region (point) end))
(insert (match-string 1 msg)))
(insert msg)))
;; Auto-scroll unless user is interacting with the window.
(when (and (window-live-p procwin)
(not (eq (selected-window) procwin)))
(with-selected-window procwin
(goto-char (point-max)))))))
(defun mu4e-update-index ()
"Update the mu4e index."
(interactive)
(mu4e~proc-index mu4e-index-cleanup mu4e-index-lazy-check))
(defun mu4e-update-index-nonlazy ()
"Update the mu4e index non-lazily.
This is just a convenience wrapper for indexing the non-lazy way
if you otherwise want to use `mu4e-index-lazy-check'."
(interactive)
(let ((mu4e-index-cleanup t) (mu4e-index-lazy-check nil))
(mu4e-update-index)))
(defvar mu4e~update-buffer nil
"Internal, store the buffer of the update process when
updating.")
(define-derived-mode mu4e~update-mail-mode special-mode "mu4e:update"
"Major mode used for retrieving new e-mail messages in `mu4e'.")
(define-key mu4e~update-mail-mode-map (kbd "q") 'mu4e-kill-update-mail)
(defun mu4e~temp-window (buf height)
"Create a temporary window with HEIGHT at the bottom of the
frame to display buffer BUF."
(let ((win
(split-window
(frame-root-window)
(- (window-height (frame-root-window)) height))))
(set-window-buffer win buf)
(set-window-dedicated-p win t)
win))
(defun mu4e~update-sentinel-func (proc _msg)
"Sentinel function for the update process."
(when mu4e~progress-reporter
(progress-reporter-done mu4e~progress-reporter)
(setq mu4e~progress-reporter nil))
(unless mu4e-hide-index-messages
(message nil))
(if (or (not (eq (process-status proc) 'exit))
(/= (process-exit-status proc) 0))
(progn
(when mu4e-index-update-error-warning
(mu4e-message "Update process returned with non-zero exit code")
(sit-for 5))
(when mu4e-index-update-error-continue
(mu4e-update-index)))
(mu4e-update-index))
(when (buffer-live-p mu4e~update-buffer)
(unless (eq mu4e-split-view 'single-window)
(mapc #'delete-window (get-buffer-window-list mu4e~update-buffer)))
(kill-buffer mu4e~update-buffer)))
;; complicated function, as it:
;; - needs to check for errors
;; - (optionally) pop-up a window
;; - (optionally) check password requests
(defun mu4e~update-mail-and-index-real (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
RUN-IN-BACKGROUND is non-nil (or called with prefix-argument),
run in the background; otherwise, pop up a window."
(let* ((process-connection-type t)
(proc (start-process-shell-command
"mu4e-update" mu4e~update-name
mu4e-get-mail-command))
(buf (process-buffer proc))
(win (or run-in-background
(mu4e~temp-window buf mu4e~update-buffer-height))))
(setq mu4e~update-buffer buf)
(when (window-live-p win)
(with-selected-window win
;; ;;(switch-to-buffer buf)
;; (set-window-dedicated-p win t)
(erase-buffer)
(insert "\n") ;; FIXME -- needed so output starts
(mu4e~update-mail-mode)))
(setq mu4e~progress-reporter
(unless mu4e-hide-index-messages
(make-progress-reporter
(mu4e-format "Retrieving mail..."))))
(set-process-sentinel proc 'mu4e~update-sentinel-func)
;; if we're running in the foreground, handle password requests
(unless run-in-background
(process-put proc 'x-interactive (not run-in-background))
(set-process-filter proc 'mu4e~get-mail-process-filter))))
(defun mu4e-update-mail-and-index (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
run-in-background is non-nil (or called with prefix-argument), run
in the background; otherwise, pop up a window."
(interactive "P")
(unless mu4e-get-mail-command
(mu4e-error "`mu4e-get-mail-command' is not defined"))
(if (and (buffer-live-p mu4e~update-buffer)
(process-live-p (get-buffer-process mu4e~update-buffer)))
(mu4e-message "Update process is already running")
(progn
(run-hooks 'mu4e-update-pre-hook)
(mu4e~update-mail-and-index-real run-in-background))))
(defun mu4e-kill-update-mail ()
"Stop the update process by killing it."
(interactive)
(let* ((proc (and (buffer-live-p mu4e~update-buffer)
(get-buffer-process mu4e~update-buffer))))
(when (process-live-p proc)
(kill-process proc t))))
(define-obsolete-function-alias 'mu4e-interrupt-update-mail
'mu4e-kill-update-mail "1.0-alpha0")
;;; Logging / debugging
(defconst mu4e~log-max-size 1000000
"Max number of characters to keep around in the log buffer.")
(defconst mu4e~log-buffer-name "*mu4e-log*"
"*internal* Name of the logging buffer.")
(defun mu4e~get-log-buffer ()
"Fetch (and maybe create) the log buffer."
(unless (get-buffer mu4e~log-buffer-name)
(with-current-buffer (get-buffer-create mu4e~log-buffer-name)
(view-mode)
(when (fboundp 'so-long-mode)
(unless (eq major-mode 'so-long-mode)
(eval '(so-long-mode))))
(setq buffer-undo-list t)))
mu4e~log-buffer-name)
(defun mu4e-log (type frm &rest args)
"Write a message of TYPE with format-string FRM and ARGS in
*mu4e-log* buffer, if the variable mu4e-debug is non-nil. Type is
either 'to-server, 'from-server or 'misc. This function is meant for debugging."
(when mu4e-debug
(with-current-buffer (mu4e~get-log-buffer)
(let* ((inhibit-read-only t)
(tstamp (propertize (format-time-string "%Y-%m-%d %T.%3N"
(current-time))
'face 'font-lock-string-face))
(msg-face
(cl-case type
(from-server 'font-lock-type-face)
(to-server 'font-lock-function-name-face)
(misc 'font-lock-variable-name-face)
(error 'font-lock-warning-face)
(otherwise (mu4e-error "Unsupported log type"))))
(msg (propertize (apply 'format frm args) 'face msg-face)))
(save-excursion
(goto-char (point-max))
(insert tstamp
(cl-case type
(from-server " <- ")
(to-server " -> ")
(error " !! ")
(otherwise " "))
msg "\n")
;; if `mu4e-log-max-lines is specified and exceeded, clearest the oldest
;; lines
(when (> (buffer-size) mu4e~log-max-size)
(goto-char (- (buffer-size) mu4e~log-max-size))
(beginning-of-line)
(delete-region (point-min) (point))))))))
(defun mu4e-toggle-logging ()
"Toggle between enabling/disabling debug-mode (in debug-mode,
mu4e logs some of its internal workings to a log-buffer. See
`mu4e-visit-log'."
(interactive)
(mu4e-log 'misc "logging disabled")
(setq mu4e-debug (not mu4e-debug))
(mu4e-message "debug logging has been %s"
(if mu4e-debug "enabled" "disabled"))
(mu4e-log 'misc "logging enabled"))
(defun mu4e-show-log ()
"Visit the mu4e debug log."
(interactive)
(unless mu4e-debug (mu4e-toggle-logging))
(let ((buf (get-buffer mu4e~log-buffer-name)))
(unless (buffer-live-p buf)
(mu4e-warn "No debug log available"))
(switch-to-buffer buf)))
(defun mu4e-split-ranges-to-numbers (str n)
"Convert STR containing attachment numbers into a list of numbers.
STR is a string; N is the highest possible number in the list.
This includes expanding e.g. 3-5 into 3,4,5. If the letter
\"a\" ('all')) is given, that is expanded to a list with numbers [1..n]."
(let ((str-split (split-string str))
beg end list)
(dolist (elem str-split list)
;; special number "a" converts into all attachments 1-N.
(when (equal elem "a")
(setq elem (concat "1-" (int-to-string n))))
(if (string-match "\\([0-9]+\\)-\\([0-9]+\\)" elem)
;; we have found a range A-B, which needs converting
;; into the numbers A, A+1, A+2, ... B.
(progn
(setq beg (string-to-number (match-string 1 elem))
end (string-to-number (match-string 2 elem)))
(while (<= beg end)
(cl-pushnew beg list :test 'equal)
(setq beg (1+ beg))))
;; else just a number
(cl-pushnew (string-to-number elem) list :test 'equal)))
;; Check that all numbers are valid.
(mapc
(lambda (x)
(cond
((> x n)
(mu4e-warn "Attachment %d bigger than maximum (%d)" x n))
((< x 1)
(mu4e-warn "Attachment number must be greater than 0 (%d)" x))))
list)))
;;; Misc 2
(defvar mu4e-imagemagick-identify "identify"
"Name/path of the Imagemagick 'identify' program.")
(defun mu4e~image-width-scale (width height max_width max_height)
"Returns a width to use for proportional image scaling
to satisfy both MAX_WIDTH and MAX_HEIGHT restrictions."
(floor
(if (<= width max_width)
(if (<= height max_height)
width ; both width and height ok, just return width
(* (/ max_height (float height)) width)) ; height is too large, scale width by hmax/h
(if (<= height max_height)
max_width ; width is too large, return max_width as scaling
(let ((width_heightscale (* (/ max_height (float height)) width)))
(min max_width width_heightscale)))))) ; both too large, return smallest width
(defun mu4e-display-image (imgpath &optional maxwidth maxheight)
"Display image IMG at point; optionally specify MAXWIDTH and
MAXHEIGHT. Function tries to use imagemagick if available (ie.,
emacs was compiled with imagemagick support); otherwise MAXWIDTH
and MAXHEIGHT are ignored."
(let* ((have-im (and (fboundp 'imagemagick-types)
(imagemagick-types))) ;; hmm, should check for specific type
(identify (and have-im maxwidth
(executable-find mu4e-imagemagick-identify)))
(props (and identify (mapcar 'string-to-number
(split-string (shell-command-to-string
(format "%s -format '%%w %%h' %s"
identify (shell-quote-argument imgpath)))))))
(width (and props (car props)))
(height (and props (car (cdr props))))
(img (if have-im
(create-image imgpath 'imagemagick nil
:width (mu4e~image-width-scale width height maxwidth maxheight))
(create-image imgpath))))
(when img
(save-excursion
(insert "\n")
(let ((size (image-size img))) ;; inspired by gnus..
(insert-char ?\n
(max 0 (round (- (window-height) (or maxheight (cdr size)) 1) 2)))
(insert-char ?\.
(max 0 (round (- (window-width) (or maxwidth (car size))) 2)))
(insert-image img))))))
(defun mu4e-hide-other-mu4e-buffers ()
"Bury mu4e-buffers (main, headers, view) (and delete all windows
displaying it). Do _not_ bury the current buffer, though."
(interactive)
(unless (eq mu4e-split-view 'single-window)
(let ((curbuf (current-buffer)))
;; note: 'walk-windows' does not seem to work correctly when modifying
;; windows; therefore, the doloops here
(dolist (frame (frame-list))
(dolist (win (window-list frame nil))
(with-current-buffer (window-buffer win)
(unless (eq curbuf (current-buffer))
(when (member major-mode '(mu4e-headers-mode mu4e-view-mode))
(when (eq t (window-deletable-p win))
(delete-window win))))))) t)))
(defun mu4e-get-time-date (prompt)
"Determine the emacs time value for the time/date entered by user
after PROMPT. Formats are all that are accepted by
`parse-time-string'."
(let ((timestr (read-string (mu4e-format "%s" prompt))))
(apply 'encode-time (org-parse-time-string timestr))))
;;; Mu4e-org-mode
(define-derived-mode mu4e-org-mode org-mode "mu4e:org"
"Major mode for mu4e documents, derived from
`org-mode'.")
(defun mu4e-info (path)
"Show a buffer with the information (an org-file) at PATH."
(unless (file-exists-p path)
(mu4e-error "Cannot find %s" path))
(let ((curbuf (current-buffer)))
(find-file path)
(mu4e-org-mode)
(setq buffer-read-only t)
(define-key mu4e-org-mode-map (kbd "q")
`(lambda ()
(interactive)
(bury-buffer)
(switch-to-buffer ,curbuf)))))
(defun mu4e-about ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/mu4e-about.org")))
(defun mu4e-news ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/NEWS.org")))
;;; Misc 3
(defun mu4e-refresh-message (path)
"Re-parse message at PATH; if this works, we will
receive (:info add :path <path> :docid <docid>) as well as (:update
<msg-sexp>)."
(mu4e~proc-add path))
(defun mu4e~fontify-cited ()
"Colorize message content based on the citation level. This is
used in the view and compose modes."
(save-excursion
(goto-char (point-min))
(when (search-forward-regexp "^\n" nil t) ;; search the first empty line
(while (re-search-forward mu4e-cited-regexp nil t)
(let* ((level (string-width (replace-regexp-in-string
"[^>]" "" (match-string 0))))
(face (unless (zerop level)
(intern-soft (format "mu4e-cited-%d-face" level)))))
(when face
(add-text-properties (line-beginning-position 1)
(line-end-position 1) `(face ,face))))))))
(defun mu4e~fontify-signature ()
"Give the message signatures a distinctive color. This is used in
the view and compose modes and will color each signature in digest messages adhering to RFC 1153."
(let ((inhibit-read-only t))
(save-excursion
;; give the footer a different color...
(goto-char (point-min))
(while (re-search-forward "^-- *$" nil t)
(let ((p (point))
(end (or
(re-search-forward "\\(^-\\{30\\}.*$\\)" nil t) ;; 30 by RFC1153
(point-max))))
(add-text-properties p end '(face mu4e-footer-face)))))))
;;; Misc 4
(defun mu4e~quote-for-modeline (str)
"Quote a string to be used literally in the modeline. The
string will be shortened to fit if its length exceeds
`mu4e-modeline-max-width'."
(replace-regexp-in-string
"%" "%%"
(truncate-string-to-width str mu4e-modeline-max-width 0 nil t)))
(defun mu4e~active-composition-buffers ()
"Return all active mu4e composition buffers"
(let (buffers)
(save-excursion
(dolist (buffer (buffer-list t))
(set-buffer buffer)
(when (eq major-mode 'mu4e-compose-mode)
(push (buffer-name buffer) buffers))))
(nreverse buffers)))
;;
;; Loading messages
;;
(defvar mu4e-loading-mode-map nil "Keymap for *mu4e-loading* buffers.")
(unless mu4e-loading-mode-map
(setq mu4e-loading-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "n" 'ignore)
(define-key map "p" 'ignore)
(define-key map "q"
(lambda()(interactive)
(if (eq mu4e-split-view 'single-window)
'kill-buffer
'kill-buffer-and-window)))
map)))
(fset 'mu4e-loading-mode-map mu4e-loading-mode-map)
(define-derived-mode mu4e-loading-mode special-mode
"mu4e:loading"
(use-local-map mu4e-loading-mode-map)
(let ((inhibit-read-only t))
(erase-buffer)
(insert (propertize "Loading message..."
'face 'mu4e-system-face 'intangible t))))
;;
;; Bug Reference mode support
;;
;; This is Emacs 28 stuff but there is no need to guard it with some (f)boundp
;; checks (which would return nil if bug-reference.el is not loaded before
;; mu4e) since the function definition doesn't hurt and `add-hook' works fine
;; for not yet defined variables (by creating them).
(declare-function bug-reference-maybe-setup-from-mail "ext:bug-reference")
(defun mu4e-view--try-setup-bug-reference-mode ()
"Try to guess bug-reference setup from the current mu4e mail.
Looks at the maildir and the mail headers List, List-Id, Maildir,
To, From, Cc, and Subject and tries to guess suitable values for
`bug-reference-bug-regexp' and `bug-reference-url-format' by
matching the maildir name against GROUP-REGEXP and each header
value against HEADER-REGEXP in
`bug-reference-setup-from-mail-alist'."
(when (derived-mode-p 'mu4e-view-mode)
(let (header-values)
(save-excursion
(goto-char (point-min))
(dolist (field '("list" "list-id" "to" "from" "cc" "subject"))
(let ((val (mail-fetch-field field)))
(when val
(push val header-values)))))
(bug-reference-maybe-setup-from-mail
(mail-fetch-field "maildir")
header-values))))
(add-hook 'bug-reference-auto-setup-functions
#'mu4e-view--try-setup-bug-reference-mode)
;;; _
(provide 'mu4e-utils)
;;; mu4e-utils.el ends here
| 23337 | ;;; mu4e-utils.el -- part of mu4e, the mu mail user agent -*- lexical-binding: t -*-
;; Copyright (C) 2011-2020 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; This file is not part of GNU Emacs.
;; mu4e is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; mu4e 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 mu4e. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Utility functions used in the mu4e
;;; Code:
(require 'org)
(require 'cl-lib)
(require 'cl-seq nil 'noerror)
(require 'mu4e-vars)
(require 'mu4e-message)
(require 'mu4e-meta)
(require 'mu4e-lists)
(require 'doc-view)
;; keep the byte-compiler happy
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-ping "mu4e-proc")
(declare-function mu4e~proc-contacts "mu4e-proc")
(declare-function mu4e~proc-kill "mu4e-proc")
(declare-function mu4e~proc-index "mu4e-proc")
(declare-function mu4e~proc-add "mu4e-proc")
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e-message-field-at-point "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e~main-view "mu4e-main")
(declare-function mu4e~context-autoswitch "mu4e-context")
(declare-function mu4e-context-determine "mu4e-context")
(declare-function mu4e-context-vars "mu4e-context")
(declare-function mu4e-context-current "mu4e-context")
(declare-function show-all "org")
;;; Various
(defun mu4e-copy-message-path ()
"Copy the message-path of message at point to the kill-ring."
(interactive)
(let ((path (mu4e-message-field-at-point :path)))
(kill-new path)
(mu4e-message "Saved '%s' to kill-ring" path)))
(defun mu4e-personal-address-p (addr)
"Is ADDR a personal address?
Evaluate to nil if ADDR matches any of the personal addresses.
Uses (mu4e-personal-addresses) for the addresses with both the plain
addresses and /regular expressions/."
(when addr
(seq-find
(lambda (m)
(if (string-match "/\\(.*\\)/" m)
(let ((rx (match-string 1 m))
(case-fold-search t))
(if (string-match rx addr) t nil))
(eq t (compare-strings addr nil nil m nil nil 'case-insensitive))))
(mu4e-personal-addresses))))
(define-obsolete-function-alias 'mu4e-user-mail-address-p
'mu4e-personal-address-p "1.5.5")
(defmacro with~mu4e-context-vars (context &rest body)
"Evaluate BODY, with variables let-bound for CONTEXT (if any).
`funcall'."
(declare (indent 2))
`(let* ((vars (and ,context (mu4e-context-vars ,context))))
(cl-progv ;; XXX: perhaps use eval's lexical environment instead of progv?
(mapcar (lambda(cell) (car cell)) vars)
(mapcar (lambda(cell) (cdr cell)) vars)
(eval ,@body))))
;;; Folders (1/2)
;; the standard folders can be functions too
(defun mu4e~get-folder (foldervar msg)
"Within the mu-context of MSG, get message folder FOLDERVAR.
If FOLDER is a string, return it, if it is a function, evaluate
this function with MSG as parameter (which may be `nil'), and
return the result."
(unless (member foldervar
'(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder mu4e-refile-folder))
(mu4e-error "Folder must be one of mu4e-(sent|drafts|trash|refile)-folder"))
;; get the value with the vars for the relevants context let-bound
(with~mu4e-context-vars (mu4e-context-determine msg nil)
(let* ((folder (symbol-value foldervar))
(val
(cond
((stringp folder) folder)
((functionp folder) (funcall folder msg))
(t (mu4e-error "unsupported type for %S" folder)))))
(or val (mu4e-error "%S evaluates to nil" foldervar)))))
(defun mu4e-get-drafts-folder (&optional msg)
"Get the sent folder. See `mu4e-drafts-folder'."
(mu4e~get-folder 'mu4e-drafts-folder msg))
(defun mu4e-get-refile-folder (&optional msg)
"Get the folder for refiling. See `mu4e-refile-folder'."
(mu4e~get-folder 'mu4e-refile-folder msg))
(defun mu4e-get-sent-folder (&optional msg)
"Get the sent folder. See `mu4e-sent-folder'."
(mu4e~get-folder 'mu4e-sent-folder msg))
(defun mu4e-get-trash-folder (&optional msg)
"Get the sent folder. See `mu4e-trash-folder'."
(mu4e~get-folder 'mu4e-trash-folder msg))
;;; Self-destructing files
(defun mu4e-remove-file-later (filename)
"Remove FILENAME in a few seconds."
(run-at-time "30 sec" nil
(lambda () (ignore-errors (delete-file filename)))))
(defun mu4e-make-temp-file (ext)
"Create a temporary file with extension EXT. The file will
self-destruct in a few seconds, enough to open it in another
program."
(let ((tmpfile (make-temp-file "mu4e-" nil (concat "." ext))))
(mu4e-remove-file-later tmpfile)
tmpfile))
;;; Folders (2/2)
;;
;; mu4e-attachment-dir is either a string or a function that takes a
;; filename and the mime-type as argument, either (or both) which can
;; be nil
(defun mu4e~get-attachment-dir (&optional fname mimetype)
"Get the directory for saving attachments from
`mu4e-attachment-dir' (which can be either a string or a function,
see its docstring)."
(let
((dir
(cond
((stringp mu4e-attachment-dir)
mu4e-attachment-dir)
((functionp mu4e-attachment-dir)
(funcall mu4e-attachment-dir fname mimetype))
(t
(mu4e-error "unsupported type for mu4e-attachment-dir" )))))
(if dir
(expand-file-name dir)
(mu4e-error "mu4e-attachment-dir evaluates to nil"))))
;;; Maildir (1/2)
(defun mu4e~guess-maildir (path)
"Guess the maildir for some path, or nil if cannot find it."
(let ((idx (string-match (mu4e-root-maildir) path)))
(when (and idx (zerop idx))
(replace-regexp-in-string
(mu4e-root-maildir)
""
(expand-file-name
(concat path "/../.."))))))
(defun mu4e-create-maildir-maybe (dir)
"Offer to create maildir DIR if it does not exist yet.
Return t if the dir already existed, or an attempt has been made to
create it -- we cannot be sure creation succeeded here, since this
is done asynchronously. Otherwise, return nil. NOte, DIR has to be
an absolute path."
(if (and (file-exists-p dir) (not (file-directory-p dir)))
(mu4e-error "%s exists, but is not a directory." dir))
(cond
((file-directory-p dir) t)
((yes-or-no-p (mu4e-format "%s does not exist yet. Create now?" dir))
(mu4e~proc-mkdir dir) t)
(t nil)))
;;; Messages, warnings and errors
(defun mu4e-format (frm &rest args)
"Create [mu4e]-prefixed string based on format FRM and ARGS."
(concat
"[" (propertize "mu4e" 'face 'mu4e-title-face) "] "
(apply 'format frm
(mapcar (lambda (x)
(if (stringp x)
(decode-coding-string x 'utf-8)
x))
args))))
(defun mu4e-message (frm &rest args)
"Like `message', but prefixed with mu4e.
If we're waiting for user-input or if there's some message in the
echo area, don't show anything."
(unless (or (active-minibuffer-window))
(message "%s" (apply 'mu4e-format frm args))))
(defun mu4e-index-message (frm &rest args)
"Like `mu4e-message', but specifically for
index-messages. Doesn't display anything if
`mu4e-hide-index-messages' is non-nil. "
(unless mu4e-hide-index-messages
(apply 'mu4e-message frm args)))
(defun mu4e-error (frm &rest args)
"Create [mu4e]-prefixed error based on format FRM and ARGS.
Does a local-exit and does not return, and raises a
debuggable (backtrace) error."
(mu4e-log 'error (apply 'mu4e-format frm args))
(error "%s" (apply 'mu4e-format frm args)))
;; the user-error function is only available in emacs-trunk
(unless (fboundp 'user-error)
(defalias 'user-error 'error))
(defun mu4e-warn (frm &rest args)
"Create [mu4e]-prefixed warning based on format FRM and ARGS.
Does a local-exit and does not return. In emacs versions below
24.2, the functions is the same as `mu4e-error'."
(mu4e-log 'error (apply 'mu4e-format frm args))
(user-error "%s" (apply 'mu4e-format frm args)))
;;; Reading user input
(defun mu4e~read-char-choice (prompt choices)
"Read and return one of CHOICES, prompting for PROMPT.
Any input that is not one of CHOICES is ignored. This mu4e's
version of `read-char-choice', that becomes case-insentive after
trying an exact match."
(let ((choice) (chosen) (inhibit-quit nil))
(while (not chosen)
(message nil);; this seems needed...
(setq choice (read-char-exclusive prompt))
(if (eq choice 27) (keyboard-quit)) ;; quit if ESC is pressed
(setq chosen (or (member choice choices)
(member (downcase choice) choices)
(member (upcase choice) choices))))
(car chosen)))
(defun mu4e-read-option (prompt options)
"Ask user for an option from a list on the input area.
PROMPT describes a multiple-choice question to the user.
OPTIONS describe the options, and is a list of cells describing
particular options. Cells have the following structure:
(OPTIONSTRING . RESULT)
where OPTIONSTRING is a non-empty string describing the
option. The first character of OPTIONSTRING is used as the
shortcut, and obviously all shortcuts must be different, so you
can prefix the string with an uniquifying character.
The options are provided as a list for the user to choose from;
user can then choose by typing CHAR. Example:
(mu4e-read-option \"Choose an animal: \"
'((\"Monkey\" . monkey) (\"Gnu\" . gnu) (\"xMoose\" . moose)))
User now will be presented with a list: \"Choose an animal:
[M]onkey, [G]nu, [x]Moose\".
Function will return the cdr of the list element."
(let* ((prompt (mu4e-format "%s" prompt))
(optionsstr
(mapconcat
(lambda (option)
;; try to detect old-style options, and warn
(when (characterp (car-safe (cdr-safe option)))
(mu4e-error
(concat "Please use the new format for options/actions; "
"see the manual")))
(let ((kar (substring (car option) 0 1)))
(concat
"[" (propertize kar 'face 'mu4e-highlight-face) "]"
(substring (car option) 1))))
options ", "))
(response
(mu4e~read-char-choice
(concat prompt optionsstr
" [" (propertize "C-g" 'face 'mu4e-highlight-face)
" to cancel]")
;; the allowable chars
(cl-map 'list (lambda(elm) (string-to-char (car elm))) options)))
(chosen
(cl-find-if
(lambda (option) (eq response (string-to-char (car option))))
options)))
(if chosen
(cdr chosen)
(mu4e-warn "Unknown shortcut '%c'" response))))
;;; Maildir (1/2)
(defun mu4e~get-maildirs-1 (path mdir)
"Get maildirs under path, recursively, as a list of relative paths."
(let ((dirs)
(dentries
(ignore-errors
(directory-files-and-attributes
(concat path mdir) nil
"^[^.]\\|\\.[^.][^.]" t))))
(dolist (dentry dentries)
(when (and (booleanp (cadr dentry)) (cadr dentry))
(if (file-accessible-directory-p
(concat (mu4e-root-maildir) "/" mdir "/" (car dentry) "/cur"))
(setq dirs (cons (concat mdir (car dentry)) dirs)))
(unless (member (car dentry) '("cur" "new" "tmp"))
(setq dirs (append dirs (mu4e~get-maildirs-1 path
(concat mdir (car dentry) "/")))))))
dirs))
(defvar mu4e-cache-maildir-list nil
"Whether to cache the list of maildirs; set it to t if you find
that generating the list on the fly is too slow. If you do, you
can set `(mu4e-root-maildir)-list' to nil to force regenerating the
cache the next time `mu4e-get-maildirs' gets called.")
(defvar mu4e-maildir-list nil
"Cached list of maildirs.")
(defun mu4e-get-maildirs ()
"Get maildirs under `mu4e-maildir', recursively, as a list of
relative paths (ie., /archive, /sent etc.). Most of the work is
done in `mu4e~get-maildirs-1'. Note, these results are /cached/
if `mu4e-cache-maildir-list' is customized to non-nil. In that case,
the list of maildirs will not change until you restart mu4e."
(unless (and mu4e-maildir-list mu4e-cache-maildir-list)
(setq mu4e-maildir-list
(sort
(append
(when (file-accessible-directory-p
(concat (mu4e-root-maildir) "/cur")) '("/"))
(mu4e~get-maildirs-1 (mu4e-root-maildir) "/"))
(lambda (s1 s2) (string< (downcase s1) (downcase s2))))))
mu4e-maildir-list)
(defun mu4e-ask-maildir (prompt)
"Ask the user for a shortcut (using PROMPT) as per
(mu4e-maildir-shortcuts), then return the corresponding folder
name. If the special shortcut 'o' (for _o_ther) is used, or if
`(mu4e-maildir-shortcuts)' evaluates to nil, let user choose from
all maildirs under `mu4e-maildir'."
(let ((prompt (mu4e-format "%s" prompt)))
(if (not (mu4e-maildir-shortcuts))
(substring-no-properties
(funcall mu4e-completing-read-function prompt (mu4e-get-maildirs)))
(let* ((mlist (append (mu4e-maildir-shortcuts)
'((:maildir "ther" :key ?o))))
(fnames
(mapconcat
(lambda (item)
(concat
"["
(propertize (make-string 1 (plist-get item :key))
'face 'mu4e-highlight-face)
"]"
(plist-get item :maildir)))
mlist ", "))
(kar (read-char (concat prompt fnames))))
(if (member kar '(?/ ?o)) ;; user chose 'other'?
(substring-no-properties
(funcall mu4e-completing-read-function prompt
(mu4e-get-maildirs) nil nil "/"))
(or (plist-get
(cl-find-if (lambda (item) (= kar (plist-get item :key)))
(mu4e-maildir-shortcuts)) :maildir)
(mu4e-warn "Unknown shortcut '%c'" kar)))))))
(defun mu4e-ask-maildir-check-exists (prompt)
"Like `mu4e-ask-maildir', but check for existence of the maildir,
and offer to create it if it does not exist yet."
(let* ((mdir (mu4e-ask-maildir prompt))
(fullpath (concat (mu4e-root-maildir) mdir)))
(unless (file-directory-p fullpath)
(and (yes-or-no-p
(mu4e-format "%s does not exist. Create now?" fullpath))
(mu4e~proc-mkdir fullpath)))
mdir))
;;; Bookmarks
(defun mu4e-ask-bookmark (prompt)
"Ask the user for a bookmark (using PROMPT) as defined in
`mu4e-bookmarks', then return the corresponding query."
(unless (mu4e-bookmarks) (mu4e-error "No bookmarks defined"))
(let* ((prompt (mu4e-format "%s" prompt))
(bmarks
(mapconcat
(lambda (bm)
(concat
"[" (propertize (make-string 1 (plist-get bm :key))
'face 'mu4e-highlight-face)
"]"
(plist-get bm :name))) (mu4e-bookmarks) ", "))
(kar (read-char (concat prompt bmarks))))
(mu4e-get-bookmark-query kar)))
(defun mu4e-get-bookmark-query (kar)
"Get the corresponding bookmarked query for shortcut character
KAR, or raise an error if none is found."
(let* ((chosen-bm
(or (cl-find-if
(lambda (bm)
(= kar (plist-get bm :key)))
(mu4e-bookmarks))
(mu4e-warn "Unknown shortcut '%c'" kar)))
(expr (plist-get chosen-bm :query))
(expr (if (not (functionp expr)) expr
(funcall expr)))
(query (eval expr)))
(if (stringp query)
query
(mu4e-warn "Expression must evaluate to query string ('%S')" expr))))
(defun mu4e-bookmark-define (query name key)
"Define a bookmark for QUERY with name NAME and
shortcut-character KEY in the list of `mu4e-bookmarks'. This
replaces any existing bookmark with KEY."
(setq mu4e-bookmarks
(cl-remove-if
(lambda (bm)
(= (plist-get bm :key) key))
(mu4e-bookmarks)))
(cl-pushnew `(:name ,name
:query ,query
:key ,key)
mu4e-bookmarks :test 'equal))
;;; Converting flags->string and vice-versa
(defun mu4e~flags-to-string-raw (flags)
"Convert a list of flags into a string as seen in Maildir
message files; flags are symbols draft, flagged, new, passed,
replied, seen, trashed and the string is the concatenation of the
uppercased first letters of these flags, as per [1]. Other flags
than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html"
(when flags
(let ((kar (cl-case (car flags)
('draft ?D)
('flagged ?F)
('new ?N)
('passed ?P)
('replied ?R)
('seen ?S)
('trashed ?T)
('attach ?a)
('encrypted ?x)
('signed ?s)
('unread ?u))))
(concat (and kar (string kar))
(mu4e~flags-to-string-raw (cdr flags))))))
(defun mu4e-flags-to-string (flags)
"Remove duplicates and sort the output of `mu4e~flags-to-string-raw'."
(concat
(sort (cl-remove-duplicates
(append (mu4e~flags-to-string-raw flags) nil)) '>)))
(defun mu4e~string-to-flags-1 (str)
"Convert a string with message flags as seen in Maildir
messages into a list of flags in; flags are symbols draft,
flagged, new, passed, replied, seen, trashed and the string is
the concatenation of the uppercased first letters of these flags,
as per [1]. Other letters than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html."
(when (/= 0 (length str))
(let ((flag
(cl-case (string-to-char str)
(?D 'draft)
(?F 'flagged)
(?P 'passed)
(?R 'replied)
(?S 'seen)
(?T 'trashed))))
(append (when flag (list flag))
(mu4e~string-to-flags-1 (substring str 1))))))
(defun mu4e-string-to-flags (str)
"Convert a string with message flags as seen in Maildir messages
into a list of flags in; flags are symbols draft, flagged, new,
passed, replied, seen, trashed and the string is the concatenation
of the uppercased first letters of these flags, as per [1]. Other
letters than the ones listed here are ignored. Also see
`mu4e-flags-to-string'. \[1\]:
http://cr.yp.to/proto/maildir.html "
;; "Remove duplicates from the output of `mu4e~string-to-flags-1'"
(cl-remove-duplicates (mu4e~string-to-flags-1 str)))
;;; Various
(defun mu4e-display-size (size)
"Get a string representation of SIZE (in bytes)."
(cond
((>= size 1000000) (format "%2.1fM" (/ size 1000000.0)))
((and (>= size 1000) (< size 1000000))
(format "%2.1fK" (/ size 1000.0)))
((< size 1000) (format "%d" size))
(t (propertize "?" 'face 'mu4e-system-face))))
(defun mu4e-display-manual ()
"Display the mu4e manual page for the current mode.
Or go to the top level if there is none."
(interactive)
(info (cl-case major-mode
('mu4e-main-mode "(mu4e)Main view")
('mu4e-headers-mode "(mu4e)Headers view")
('mu4e-view-mode "(mu4e)Message view")
(t "mu4e"))))
;;; Misc
(defun mu4e-last-query ()
"Get the most recent query or nil if there is none."
(when (buffer-live-p (mu4e-get-headers-buffer))
(with-current-buffer (mu4e-get-headers-buffer)
mu4e~headers-last-query)))
(defvar gnus-article-buffer) ;; Fix byte-compiler warning.
(defun mu4e-get-view-buffer ()
"Get the view buffer, if any."
(get-buffer
(if mu4e-view-use-old
mu4e~view-buffer-name
gnus-article-buffer)))
(defun mu4e-get-headers-buffer ()
(get-buffer mu4e~headers-buffer-name))
(defun mu4e-select-other-view ()
"When the headers view is selected, select the message view (if
that has a live window), and vice versa."
(interactive)
(let* ((other-buf
(cond
((eq major-mode 'mu4e-headers-mode)
(mu4e-get-view-buffer))
((eq major-mode 'mu4e-view-mode)
(mu4e-get-headers-buffer))))
(other-win (and other-buf (get-buffer-window other-buf))))
(if (window-live-p other-win)
(select-window other-win)
(mu4e-message "No window to switch to"))))
(defconst mu4e-output-buffer-name "*mu4e-output*"
"*internal* Name of the mu4e output buffer.")
(defun mu4e-process-file-through-pipe (path pipecmd)
"Process file at PATH through a pipe with PIPECMD."
(let ((buf (get-buffer-create mu4e-output-buffer-name)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(call-process-shell-command pipecmd path t t)
(view-mode)))
(switch-to-buffer buf)))
(defvar mu4e~lists-hash nil
"Hashtable of mailing-list-id => shortname, based on
`mu4e~mailing-lists' and `mu4e-user-mailing-lists'.")
(defun mu4e-get-mailing-list-shortname (list-id)
"Get the shortname for a mailing-list with list-id LIST-ID. based
on `mu4e~mailing-lists', `mu4e-user-mailing-lists', and
`mu4e-mailing-list-patterns'."
(unless mu4e~lists-hash
(setq mu4e~lists-hash (make-hash-table :test 'equal))
(dolist (cell mu4e~mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash))
(dolist (cell mu4e-user-mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash)))
(or
(gethash list-id mu4e~lists-hash)
(and (boundp 'mu4e-mailing-list-patterns)
(cl-member-if
(lambda (pattern)
(string-match pattern list-id))
mu4e-mailing-list-patterns)
(match-string 1 list-id))
;; if it's not in the db, take the part until the first dot if there is one;
;; otherwise just return the whole thing
(if (string-match "\\([^.]*\\)\\." list-id)
(match-string 1 list-id)
list-id)))
(defvar mu4e-index-updated-hook nil
"Hook run when the indexing process had one or more updated messages.
This can be used as a simple way to invoke some action when new
messages appear, but note that an update in the index does not
necessarily mean a new message.")
(defvar mu4e-message-changed-hook nil
"Hook run when there is a message changed in db. For new
messages, it depends on `mu4e-index-updated-hook'. This can be
used as a simple way to invoke some action when a message
changed.")
(make-obsolete-variable 'mu4e-msg-changed-hook
'mu4e-message-changed-hook "0.9.19")
(defvar mu4e~contacts-tstamp "0"
"Timestamp for the most recent contacts update." )
;;; Some handler functions for server messages
(defun mu4e-info-handler (info)
"Handler function for (:info ...) sexps received from the server
process."
(let* ((type (plist-get info :info))
(processed (plist-get info :processed))
(updated (plist-get info :updated))
(cleaned-up (plist-get info :cleaned-up))
(mainbuf (get-buffer mu4e-main-buffer-name)))
(cond
((eq type 'add) t) ;; do nothing
((eq type 'index)
(if (eq (plist-get info :status) 'running)
(mu4e-index-message
"Indexing... processed %d, updated %d" processed updated)
(progn
(mu4e-index-message
"%s completed; processed %d, updated %d, cleaned-up %d"
(if mu4e-index-lazy-check "Lazy indexing" "Indexing")
processed updated cleaned-up)
;; call the updated hook if anything changed.
(unless (zerop (+ updated cleaned-up))
(run-hooks 'mu4e-index-updated-hook))
(unless (and (not (string= mu4e~contacts-tstamp "0"))
(zerop (plist-get info :updated)))
(mu4e~request-contacts-maybe))
(when (and (buffer-live-p mainbuf) (get-buffer-window mainbuf))
(save-window-excursion
(select-window (get-buffer-window mainbuf))
(mu4e~main-view 'refresh))))))
((plist-get info :message)
(mu4e-index-message "%s" (plist-get info :message))))))
(defun mu4e-error-handler (errcode errmsg)
"Handler function for showing an error."
;; don't use mu4e-error here; it's running in the process filter context
(cl-case errcode
(4 (user-error "No matches for this search query."))
(110 (display-warning 'mu4e errmsg :error)) ;; schema version.
(t (error "Error %d: %s" errcode errmsg))))
;;; Contacts
(defun mu4e~update-contacts (contacts &optional tstamp)
"Receive a sorted list of CONTACTS.
Each of the contacts has the form
(FULL_EMAIL_ADDRESS . RANK) and fill `mu4e~contacts-hash' with
it, with each contact mapped to an integer for their ranking.
This is used by the completion function in mu4e-compose."
;; We have our nicely sorted list, map them to a list
;; of increasing integers. We use that map in the composer
;; to sort them there. It would have been so much easier if emacs
;; allowed us to use the sorted-list as-is, but no such luck.
(let ((n 0))
(unless mu4e~contacts-hash
(setq mu4e~contacts-hash (make-hash-table :test 'equal :weakness nil
:size (length contacts))))
(dolist (contact contacts)
(cl-incf n)
(let* ((address (plist-get contact :address))
(address
(if (functionp mu4e-contact-process-function)
(funcall mu4e-contact-process-function address)
address)))
(when address ;; note the explicit deccode; the strings we get are utf-8,
;; but emacs doesn't know yet.
(puthash (decode-coding-string address 'utf-8)
(plist-get contact :rank) mu4e~contacts-hash))))
(setq mu4e~contacts-tstamp (or tstamp "0"))
(unless (zerop n)
(mu4e-index-message "Contacts updated: %d; total %d"
n (hash-table-count mu4e~contacts-hash)))))
(defun mu4e-contacts-info ()
"Display information about the cache used for contacts
completion; for testing/debugging."
(interactive)
(with-current-buffer (get-buffer-create "*mu4e-contacts-info*")
(erase-buffer)
(insert (format "complete addresses: %s\n"
(if mu4e-compose-complete-addresses "yes" "no")))
(insert (format "only personal addresses: %s\n"
(if mu4e-compose-complete-only-personal "yes" "no")))
(insert (format "only addresses seen after: %s\n"
(or mu4e-compose-complete-only-after "no restrictions")))
(when mu4e~contacts-hash
(insert (format "number of contacts cached: %d\n\n"
(hash-table-count mu4e~contacts-hash)))
(let ((contacts))
(maphash (lambda (addr rank)
(setq contacts (cons (cons rank addr) contacts)))
mu4e~contacts-hash)
(setq contacts (sort contacts
(lambda(cell1 cell2) (< (car cell1) (car cell2)))))
(dolist (contact contacts)
(insert (format "%s\n" (cdr contact))))))
(pop-to-buffer "*mu4e-contacts-info*")))
(defun mu4e~check-requirements ()
"Check for the settings required for running mu4e."
(unless (>= emacs-major-version 25)
(mu4e-error "Emacs >= 25.x is required for mu4e"))
(when mu4e~server-props
(unless (string= (mu4e-server-version) mu4e-mu-version)
(mu4e-error "mu server has version %s, but we need %s"
(mu4e-server-version) mu4e-mu-version)))
(unless (and mu4e-mu-binary (file-executable-p mu4e-mu-binary))
(mu4e-error "Please set `mu4e-mu-binary' to the full path to the mu
binary."))
(dolist (var '(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder))
(unless (and (boundp var) (symbol-value var))
(mu4e-error "Please set %S" var))
(unless (functionp (symbol-value var)) ;; functions are okay, too
(let* ((dir (symbol-value var))
(path (concat (mu4e-root-maildir) dir)))
(unless (string= (substring dir 0 1) "/")
(mu4e-error "%S must start with a '/'" dir))
(unless (mu4e-create-maildir-maybe path)
(mu4e-error "%s (%S) does not exist" path var))))))
(defun mu4e-running-p ()
"Whether mu4e is running.
Checks whether the server process is live."
(mu4e~proc-running-p))
;;; Starting / getting mail / updating the index
(defvar mu4e~update-timer nil
"The mu4e update timer.")
(defconst mu4e~update-name " *mu4e-update*"
"Name of the process and buffer to update mail.")
(defconst mu4e~update-buffer-height 8
"Height of the mu4e message retrieval/update buffer.")
(defvar mu4e~get-mail-ask-password "mu4e get-mail: Enter password: "
"Query string for `mu4e-get-mail-command' password.")
(defvar mu4e~get-mail-password-regexp "^Remote: Enter password: $"
"Regexp to match a password query in the `mu4e-get-mail-command' output.")
(defun mu4e~request-contacts-maybe ()
"If `mu4e-compose-complete-addresses' is non-nil, get/update
the list of contacts we use for autocompletion; otherwise, do
nothing."
(when mu4e-compose-complete-addresses
(setq mu4e-contacts-func 'mu4e~update-contacts)
(mu4e~proc-contacts
mu4e-compose-complete-only-personal
mu4e-compose-complete-only-after
mu4e~contacts-tstamp)))
(defun mu4e~pong-handler (data func)
"Handle 'pong' responses from the mu server."
(setq mu4e~server-props (plist-get data :props)) ;; save info from the server
(let ((doccount (plist-get mu4e~server-props :doccount)))
(mu4e~check-requirements)
(when func (funcall func))
(when (zerop doccount)
(mu4e-message "Store is empty; (re)indexing. This may take a while.") ;
(mu4e-update-index))
(when (and mu4e-update-interval (null mu4e~update-timer))
(setq mu4e~update-timer
(run-at-time 0 mu4e-update-interval
(lambda () (mu4e-update-mail-and-index
mu4e-index-update-in-background)))))))
(defun mu4e-last-query-results ()
"Get the results (counts) of the last cached queries.
The cached queries are the bookmark / maildir queries that are
used to populated the read/unread counts in the main view. They
are refreshed when calling `(mu4e)', i.e., when going to the main
view.
The results are a list of elements of the form
(:query \"query string\"
:count <total number matching count>
:unread <number of unread messages in count>)"
(plist-get mu4e~server-props :queries))
(defun mu4e-last-query-result (query)
"Get the last result for some cached query, as per
`mu4e-bookmark-query-results' or nil if not found."
(cl-find-if
(lambda (elm) (string= (plist-get elm :query) query))
(mu4e-last-query-results)))
(defun mu4e~start (&optional func)
"If `mu4e-contexts' have been defined, but we don't have a
context yet, switch to the matching one, or none matches, the
first. If mu4e is already running, execute function FUNC (if
non-nil). Otherwise, check various requireme`'nts, then start mu4e.
When successful, call FUNC (if non-nil) afterwards."
(unless (mu4e-context-current)
(mu4e~context-autoswitch nil mu4e-context-policy))
(setq mu4e-pong-func (lambda (info) (mu4e~pong-handler info func)))
(mu4e~proc-ping
(mapcar ;; send it a list of queries we'd like to see read/unread info for
(lambda (bm)
(funcall (or mu4e-query-rewrite-function #'identity)
(plist-get bm :query)))
;; exclude bookmarks that are not strings, and with certain flags
(seq-filter (lambda (bm)
(and (stringp (plist-get bm :query))
(not (or (plist-get bm :hide) (plist-get bm :hide-unread)))))
(append (mu4e-bookmarks)
(mu4e~maildirs-with-query)))))
;; maybe request the list of contacts, automatically refreshed after
;; reindexing
(unless mu4e~contacts-hash (mu4e~request-contacts-maybe)))
(defun mu4e-clear-caches ()
"Clear any cached resources."
(setq
mu4e-maildir-list nil
mu4e~contacts-hash nil
mu4e~contacts-tstamp "0"))
(defun mu4e~stop ()
"Stop the mu4e session."
(when mu4e~update-timer
(cancel-timer mu4e~update-timer)
(setq mu4e~update-timer nil))
(mu4e-clear-caches)
(mu4e~proc-kill)
;; kill all mu4e buffers
(mapc
(lambda (buf)
;; When using the Gnus-based viewer, the view buffer has the
;; kill-buffer-hook function mu4e~view-kill-buffer-hook-fn which kills the
;; mm-* buffers created by Gnus' article mode. Those have been returned by
;; `buffer-list' but might already be deleted in case the view buffer has
;; been killed first. So we need a `buffer-live-p' check here.
(when (buffer-live-p buf)
(with-current-buffer buf
(when (member major-mode
'(mu4e-headers-mode mu4e-view-mode mu4e-main-mode))
(kill-buffer)))))
(buffer-list)))
(defun mu4e~maildirs-with-query ()
"Return a copy of `mu4e-maildirs-shortcuts' with :query populated.
This is meant to be the exact same data structure as
`mu4e-bookmarks'."
(cl-mapcar
(lambda (m)
(append
;; we want to change the :maildir key to :name, and add a :query key
(list :name (plist-get m :maildir)
:query (format "maildir:\"%s\"" (plist-get m :maildir)))
;; next we want to append any other keys to our previous list (e.g. :hide,
;; :key, etc) but skipping :maildir (since it's renamed to :name)
(cl-loop for (key value) on m by 'cddr
when (not (equal key :maildir))
append (list key value))))
(mu4e-maildir-shortcuts)))
(defun mu4e~longest-of-maildirs-and-bookmarks ()
"Return the length of longest name of bookmarks and maildirs."
(cl-loop for b in (append (mu4e-bookmarks)
(mu4e~maildirs-with-query))
maximize (string-width (plist-get b :name))))
;;; Indexing & Updating
(defvar mu4e~progress-reporter nil
"Internal, the progress reporter object.")
(defun mu4e~get-mail-process-filter (proc msg)
"Filter the output of `mu4e-get-mail-command'.
Currently the filter only checks if the command asks for a password
by matching the output against `mu4e~get-mail-password-regexp'.
The messages are inserted into the process buffer.
Also scrolls to the final line, and update the progress throbber."
(when mu4e~progress-reporter
(progress-reporter-update mu4e~progress-reporter))
(when (string-match mu4e~get-mail-password-regexp msg)
(if (process-get proc 'x-interactive)
(process-send-string proc
(concat (read-passwd mu4e~get-mail-ask-password)
"\n"))
;; TODO kill process?
(mu4e-error "Unrecognized password request")))
(when (process-buffer proc)
(let ((inhibit-read-only t)
(procwin (get-buffer-window (process-buffer proc))))
;; Insert at end of buffer. Leave point alone.
(with-current-buffer (process-buffer proc)
(goto-char (point-max))
(if (string-match ".*\r\\(.*\\)" msg)
(progn
;; kill even with \r
(end-of-line)
(let ((end (point)))
(beginning-of-line)
(delete-region (point) end))
(insert (match-string 1 msg)))
(insert msg)))
;; Auto-scroll unless user is interacting with the window.
(when (and (window-live-p procwin)
(not (eq (selected-window) procwin)))
(with-selected-window procwin
(goto-char (point-max)))))))
(defun mu4e-update-index ()
"Update the mu4e index."
(interactive)
(mu4e~proc-index mu4e-index-cleanup mu4e-index-lazy-check))
(defun mu4e-update-index-nonlazy ()
"Update the mu4e index non-lazily.
This is just a convenience wrapper for indexing the non-lazy way
if you otherwise want to use `mu4e-index-lazy-check'."
(interactive)
(let ((mu4e-index-cleanup t) (mu4e-index-lazy-check nil))
(mu4e-update-index)))
(defvar mu4e~update-buffer nil
"Internal, store the buffer of the update process when
updating.")
(define-derived-mode mu4e~update-mail-mode special-mode "mu4e:update"
"Major mode used for retrieving new e-mail messages in `mu4e'.")
(define-key mu4e~update-mail-mode-map (kbd "q") 'mu4e-kill-update-mail)
(defun mu4e~temp-window (buf height)
"Create a temporary window with HEIGHT at the bottom of the
frame to display buffer BUF."
(let ((win
(split-window
(frame-root-window)
(- (window-height (frame-root-window)) height))))
(set-window-buffer win buf)
(set-window-dedicated-p win t)
win))
(defun mu4e~update-sentinel-func (proc _msg)
"Sentinel function for the update process."
(when mu4e~progress-reporter
(progress-reporter-done mu4e~progress-reporter)
(setq mu4e~progress-reporter nil))
(unless mu4e-hide-index-messages
(message nil))
(if (or (not (eq (process-status proc) 'exit))
(/= (process-exit-status proc) 0))
(progn
(when mu4e-index-update-error-warning
(mu4e-message "Update process returned with non-zero exit code")
(sit-for 5))
(when mu4e-index-update-error-continue
(mu4e-update-index)))
(mu4e-update-index))
(when (buffer-live-p mu4e~update-buffer)
(unless (eq mu4e-split-view 'single-window)
(mapc #'delete-window (get-buffer-window-list mu4e~update-buffer)))
(kill-buffer mu4e~update-buffer)))
;; complicated function, as it:
;; - needs to check for errors
;; - (optionally) pop-up a window
;; - (optionally) check password requests
(defun mu4e~update-mail-and-index-real (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
RUN-IN-BACKGROUND is non-nil (or called with prefix-argument),
run in the background; otherwise, pop up a window."
(let* ((process-connection-type t)
(proc (start-process-shell-command
"mu4e-update" mu4e~update-name
mu4e-get-mail-command))
(buf (process-buffer proc))
(win (or run-in-background
(mu4e~temp-window buf mu4e~update-buffer-height))))
(setq mu4e~update-buffer buf)
(when (window-live-p win)
(with-selected-window win
;; ;;(switch-to-buffer buf)
;; (set-window-dedicated-p win t)
(erase-buffer)
(insert "\n") ;; FIXME -- needed so output starts
(mu4e~update-mail-mode)))
(setq mu4e~progress-reporter
(unless mu4e-hide-index-messages
(make-progress-reporter
(mu4e-format "Retrieving mail..."))))
(set-process-sentinel proc 'mu4e~update-sentinel-func)
;; if we're running in the foreground, handle password requests
(unless run-in-background
(process-put proc 'x-interactive (not run-in-background))
(set-process-filter proc 'mu4e~get-mail-process-filter))))
(defun mu4e-update-mail-and-index (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
run-in-background is non-nil (or called with prefix-argument), run
in the background; otherwise, pop up a window."
(interactive "P")
(unless mu4e-get-mail-command
(mu4e-error "`mu4e-get-mail-command' is not defined"))
(if (and (buffer-live-p mu4e~update-buffer)
(process-live-p (get-buffer-process mu4e~update-buffer)))
(mu4e-message "Update process is already running")
(progn
(run-hooks 'mu4e-update-pre-hook)
(mu4e~update-mail-and-index-real run-in-background))))
(defun mu4e-kill-update-mail ()
"Stop the update process by killing it."
(interactive)
(let* ((proc (and (buffer-live-p mu4e~update-buffer)
(get-buffer-process mu4e~update-buffer))))
(when (process-live-p proc)
(kill-process proc t))))
(define-obsolete-function-alias 'mu4e-interrupt-update-mail
'mu4e-kill-update-mail "1.0-alpha0")
;;; Logging / debugging
(defconst mu4e~log-max-size 1000000
"Max number of characters to keep around in the log buffer.")
(defconst mu4e~log-buffer-name "*mu4e-log*"
"*internal* Name of the logging buffer.")
(defun mu4e~get-log-buffer ()
"Fetch (and maybe create) the log buffer."
(unless (get-buffer mu4e~log-buffer-name)
(with-current-buffer (get-buffer-create mu4e~log-buffer-name)
(view-mode)
(when (fboundp 'so-long-mode)
(unless (eq major-mode 'so-long-mode)
(eval '(so-long-mode))))
(setq buffer-undo-list t)))
mu4e~log-buffer-name)
(defun mu4e-log (type frm &rest args)
"Write a message of TYPE with format-string FRM and ARGS in
*mu4e-log* buffer, if the variable mu4e-debug is non-nil. Type is
either 'to-server, 'from-server or 'misc. This function is meant for debugging."
(when mu4e-debug
(with-current-buffer (mu4e~get-log-buffer)
(let* ((inhibit-read-only t)
(tstamp (propertize (format-time-string "%Y-%m-%d %T.%3N"
(current-time))
'face 'font-lock-string-face))
(msg-face
(cl-case type
(from-server 'font-lock-type-face)
(to-server 'font-lock-function-name-face)
(misc 'font-lock-variable-name-face)
(error 'font-lock-warning-face)
(otherwise (mu4e-error "Unsupported log type"))))
(msg (propertize (apply 'format frm args) 'face msg-face)))
(save-excursion
(goto-char (point-max))
(insert tstamp
(cl-case type
(from-server " <- ")
(to-server " -> ")
(error " !! ")
(otherwise " "))
msg "\n")
;; if `mu4e-log-max-lines is specified and exceeded, clearest the oldest
;; lines
(when (> (buffer-size) mu4e~log-max-size)
(goto-char (- (buffer-size) mu4e~log-max-size))
(beginning-of-line)
(delete-region (point-min) (point))))))))
(defun mu4e-toggle-logging ()
"Toggle between enabling/disabling debug-mode (in debug-mode,
mu4e logs some of its internal workings to a log-buffer. See
`mu4e-visit-log'."
(interactive)
(mu4e-log 'misc "logging disabled")
(setq mu4e-debug (not mu4e-debug))
(mu4e-message "debug logging has been %s"
(if mu4e-debug "enabled" "disabled"))
(mu4e-log 'misc "logging enabled"))
(defun mu4e-show-log ()
"Visit the mu4e debug log."
(interactive)
(unless mu4e-debug (mu4e-toggle-logging))
(let ((buf (get-buffer mu4e~log-buffer-name)))
(unless (buffer-live-p buf)
(mu4e-warn "No debug log available"))
(switch-to-buffer buf)))
(defun mu4e-split-ranges-to-numbers (str n)
"Convert STR containing attachment numbers into a list of numbers.
STR is a string; N is the highest possible number in the list.
This includes expanding e.g. 3-5 into 3,4,5. If the letter
\"a\" ('all')) is given, that is expanded to a list with numbers [1..n]."
(let ((str-split (split-string str))
beg end list)
(dolist (elem str-split list)
;; special number "a" converts into all attachments 1-N.
(when (equal elem "a")
(setq elem (concat "1-" (int-to-string n))))
(if (string-match "\\([0-9]+\\)-\\([0-9]+\\)" elem)
;; we have found a range A-B, which needs converting
;; into the numbers A, A+1, A+2, ... B.
(progn
(setq beg (string-to-number (match-string 1 elem))
end (string-to-number (match-string 2 elem)))
(while (<= beg end)
(cl-pushnew beg list :test 'equal)
(setq beg (1+ beg))))
;; else just a number
(cl-pushnew (string-to-number elem) list :test 'equal)))
;; Check that all numbers are valid.
(mapc
(lambda (x)
(cond
((> x n)
(mu4e-warn "Attachment %d bigger than maximum (%d)" x n))
((< x 1)
(mu4e-warn "Attachment number must be greater than 0 (%d)" x))))
list)))
;;; Misc 2
(defvar mu4e-imagemagick-identify "identify"
"Name/path of the Imagemagick 'identify' program.")
(defun mu4e~image-width-scale (width height max_width max_height)
"Returns a width to use for proportional image scaling
to satisfy both MAX_WIDTH and MAX_HEIGHT restrictions."
(floor
(if (<= width max_width)
(if (<= height max_height)
width ; both width and height ok, just return width
(* (/ max_height (float height)) width)) ; height is too large, scale width by hmax/h
(if (<= height max_height)
max_width ; width is too large, return max_width as scaling
(let ((width_heightscale (* (/ max_height (float height)) width)))
(min max_width width_heightscale)))))) ; both too large, return smallest width
(defun mu4e-display-image (imgpath &optional maxwidth maxheight)
"Display image IMG at point; optionally specify MAXWIDTH and
MAXHEIGHT. Function tries to use imagemagick if available (ie.,
emacs was compiled with imagemagick support); otherwise MAXWIDTH
and MAXHEIGHT are ignored."
(let* ((have-im (and (fboundp 'imagemagick-types)
(imagemagick-types))) ;; hmm, should check for specific type
(identify (and have-im maxwidth
(executable-find mu4e-imagemagick-identify)))
(props (and identify (mapcar 'string-to-number
(split-string (shell-command-to-string
(format "%s -format '%%w %%h' %s"
identify (shell-quote-argument imgpath)))))))
(width (and props (car props)))
(height (and props (car (cdr props))))
(img (if have-im
(create-image imgpath 'imagemagick nil
:width (mu4e~image-width-scale width height maxwidth maxheight))
(create-image imgpath))))
(when img
(save-excursion
(insert "\n")
(let ((size (image-size img))) ;; inspired by gnus..
(insert-char ?\n
(max 0 (round (- (window-height) (or maxheight (cdr size)) 1) 2)))
(insert-char ?\.
(max 0 (round (- (window-width) (or maxwidth (car size))) 2)))
(insert-image img))))))
(defun mu4e-hide-other-mu4e-buffers ()
"Bury mu4e-buffers (main, headers, view) (and delete all windows
displaying it). Do _not_ bury the current buffer, though."
(interactive)
(unless (eq mu4e-split-view 'single-window)
(let ((curbuf (current-buffer)))
;; note: 'walk-windows' does not seem to work correctly when modifying
;; windows; therefore, the doloops here
(dolist (frame (frame-list))
(dolist (win (window-list frame nil))
(with-current-buffer (window-buffer win)
(unless (eq curbuf (current-buffer))
(when (member major-mode '(mu4e-headers-mode mu4e-view-mode))
(when (eq t (window-deletable-p win))
(delete-window win))))))) t)))
(defun mu4e-get-time-date (prompt)
"Determine the emacs time value for the time/date entered by user
after PROMPT. Formats are all that are accepted by
`parse-time-string'."
(let ((timestr (read-string (mu4e-format "%s" prompt))))
(apply 'encode-time (org-parse-time-string timestr))))
;;; Mu4e-org-mode
(define-derived-mode mu4e-org-mode org-mode "mu4e:org"
"Major mode for mu4e documents, derived from
`org-mode'.")
(defun mu4e-info (path)
"Show a buffer with the information (an org-file) at PATH."
(unless (file-exists-p path)
(mu4e-error "Cannot find %s" path))
(let ((curbuf (current-buffer)))
(find-file path)
(mu4e-org-mode)
(setq buffer-read-only t)
(define-key mu4e-org-mode-map (kbd "q")
`(lambda ()
(interactive)
(bury-buffer)
(switch-to-buffer ,curbuf)))))
(defun mu4e-about ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/mu4e-about.org")))
(defun mu4e-news ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/NEWS.org")))
;;; Misc 3
(defun mu4e-refresh-message (path)
"Re-parse message at PATH; if this works, we will
receive (:info add :path <path> :docid <docid>) as well as (:update
<msg-sexp>)."
(mu4e~proc-add path))
(defun mu4e~fontify-cited ()
"Colorize message content based on the citation level. This is
used in the view and compose modes."
(save-excursion
(goto-char (point-min))
(when (search-forward-regexp "^\n" nil t) ;; search the first empty line
(while (re-search-forward mu4e-cited-regexp nil t)
(let* ((level (string-width (replace-regexp-in-string
"[^>]" "" (match-string 0))))
(face (unless (zerop level)
(intern-soft (format "mu4e-cited-%d-face" level)))))
(when face
(add-text-properties (line-beginning-position 1)
(line-end-position 1) `(face ,face))))))))
(defun mu4e~fontify-signature ()
"Give the message signatures a distinctive color. This is used in
the view and compose modes and will color each signature in digest messages adhering to RFC 1153."
(let ((inhibit-read-only t))
(save-excursion
;; give the footer a different color...
(goto-char (point-min))
(while (re-search-forward "^-- *$" nil t)
(let ((p (point))
(end (or
(re-search-forward "\\(^-\\{30\\}.*$\\)" nil t) ;; 30 by RFC1153
(point-max))))
(add-text-properties p end '(face mu4e-footer-face)))))))
;;; Misc 4
(defun mu4e~quote-for-modeline (str)
"Quote a string to be used literally in the modeline. The
string will be shortened to fit if its length exceeds
`mu4e-modeline-max-width'."
(replace-regexp-in-string
"%" "%%"
(truncate-string-to-width str mu4e-modeline-max-width 0 nil t)))
(defun mu4e~active-composition-buffers ()
"Return all active mu4e composition buffers"
(let (buffers)
(save-excursion
(dolist (buffer (buffer-list t))
(set-buffer buffer)
(when (eq major-mode 'mu4e-compose-mode)
(push (buffer-name buffer) buffers))))
(nreverse buffers)))
;;
;; Loading messages
;;
(defvar mu4e-loading-mode-map nil "Keymap for *mu4e-loading* buffers.")
(unless mu4e-loading-mode-map
(setq mu4e-loading-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "n" 'ignore)
(define-key map "p" 'ignore)
(define-key map "q"
(lambda()(interactive)
(if (eq mu4e-split-view 'single-window)
'kill-buffer
'kill-buffer-and-window)))
map)))
(fset 'mu4e-loading-mode-map mu4e-loading-mode-map)
(define-derived-mode mu4e-loading-mode special-mode
"mu4e:loading"
(use-local-map mu4e-loading-mode-map)
(let ((inhibit-read-only t))
(erase-buffer)
(insert (propertize "Loading message..."
'face 'mu4e-system-face 'intangible t))))
;;
;; Bug Reference mode support
;;
;; This is Emacs 28 stuff but there is no need to guard it with some (f)boundp
;; checks (which would return nil if bug-reference.el is not loaded before
;; mu4e) since the function definition doesn't hurt and `add-hook' works fine
;; for not yet defined variables (by creating them).
(declare-function bug-reference-maybe-setup-from-mail "ext:bug-reference")
(defun mu4e-view--try-setup-bug-reference-mode ()
"Try to guess bug-reference setup from the current mu4e mail.
Looks at the maildir and the mail headers List, List-Id, Maildir,
To, From, Cc, and Subject and tries to guess suitable values for
`bug-reference-bug-regexp' and `bug-reference-url-format' by
matching the maildir name against GROUP-REGEXP and each header
value against HEADER-REGEXP in
`bug-reference-setup-from-mail-alist'."
(when (derived-mode-p 'mu4e-view-mode)
(let (header-values)
(save-excursion
(goto-char (point-min))
(dolist (field '("list" "list-id" "to" "from" "cc" "subject"))
(let ((val (mail-fetch-field field)))
(when val
(push val header-values)))))
(bug-reference-maybe-setup-from-mail
(mail-fetch-field "maildir")
header-values))))
(add-hook 'bug-reference-auto-setup-functions
#'mu4e-view--try-setup-bug-reference-mode)
;;; _
(provide 'mu4e-utils)
;;; mu4e-utils.el ends here
| true | ;;; mu4e-utils.el -- part of mu4e, the mu mail user agent -*- lexical-binding: t -*-
;; Copyright (C) 2011-2020 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; This file is not part of GNU Emacs.
;; mu4e is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; mu4e 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 mu4e. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Utility functions used in the mu4e
;;; Code:
(require 'org)
(require 'cl-lib)
(require 'cl-seq nil 'noerror)
(require 'mu4e-vars)
(require 'mu4e-message)
(require 'mu4e-meta)
(require 'mu4e-lists)
(require 'doc-view)
;; keep the byte-compiler happy
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-ping "mu4e-proc")
(declare-function mu4e~proc-contacts "mu4e-proc")
(declare-function mu4e~proc-kill "mu4e-proc")
(declare-function mu4e~proc-index "mu4e-proc")
(declare-function mu4e~proc-add "mu4e-proc")
(declare-function mu4e~proc-mkdir "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e-message-field-at-point "mu4e-proc")
(declare-function mu4e~proc-running-p "mu4e-proc")
(declare-function mu4e~main-view "mu4e-main")
(declare-function mu4e~context-autoswitch "mu4e-context")
(declare-function mu4e-context-determine "mu4e-context")
(declare-function mu4e-context-vars "mu4e-context")
(declare-function mu4e-context-current "mu4e-context")
(declare-function show-all "org")
;;; Various
(defun mu4e-copy-message-path ()
"Copy the message-path of message at point to the kill-ring."
(interactive)
(let ((path (mu4e-message-field-at-point :path)))
(kill-new path)
(mu4e-message "Saved '%s' to kill-ring" path)))
(defun mu4e-personal-address-p (addr)
"Is ADDR a personal address?
Evaluate to nil if ADDR matches any of the personal addresses.
Uses (mu4e-personal-addresses) for the addresses with both the plain
addresses and /regular expressions/."
(when addr
(seq-find
(lambda (m)
(if (string-match "/\\(.*\\)/" m)
(let ((rx (match-string 1 m))
(case-fold-search t))
(if (string-match rx addr) t nil))
(eq t (compare-strings addr nil nil m nil nil 'case-insensitive))))
(mu4e-personal-addresses))))
(define-obsolete-function-alias 'mu4e-user-mail-address-p
'mu4e-personal-address-p "1.5.5")
(defmacro with~mu4e-context-vars (context &rest body)
"Evaluate BODY, with variables let-bound for CONTEXT (if any).
`funcall'."
(declare (indent 2))
`(let* ((vars (and ,context (mu4e-context-vars ,context))))
(cl-progv ;; XXX: perhaps use eval's lexical environment instead of progv?
(mapcar (lambda(cell) (car cell)) vars)
(mapcar (lambda(cell) (cdr cell)) vars)
(eval ,@body))))
;;; Folders (1/2)
;; the standard folders can be functions too
(defun mu4e~get-folder (foldervar msg)
"Within the mu-context of MSG, get message folder FOLDERVAR.
If FOLDER is a string, return it, if it is a function, evaluate
this function with MSG as parameter (which may be `nil'), and
return the result."
(unless (member foldervar
'(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder mu4e-refile-folder))
(mu4e-error "Folder must be one of mu4e-(sent|drafts|trash|refile)-folder"))
;; get the value with the vars for the relevants context let-bound
(with~mu4e-context-vars (mu4e-context-determine msg nil)
(let* ((folder (symbol-value foldervar))
(val
(cond
((stringp folder) folder)
((functionp folder) (funcall folder msg))
(t (mu4e-error "unsupported type for %S" folder)))))
(or val (mu4e-error "%S evaluates to nil" foldervar)))))
(defun mu4e-get-drafts-folder (&optional msg)
"Get the sent folder. See `mu4e-drafts-folder'."
(mu4e~get-folder 'mu4e-drafts-folder msg))
(defun mu4e-get-refile-folder (&optional msg)
"Get the folder for refiling. See `mu4e-refile-folder'."
(mu4e~get-folder 'mu4e-refile-folder msg))
(defun mu4e-get-sent-folder (&optional msg)
"Get the sent folder. See `mu4e-sent-folder'."
(mu4e~get-folder 'mu4e-sent-folder msg))
(defun mu4e-get-trash-folder (&optional msg)
"Get the sent folder. See `mu4e-trash-folder'."
(mu4e~get-folder 'mu4e-trash-folder msg))
;;; Self-destructing files
(defun mu4e-remove-file-later (filename)
"Remove FILENAME in a few seconds."
(run-at-time "30 sec" nil
(lambda () (ignore-errors (delete-file filename)))))
(defun mu4e-make-temp-file (ext)
"Create a temporary file with extension EXT. The file will
self-destruct in a few seconds, enough to open it in another
program."
(let ((tmpfile (make-temp-file "mu4e-" nil (concat "." ext))))
(mu4e-remove-file-later tmpfile)
tmpfile))
;;; Folders (2/2)
;;
;; mu4e-attachment-dir is either a string or a function that takes a
;; filename and the mime-type as argument, either (or both) which can
;; be nil
(defun mu4e~get-attachment-dir (&optional fname mimetype)
"Get the directory for saving attachments from
`mu4e-attachment-dir' (which can be either a string or a function,
see its docstring)."
(let
((dir
(cond
((stringp mu4e-attachment-dir)
mu4e-attachment-dir)
((functionp mu4e-attachment-dir)
(funcall mu4e-attachment-dir fname mimetype))
(t
(mu4e-error "unsupported type for mu4e-attachment-dir" )))))
(if dir
(expand-file-name dir)
(mu4e-error "mu4e-attachment-dir evaluates to nil"))))
;;; Maildir (1/2)
(defun mu4e~guess-maildir (path)
"Guess the maildir for some path, or nil if cannot find it."
(let ((idx (string-match (mu4e-root-maildir) path)))
(when (and idx (zerop idx))
(replace-regexp-in-string
(mu4e-root-maildir)
""
(expand-file-name
(concat path "/../.."))))))
(defun mu4e-create-maildir-maybe (dir)
"Offer to create maildir DIR if it does not exist yet.
Return t if the dir already existed, or an attempt has been made to
create it -- we cannot be sure creation succeeded here, since this
is done asynchronously. Otherwise, return nil. NOte, DIR has to be
an absolute path."
(if (and (file-exists-p dir) (not (file-directory-p dir)))
(mu4e-error "%s exists, but is not a directory." dir))
(cond
((file-directory-p dir) t)
((yes-or-no-p (mu4e-format "%s does not exist yet. Create now?" dir))
(mu4e~proc-mkdir dir) t)
(t nil)))
;;; Messages, warnings and errors
(defun mu4e-format (frm &rest args)
"Create [mu4e]-prefixed string based on format FRM and ARGS."
(concat
"[" (propertize "mu4e" 'face 'mu4e-title-face) "] "
(apply 'format frm
(mapcar (lambda (x)
(if (stringp x)
(decode-coding-string x 'utf-8)
x))
args))))
(defun mu4e-message (frm &rest args)
"Like `message', but prefixed with mu4e.
If we're waiting for user-input or if there's some message in the
echo area, don't show anything."
(unless (or (active-minibuffer-window))
(message "%s" (apply 'mu4e-format frm args))))
(defun mu4e-index-message (frm &rest args)
"Like `mu4e-message', but specifically for
index-messages. Doesn't display anything if
`mu4e-hide-index-messages' is non-nil. "
(unless mu4e-hide-index-messages
(apply 'mu4e-message frm args)))
(defun mu4e-error (frm &rest args)
"Create [mu4e]-prefixed error based on format FRM and ARGS.
Does a local-exit and does not return, and raises a
debuggable (backtrace) error."
(mu4e-log 'error (apply 'mu4e-format frm args))
(error "%s" (apply 'mu4e-format frm args)))
;; the user-error function is only available in emacs-trunk
(unless (fboundp 'user-error)
(defalias 'user-error 'error))
(defun mu4e-warn (frm &rest args)
"Create [mu4e]-prefixed warning based on format FRM and ARGS.
Does a local-exit and does not return. In emacs versions below
24.2, the functions is the same as `mu4e-error'."
(mu4e-log 'error (apply 'mu4e-format frm args))
(user-error "%s" (apply 'mu4e-format frm args)))
;;; Reading user input
(defun mu4e~read-char-choice (prompt choices)
"Read and return one of CHOICES, prompting for PROMPT.
Any input that is not one of CHOICES is ignored. This mu4e's
version of `read-char-choice', that becomes case-insentive after
trying an exact match."
(let ((choice) (chosen) (inhibit-quit nil))
(while (not chosen)
(message nil);; this seems needed...
(setq choice (read-char-exclusive prompt))
(if (eq choice 27) (keyboard-quit)) ;; quit if ESC is pressed
(setq chosen (or (member choice choices)
(member (downcase choice) choices)
(member (upcase choice) choices))))
(car chosen)))
(defun mu4e-read-option (prompt options)
"Ask user for an option from a list on the input area.
PROMPT describes a multiple-choice question to the user.
OPTIONS describe the options, and is a list of cells describing
particular options. Cells have the following structure:
(OPTIONSTRING . RESULT)
where OPTIONSTRING is a non-empty string describing the
option. The first character of OPTIONSTRING is used as the
shortcut, and obviously all shortcuts must be different, so you
can prefix the string with an uniquifying character.
The options are provided as a list for the user to choose from;
user can then choose by typing CHAR. Example:
(mu4e-read-option \"Choose an animal: \"
'((\"Monkey\" . monkey) (\"Gnu\" . gnu) (\"xMoose\" . moose)))
User now will be presented with a list: \"Choose an animal:
[M]onkey, [G]nu, [x]Moose\".
Function will return the cdr of the list element."
(let* ((prompt (mu4e-format "%s" prompt))
(optionsstr
(mapconcat
(lambda (option)
;; try to detect old-style options, and warn
(when (characterp (car-safe (cdr-safe option)))
(mu4e-error
(concat "Please use the new format for options/actions; "
"see the manual")))
(let ((kar (substring (car option) 0 1)))
(concat
"[" (propertize kar 'face 'mu4e-highlight-face) "]"
(substring (car option) 1))))
options ", "))
(response
(mu4e~read-char-choice
(concat prompt optionsstr
" [" (propertize "C-g" 'face 'mu4e-highlight-face)
" to cancel]")
;; the allowable chars
(cl-map 'list (lambda(elm) (string-to-char (car elm))) options)))
(chosen
(cl-find-if
(lambda (option) (eq response (string-to-char (car option))))
options)))
(if chosen
(cdr chosen)
(mu4e-warn "Unknown shortcut '%c'" response))))
;;; Maildir (1/2)
(defun mu4e~get-maildirs-1 (path mdir)
"Get maildirs under path, recursively, as a list of relative paths."
(let ((dirs)
(dentries
(ignore-errors
(directory-files-and-attributes
(concat path mdir) nil
"^[^.]\\|\\.[^.][^.]" t))))
(dolist (dentry dentries)
(when (and (booleanp (cadr dentry)) (cadr dentry))
(if (file-accessible-directory-p
(concat (mu4e-root-maildir) "/" mdir "/" (car dentry) "/cur"))
(setq dirs (cons (concat mdir (car dentry)) dirs)))
(unless (member (car dentry) '("cur" "new" "tmp"))
(setq dirs (append dirs (mu4e~get-maildirs-1 path
(concat mdir (car dentry) "/")))))))
dirs))
(defvar mu4e-cache-maildir-list nil
"Whether to cache the list of maildirs; set it to t if you find
that generating the list on the fly is too slow. If you do, you
can set `(mu4e-root-maildir)-list' to nil to force regenerating the
cache the next time `mu4e-get-maildirs' gets called.")
(defvar mu4e-maildir-list nil
"Cached list of maildirs.")
(defun mu4e-get-maildirs ()
"Get maildirs under `mu4e-maildir', recursively, as a list of
relative paths (ie., /archive, /sent etc.). Most of the work is
done in `mu4e~get-maildirs-1'. Note, these results are /cached/
if `mu4e-cache-maildir-list' is customized to non-nil. In that case,
the list of maildirs will not change until you restart mu4e."
(unless (and mu4e-maildir-list mu4e-cache-maildir-list)
(setq mu4e-maildir-list
(sort
(append
(when (file-accessible-directory-p
(concat (mu4e-root-maildir) "/cur")) '("/"))
(mu4e~get-maildirs-1 (mu4e-root-maildir) "/"))
(lambda (s1 s2) (string< (downcase s1) (downcase s2))))))
mu4e-maildir-list)
(defun mu4e-ask-maildir (prompt)
"Ask the user for a shortcut (using PROMPT) as per
(mu4e-maildir-shortcuts), then return the corresponding folder
name. If the special shortcut 'o' (for _o_ther) is used, or if
`(mu4e-maildir-shortcuts)' evaluates to nil, let user choose from
all maildirs under `mu4e-maildir'."
(let ((prompt (mu4e-format "%s" prompt)))
(if (not (mu4e-maildir-shortcuts))
(substring-no-properties
(funcall mu4e-completing-read-function prompt (mu4e-get-maildirs)))
(let* ((mlist (append (mu4e-maildir-shortcuts)
'((:maildir "ther" :key ?o))))
(fnames
(mapconcat
(lambda (item)
(concat
"["
(propertize (make-string 1 (plist-get item :key))
'face 'mu4e-highlight-face)
"]"
(plist-get item :maildir)))
mlist ", "))
(kar (read-char (concat prompt fnames))))
(if (member kar '(?/ ?o)) ;; user chose 'other'?
(substring-no-properties
(funcall mu4e-completing-read-function prompt
(mu4e-get-maildirs) nil nil "/"))
(or (plist-get
(cl-find-if (lambda (item) (= kar (plist-get item :key)))
(mu4e-maildir-shortcuts)) :maildir)
(mu4e-warn "Unknown shortcut '%c'" kar)))))))
(defun mu4e-ask-maildir-check-exists (prompt)
"Like `mu4e-ask-maildir', but check for existence of the maildir,
and offer to create it if it does not exist yet."
(let* ((mdir (mu4e-ask-maildir prompt))
(fullpath (concat (mu4e-root-maildir) mdir)))
(unless (file-directory-p fullpath)
(and (yes-or-no-p
(mu4e-format "%s does not exist. Create now?" fullpath))
(mu4e~proc-mkdir fullpath)))
mdir))
;;; Bookmarks
(defun mu4e-ask-bookmark (prompt)
"Ask the user for a bookmark (using PROMPT) as defined in
`mu4e-bookmarks', then return the corresponding query."
(unless (mu4e-bookmarks) (mu4e-error "No bookmarks defined"))
(let* ((prompt (mu4e-format "%s" prompt))
(bmarks
(mapconcat
(lambda (bm)
(concat
"[" (propertize (make-string 1 (plist-get bm :key))
'face 'mu4e-highlight-face)
"]"
(plist-get bm :name))) (mu4e-bookmarks) ", "))
(kar (read-char (concat prompt bmarks))))
(mu4e-get-bookmark-query kar)))
(defun mu4e-get-bookmark-query (kar)
"Get the corresponding bookmarked query for shortcut character
KAR, or raise an error if none is found."
(let* ((chosen-bm
(or (cl-find-if
(lambda (bm)
(= kar (plist-get bm :key)))
(mu4e-bookmarks))
(mu4e-warn "Unknown shortcut '%c'" kar)))
(expr (plist-get chosen-bm :query))
(expr (if (not (functionp expr)) expr
(funcall expr)))
(query (eval expr)))
(if (stringp query)
query
(mu4e-warn "Expression must evaluate to query string ('%S')" expr))))
(defun mu4e-bookmark-define (query name key)
"Define a bookmark for QUERY with name NAME and
shortcut-character KEY in the list of `mu4e-bookmarks'. This
replaces any existing bookmark with KEY."
(setq mu4e-bookmarks
(cl-remove-if
(lambda (bm)
(= (plist-get bm :key) key))
(mu4e-bookmarks)))
(cl-pushnew `(:name ,name
:query ,query
:key ,key)
mu4e-bookmarks :test 'equal))
;;; Converting flags->string and vice-versa
(defun mu4e~flags-to-string-raw (flags)
"Convert a list of flags into a string as seen in Maildir
message files; flags are symbols draft, flagged, new, passed,
replied, seen, trashed and the string is the concatenation of the
uppercased first letters of these flags, as per [1]. Other flags
than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html"
(when flags
(let ((kar (cl-case (car flags)
('draft ?D)
('flagged ?F)
('new ?N)
('passed ?P)
('replied ?R)
('seen ?S)
('trashed ?T)
('attach ?a)
('encrypted ?x)
('signed ?s)
('unread ?u))))
(concat (and kar (string kar))
(mu4e~flags-to-string-raw (cdr flags))))))
(defun mu4e-flags-to-string (flags)
"Remove duplicates and sort the output of `mu4e~flags-to-string-raw'."
(concat
(sort (cl-remove-duplicates
(append (mu4e~flags-to-string-raw flags) nil)) '>)))
(defun mu4e~string-to-flags-1 (str)
"Convert a string with message flags as seen in Maildir
messages into a list of flags in; flags are symbols draft,
flagged, new, passed, replied, seen, trashed and the string is
the concatenation of the uppercased first letters of these flags,
as per [1]. Other letters than the ones listed here are ignored.
Also see `mu4e-flags-to-string'.
\[1\]: http://cr.yp.to/proto/maildir.html."
(when (/= 0 (length str))
(let ((flag
(cl-case (string-to-char str)
(?D 'draft)
(?F 'flagged)
(?P 'passed)
(?R 'replied)
(?S 'seen)
(?T 'trashed))))
(append (when flag (list flag))
(mu4e~string-to-flags-1 (substring str 1))))))
(defun mu4e-string-to-flags (str)
"Convert a string with message flags as seen in Maildir messages
into a list of flags in; flags are symbols draft, flagged, new,
passed, replied, seen, trashed and the string is the concatenation
of the uppercased first letters of these flags, as per [1]. Other
letters than the ones listed here are ignored. Also see
`mu4e-flags-to-string'. \[1\]:
http://cr.yp.to/proto/maildir.html "
;; "Remove duplicates from the output of `mu4e~string-to-flags-1'"
(cl-remove-duplicates (mu4e~string-to-flags-1 str)))
;;; Various
(defun mu4e-display-size (size)
"Get a string representation of SIZE (in bytes)."
(cond
((>= size 1000000) (format "%2.1fM" (/ size 1000000.0)))
((and (>= size 1000) (< size 1000000))
(format "%2.1fK" (/ size 1000.0)))
((< size 1000) (format "%d" size))
(t (propertize "?" 'face 'mu4e-system-face))))
(defun mu4e-display-manual ()
"Display the mu4e manual page for the current mode.
Or go to the top level if there is none."
(interactive)
(info (cl-case major-mode
('mu4e-main-mode "(mu4e)Main view")
('mu4e-headers-mode "(mu4e)Headers view")
('mu4e-view-mode "(mu4e)Message view")
(t "mu4e"))))
;;; Misc
(defun mu4e-last-query ()
"Get the most recent query or nil if there is none."
(when (buffer-live-p (mu4e-get-headers-buffer))
(with-current-buffer (mu4e-get-headers-buffer)
mu4e~headers-last-query)))
(defvar gnus-article-buffer) ;; Fix byte-compiler warning.
(defun mu4e-get-view-buffer ()
"Get the view buffer, if any."
(get-buffer
(if mu4e-view-use-old
mu4e~view-buffer-name
gnus-article-buffer)))
(defun mu4e-get-headers-buffer ()
(get-buffer mu4e~headers-buffer-name))
(defun mu4e-select-other-view ()
"When the headers view is selected, select the message view (if
that has a live window), and vice versa."
(interactive)
(let* ((other-buf
(cond
((eq major-mode 'mu4e-headers-mode)
(mu4e-get-view-buffer))
((eq major-mode 'mu4e-view-mode)
(mu4e-get-headers-buffer))))
(other-win (and other-buf (get-buffer-window other-buf))))
(if (window-live-p other-win)
(select-window other-win)
(mu4e-message "No window to switch to"))))
(defconst mu4e-output-buffer-name "*mu4e-output*"
"*internal* Name of the mu4e output buffer.")
(defun mu4e-process-file-through-pipe (path pipecmd)
"Process file at PATH through a pipe with PIPECMD."
(let ((buf (get-buffer-create mu4e-output-buffer-name)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(call-process-shell-command pipecmd path t t)
(view-mode)))
(switch-to-buffer buf)))
(defvar mu4e~lists-hash nil
"Hashtable of mailing-list-id => shortname, based on
`mu4e~mailing-lists' and `mu4e-user-mailing-lists'.")
(defun mu4e-get-mailing-list-shortname (list-id)
"Get the shortname for a mailing-list with list-id LIST-ID. based
on `mu4e~mailing-lists', `mu4e-user-mailing-lists', and
`mu4e-mailing-list-patterns'."
(unless mu4e~lists-hash
(setq mu4e~lists-hash (make-hash-table :test 'equal))
(dolist (cell mu4e~mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash))
(dolist (cell mu4e-user-mailing-lists)
(puthash (car cell) (cdr cell) mu4e~lists-hash)))
(or
(gethash list-id mu4e~lists-hash)
(and (boundp 'mu4e-mailing-list-patterns)
(cl-member-if
(lambda (pattern)
(string-match pattern list-id))
mu4e-mailing-list-patterns)
(match-string 1 list-id))
;; if it's not in the db, take the part until the first dot if there is one;
;; otherwise just return the whole thing
(if (string-match "\\([^.]*\\)\\." list-id)
(match-string 1 list-id)
list-id)))
(defvar mu4e-index-updated-hook nil
"Hook run when the indexing process had one or more updated messages.
This can be used as a simple way to invoke some action when new
messages appear, but note that an update in the index does not
necessarily mean a new message.")
(defvar mu4e-message-changed-hook nil
"Hook run when there is a message changed in db. For new
messages, it depends on `mu4e-index-updated-hook'. This can be
used as a simple way to invoke some action when a message
changed.")
(make-obsolete-variable 'mu4e-msg-changed-hook
'mu4e-message-changed-hook "0.9.19")
(defvar mu4e~contacts-tstamp "0"
"Timestamp for the most recent contacts update." )
;;; Some handler functions for server messages
(defun mu4e-info-handler (info)
"Handler function for (:info ...) sexps received from the server
process."
(let* ((type (plist-get info :info))
(processed (plist-get info :processed))
(updated (plist-get info :updated))
(cleaned-up (plist-get info :cleaned-up))
(mainbuf (get-buffer mu4e-main-buffer-name)))
(cond
((eq type 'add) t) ;; do nothing
((eq type 'index)
(if (eq (plist-get info :status) 'running)
(mu4e-index-message
"Indexing... processed %d, updated %d" processed updated)
(progn
(mu4e-index-message
"%s completed; processed %d, updated %d, cleaned-up %d"
(if mu4e-index-lazy-check "Lazy indexing" "Indexing")
processed updated cleaned-up)
;; call the updated hook if anything changed.
(unless (zerop (+ updated cleaned-up))
(run-hooks 'mu4e-index-updated-hook))
(unless (and (not (string= mu4e~contacts-tstamp "0"))
(zerop (plist-get info :updated)))
(mu4e~request-contacts-maybe))
(when (and (buffer-live-p mainbuf) (get-buffer-window mainbuf))
(save-window-excursion
(select-window (get-buffer-window mainbuf))
(mu4e~main-view 'refresh))))))
((plist-get info :message)
(mu4e-index-message "%s" (plist-get info :message))))))
(defun mu4e-error-handler (errcode errmsg)
"Handler function for showing an error."
;; don't use mu4e-error here; it's running in the process filter context
(cl-case errcode
(4 (user-error "No matches for this search query."))
(110 (display-warning 'mu4e errmsg :error)) ;; schema version.
(t (error "Error %d: %s" errcode errmsg))))
;;; Contacts
(defun mu4e~update-contacts (contacts &optional tstamp)
"Receive a sorted list of CONTACTS.
Each of the contacts has the form
(FULL_EMAIL_ADDRESS . RANK) and fill `mu4e~contacts-hash' with
it, with each contact mapped to an integer for their ranking.
This is used by the completion function in mu4e-compose."
;; We have our nicely sorted list, map them to a list
;; of increasing integers. We use that map in the composer
;; to sort them there. It would have been so much easier if emacs
;; allowed us to use the sorted-list as-is, but no such luck.
(let ((n 0))
(unless mu4e~contacts-hash
(setq mu4e~contacts-hash (make-hash-table :test 'equal :weakness nil
:size (length contacts))))
(dolist (contact contacts)
(cl-incf n)
(let* ((address (plist-get contact :address))
(address
(if (functionp mu4e-contact-process-function)
(funcall mu4e-contact-process-function address)
address)))
(when address ;; note the explicit deccode; the strings we get are utf-8,
;; but emacs doesn't know yet.
(puthash (decode-coding-string address 'utf-8)
(plist-get contact :rank) mu4e~contacts-hash))))
(setq mu4e~contacts-tstamp (or tstamp "0"))
(unless (zerop n)
(mu4e-index-message "Contacts updated: %d; total %d"
n (hash-table-count mu4e~contacts-hash)))))
(defun mu4e-contacts-info ()
"Display information about the cache used for contacts
completion; for testing/debugging."
(interactive)
(with-current-buffer (get-buffer-create "*mu4e-contacts-info*")
(erase-buffer)
(insert (format "complete addresses: %s\n"
(if mu4e-compose-complete-addresses "yes" "no")))
(insert (format "only personal addresses: %s\n"
(if mu4e-compose-complete-only-personal "yes" "no")))
(insert (format "only addresses seen after: %s\n"
(or mu4e-compose-complete-only-after "no restrictions")))
(when mu4e~contacts-hash
(insert (format "number of contacts cached: %d\n\n"
(hash-table-count mu4e~contacts-hash)))
(let ((contacts))
(maphash (lambda (addr rank)
(setq contacts (cons (cons rank addr) contacts)))
mu4e~contacts-hash)
(setq contacts (sort contacts
(lambda(cell1 cell2) (< (car cell1) (car cell2)))))
(dolist (contact contacts)
(insert (format "%s\n" (cdr contact))))))
(pop-to-buffer "*mu4e-contacts-info*")))
(defun mu4e~check-requirements ()
"Check for the settings required for running mu4e."
(unless (>= emacs-major-version 25)
(mu4e-error "Emacs >= 25.x is required for mu4e"))
(when mu4e~server-props
(unless (string= (mu4e-server-version) mu4e-mu-version)
(mu4e-error "mu server has version %s, but we need %s"
(mu4e-server-version) mu4e-mu-version)))
(unless (and mu4e-mu-binary (file-executable-p mu4e-mu-binary))
(mu4e-error "Please set `mu4e-mu-binary' to the full path to the mu
binary."))
(dolist (var '(mu4e-sent-folder mu4e-drafts-folder
mu4e-trash-folder))
(unless (and (boundp var) (symbol-value var))
(mu4e-error "Please set %S" var))
(unless (functionp (symbol-value var)) ;; functions are okay, too
(let* ((dir (symbol-value var))
(path (concat (mu4e-root-maildir) dir)))
(unless (string= (substring dir 0 1) "/")
(mu4e-error "%S must start with a '/'" dir))
(unless (mu4e-create-maildir-maybe path)
(mu4e-error "%s (%S) does not exist" path var))))))
(defun mu4e-running-p ()
"Whether mu4e is running.
Checks whether the server process is live."
(mu4e~proc-running-p))
;;; Starting / getting mail / updating the index
(defvar mu4e~update-timer nil
"The mu4e update timer.")
(defconst mu4e~update-name " *mu4e-update*"
"Name of the process and buffer to update mail.")
(defconst mu4e~update-buffer-height 8
"Height of the mu4e message retrieval/update buffer.")
(defvar mu4e~get-mail-ask-password "mu4e get-mail: Enter password: "
"Query string for `mu4e-get-mail-command' password.")
(defvar mu4e~get-mail-password-regexp "^Remote: Enter password: $"
"Regexp to match a password query in the `mu4e-get-mail-command' output.")
(defun mu4e~request-contacts-maybe ()
"If `mu4e-compose-complete-addresses' is non-nil, get/update
the list of contacts we use for autocompletion; otherwise, do
nothing."
(when mu4e-compose-complete-addresses
(setq mu4e-contacts-func 'mu4e~update-contacts)
(mu4e~proc-contacts
mu4e-compose-complete-only-personal
mu4e-compose-complete-only-after
mu4e~contacts-tstamp)))
(defun mu4e~pong-handler (data func)
"Handle 'pong' responses from the mu server."
(setq mu4e~server-props (plist-get data :props)) ;; save info from the server
(let ((doccount (plist-get mu4e~server-props :doccount)))
(mu4e~check-requirements)
(when func (funcall func))
(when (zerop doccount)
(mu4e-message "Store is empty; (re)indexing. This may take a while.") ;
(mu4e-update-index))
(when (and mu4e-update-interval (null mu4e~update-timer))
(setq mu4e~update-timer
(run-at-time 0 mu4e-update-interval
(lambda () (mu4e-update-mail-and-index
mu4e-index-update-in-background)))))))
(defun mu4e-last-query-results ()
"Get the results (counts) of the last cached queries.
The cached queries are the bookmark / maildir queries that are
used to populated the read/unread counts in the main view. They
are refreshed when calling `(mu4e)', i.e., when going to the main
view.
The results are a list of elements of the form
(:query \"query string\"
:count <total number matching count>
:unread <number of unread messages in count>)"
(plist-get mu4e~server-props :queries))
(defun mu4e-last-query-result (query)
"Get the last result for some cached query, as per
`mu4e-bookmark-query-results' or nil if not found."
(cl-find-if
(lambda (elm) (string= (plist-get elm :query) query))
(mu4e-last-query-results)))
(defun mu4e~start (&optional func)
"If `mu4e-contexts' have been defined, but we don't have a
context yet, switch to the matching one, or none matches, the
first. If mu4e is already running, execute function FUNC (if
non-nil). Otherwise, check various requireme`'nts, then start mu4e.
When successful, call FUNC (if non-nil) afterwards."
(unless (mu4e-context-current)
(mu4e~context-autoswitch nil mu4e-context-policy))
(setq mu4e-pong-func (lambda (info) (mu4e~pong-handler info func)))
(mu4e~proc-ping
(mapcar ;; send it a list of queries we'd like to see read/unread info for
(lambda (bm)
(funcall (or mu4e-query-rewrite-function #'identity)
(plist-get bm :query)))
;; exclude bookmarks that are not strings, and with certain flags
(seq-filter (lambda (bm)
(and (stringp (plist-get bm :query))
(not (or (plist-get bm :hide) (plist-get bm :hide-unread)))))
(append (mu4e-bookmarks)
(mu4e~maildirs-with-query)))))
;; maybe request the list of contacts, automatically refreshed after
;; reindexing
(unless mu4e~contacts-hash (mu4e~request-contacts-maybe)))
(defun mu4e-clear-caches ()
"Clear any cached resources."
(setq
mu4e-maildir-list nil
mu4e~contacts-hash nil
mu4e~contacts-tstamp "0"))
(defun mu4e~stop ()
"Stop the mu4e session."
(when mu4e~update-timer
(cancel-timer mu4e~update-timer)
(setq mu4e~update-timer nil))
(mu4e-clear-caches)
(mu4e~proc-kill)
;; kill all mu4e buffers
(mapc
(lambda (buf)
;; When using the Gnus-based viewer, the view buffer has the
;; kill-buffer-hook function mu4e~view-kill-buffer-hook-fn which kills the
;; mm-* buffers created by Gnus' article mode. Those have been returned by
;; `buffer-list' but might already be deleted in case the view buffer has
;; been killed first. So we need a `buffer-live-p' check here.
(when (buffer-live-p buf)
(with-current-buffer buf
(when (member major-mode
'(mu4e-headers-mode mu4e-view-mode mu4e-main-mode))
(kill-buffer)))))
(buffer-list)))
(defun mu4e~maildirs-with-query ()
"Return a copy of `mu4e-maildirs-shortcuts' with :query populated.
This is meant to be the exact same data structure as
`mu4e-bookmarks'."
(cl-mapcar
(lambda (m)
(append
;; we want to change the :maildir key to :name, and add a :query key
(list :name (plist-get m :maildir)
:query (format "maildir:\"%s\"" (plist-get m :maildir)))
;; next we want to append any other keys to our previous list (e.g. :hide,
;; :key, etc) but skipping :maildir (since it's renamed to :name)
(cl-loop for (key value) on m by 'cddr
when (not (equal key :maildir))
append (list key value))))
(mu4e-maildir-shortcuts)))
(defun mu4e~longest-of-maildirs-and-bookmarks ()
"Return the length of longest name of bookmarks and maildirs."
(cl-loop for b in (append (mu4e-bookmarks)
(mu4e~maildirs-with-query))
maximize (string-width (plist-get b :name))))
;;; Indexing & Updating
(defvar mu4e~progress-reporter nil
"Internal, the progress reporter object.")
(defun mu4e~get-mail-process-filter (proc msg)
"Filter the output of `mu4e-get-mail-command'.
Currently the filter only checks if the command asks for a password
by matching the output against `mu4e~get-mail-password-regexp'.
The messages are inserted into the process buffer.
Also scrolls to the final line, and update the progress throbber."
(when mu4e~progress-reporter
(progress-reporter-update mu4e~progress-reporter))
(when (string-match mu4e~get-mail-password-regexp msg)
(if (process-get proc 'x-interactive)
(process-send-string proc
(concat (read-passwd mu4e~get-mail-ask-password)
"\n"))
;; TODO kill process?
(mu4e-error "Unrecognized password request")))
(when (process-buffer proc)
(let ((inhibit-read-only t)
(procwin (get-buffer-window (process-buffer proc))))
;; Insert at end of buffer. Leave point alone.
(with-current-buffer (process-buffer proc)
(goto-char (point-max))
(if (string-match ".*\r\\(.*\\)" msg)
(progn
;; kill even with \r
(end-of-line)
(let ((end (point)))
(beginning-of-line)
(delete-region (point) end))
(insert (match-string 1 msg)))
(insert msg)))
;; Auto-scroll unless user is interacting with the window.
(when (and (window-live-p procwin)
(not (eq (selected-window) procwin)))
(with-selected-window procwin
(goto-char (point-max)))))))
(defun mu4e-update-index ()
"Update the mu4e index."
(interactive)
(mu4e~proc-index mu4e-index-cleanup mu4e-index-lazy-check))
(defun mu4e-update-index-nonlazy ()
"Update the mu4e index non-lazily.
This is just a convenience wrapper for indexing the non-lazy way
if you otherwise want to use `mu4e-index-lazy-check'."
(interactive)
(let ((mu4e-index-cleanup t) (mu4e-index-lazy-check nil))
(mu4e-update-index)))
(defvar mu4e~update-buffer nil
"Internal, store the buffer of the update process when
updating.")
(define-derived-mode mu4e~update-mail-mode special-mode "mu4e:update"
"Major mode used for retrieving new e-mail messages in `mu4e'.")
(define-key mu4e~update-mail-mode-map (kbd "q") 'mu4e-kill-update-mail)
(defun mu4e~temp-window (buf height)
"Create a temporary window with HEIGHT at the bottom of the
frame to display buffer BUF."
(let ((win
(split-window
(frame-root-window)
(- (window-height (frame-root-window)) height))))
(set-window-buffer win buf)
(set-window-dedicated-p win t)
win))
(defun mu4e~update-sentinel-func (proc _msg)
"Sentinel function for the update process."
(when mu4e~progress-reporter
(progress-reporter-done mu4e~progress-reporter)
(setq mu4e~progress-reporter nil))
(unless mu4e-hide-index-messages
(message nil))
(if (or (not (eq (process-status proc) 'exit))
(/= (process-exit-status proc) 0))
(progn
(when mu4e-index-update-error-warning
(mu4e-message "Update process returned with non-zero exit code")
(sit-for 5))
(when mu4e-index-update-error-continue
(mu4e-update-index)))
(mu4e-update-index))
(when (buffer-live-p mu4e~update-buffer)
(unless (eq mu4e-split-view 'single-window)
(mapc #'delete-window (get-buffer-window-list mu4e~update-buffer)))
(kill-buffer mu4e~update-buffer)))
;; complicated function, as it:
;; - needs to check for errors
;; - (optionally) pop-up a window
;; - (optionally) check password requests
(defun mu4e~update-mail-and-index-real (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
RUN-IN-BACKGROUND is non-nil (or called with prefix-argument),
run in the background; otherwise, pop up a window."
(let* ((process-connection-type t)
(proc (start-process-shell-command
"mu4e-update" mu4e~update-name
mu4e-get-mail-command))
(buf (process-buffer proc))
(win (or run-in-background
(mu4e~temp-window buf mu4e~update-buffer-height))))
(setq mu4e~update-buffer buf)
(when (window-live-p win)
(with-selected-window win
;; ;;(switch-to-buffer buf)
;; (set-window-dedicated-p win t)
(erase-buffer)
(insert "\n") ;; FIXME -- needed so output starts
(mu4e~update-mail-mode)))
(setq mu4e~progress-reporter
(unless mu4e-hide-index-messages
(make-progress-reporter
(mu4e-format "Retrieving mail..."))))
(set-process-sentinel proc 'mu4e~update-sentinel-func)
;; if we're running in the foreground, handle password requests
(unless run-in-background
(process-put proc 'x-interactive (not run-in-background))
(set-process-filter proc 'mu4e~get-mail-process-filter))))
(defun mu4e-update-mail-and-index (run-in-background)
"Get a new mail by running `mu4e-get-mail-command'. If
run-in-background is non-nil (or called with prefix-argument), run
in the background; otherwise, pop up a window."
(interactive "P")
(unless mu4e-get-mail-command
(mu4e-error "`mu4e-get-mail-command' is not defined"))
(if (and (buffer-live-p mu4e~update-buffer)
(process-live-p (get-buffer-process mu4e~update-buffer)))
(mu4e-message "Update process is already running")
(progn
(run-hooks 'mu4e-update-pre-hook)
(mu4e~update-mail-and-index-real run-in-background))))
(defun mu4e-kill-update-mail ()
"Stop the update process by killing it."
(interactive)
(let* ((proc (and (buffer-live-p mu4e~update-buffer)
(get-buffer-process mu4e~update-buffer))))
(when (process-live-p proc)
(kill-process proc t))))
(define-obsolete-function-alias 'mu4e-interrupt-update-mail
'mu4e-kill-update-mail "1.0-alpha0")
;;; Logging / debugging
(defconst mu4e~log-max-size 1000000
"Max number of characters to keep around in the log buffer.")
(defconst mu4e~log-buffer-name "*mu4e-log*"
"*internal* Name of the logging buffer.")
(defun mu4e~get-log-buffer ()
"Fetch (and maybe create) the log buffer."
(unless (get-buffer mu4e~log-buffer-name)
(with-current-buffer (get-buffer-create mu4e~log-buffer-name)
(view-mode)
(when (fboundp 'so-long-mode)
(unless (eq major-mode 'so-long-mode)
(eval '(so-long-mode))))
(setq buffer-undo-list t)))
mu4e~log-buffer-name)
(defun mu4e-log (type frm &rest args)
"Write a message of TYPE with format-string FRM and ARGS in
*mu4e-log* buffer, if the variable mu4e-debug is non-nil. Type is
either 'to-server, 'from-server or 'misc. This function is meant for debugging."
(when mu4e-debug
(with-current-buffer (mu4e~get-log-buffer)
(let* ((inhibit-read-only t)
(tstamp (propertize (format-time-string "%Y-%m-%d %T.%3N"
(current-time))
'face 'font-lock-string-face))
(msg-face
(cl-case type
(from-server 'font-lock-type-face)
(to-server 'font-lock-function-name-face)
(misc 'font-lock-variable-name-face)
(error 'font-lock-warning-face)
(otherwise (mu4e-error "Unsupported log type"))))
(msg (propertize (apply 'format frm args) 'face msg-face)))
(save-excursion
(goto-char (point-max))
(insert tstamp
(cl-case type
(from-server " <- ")
(to-server " -> ")
(error " !! ")
(otherwise " "))
msg "\n")
;; if `mu4e-log-max-lines is specified and exceeded, clearest the oldest
;; lines
(when (> (buffer-size) mu4e~log-max-size)
(goto-char (- (buffer-size) mu4e~log-max-size))
(beginning-of-line)
(delete-region (point-min) (point))))))))
(defun mu4e-toggle-logging ()
"Toggle between enabling/disabling debug-mode (in debug-mode,
mu4e logs some of its internal workings to a log-buffer. See
`mu4e-visit-log'."
(interactive)
(mu4e-log 'misc "logging disabled")
(setq mu4e-debug (not mu4e-debug))
(mu4e-message "debug logging has been %s"
(if mu4e-debug "enabled" "disabled"))
(mu4e-log 'misc "logging enabled"))
(defun mu4e-show-log ()
"Visit the mu4e debug log."
(interactive)
(unless mu4e-debug (mu4e-toggle-logging))
(let ((buf (get-buffer mu4e~log-buffer-name)))
(unless (buffer-live-p buf)
(mu4e-warn "No debug log available"))
(switch-to-buffer buf)))
(defun mu4e-split-ranges-to-numbers (str n)
"Convert STR containing attachment numbers into a list of numbers.
STR is a string; N is the highest possible number in the list.
This includes expanding e.g. 3-5 into 3,4,5. If the letter
\"a\" ('all')) is given, that is expanded to a list with numbers [1..n]."
(let ((str-split (split-string str))
beg end list)
(dolist (elem str-split list)
;; special number "a" converts into all attachments 1-N.
(when (equal elem "a")
(setq elem (concat "1-" (int-to-string n))))
(if (string-match "\\([0-9]+\\)-\\([0-9]+\\)" elem)
;; we have found a range A-B, which needs converting
;; into the numbers A, A+1, A+2, ... B.
(progn
(setq beg (string-to-number (match-string 1 elem))
end (string-to-number (match-string 2 elem)))
(while (<= beg end)
(cl-pushnew beg list :test 'equal)
(setq beg (1+ beg))))
;; else just a number
(cl-pushnew (string-to-number elem) list :test 'equal)))
;; Check that all numbers are valid.
(mapc
(lambda (x)
(cond
((> x n)
(mu4e-warn "Attachment %d bigger than maximum (%d)" x n))
((< x 1)
(mu4e-warn "Attachment number must be greater than 0 (%d)" x))))
list)))
;;; Misc 2
(defvar mu4e-imagemagick-identify "identify"
"Name/path of the Imagemagick 'identify' program.")
(defun mu4e~image-width-scale (width height max_width max_height)
"Returns a width to use for proportional image scaling
to satisfy both MAX_WIDTH and MAX_HEIGHT restrictions."
(floor
(if (<= width max_width)
(if (<= height max_height)
width ; both width and height ok, just return width
(* (/ max_height (float height)) width)) ; height is too large, scale width by hmax/h
(if (<= height max_height)
max_width ; width is too large, return max_width as scaling
(let ((width_heightscale (* (/ max_height (float height)) width)))
(min max_width width_heightscale)))))) ; both too large, return smallest width
(defun mu4e-display-image (imgpath &optional maxwidth maxheight)
"Display image IMG at point; optionally specify MAXWIDTH and
MAXHEIGHT. Function tries to use imagemagick if available (ie.,
emacs was compiled with imagemagick support); otherwise MAXWIDTH
and MAXHEIGHT are ignored."
(let* ((have-im (and (fboundp 'imagemagick-types)
(imagemagick-types))) ;; hmm, should check for specific type
(identify (and have-im maxwidth
(executable-find mu4e-imagemagick-identify)))
(props (and identify (mapcar 'string-to-number
(split-string (shell-command-to-string
(format "%s -format '%%w %%h' %s"
identify (shell-quote-argument imgpath)))))))
(width (and props (car props)))
(height (and props (car (cdr props))))
(img (if have-im
(create-image imgpath 'imagemagick nil
:width (mu4e~image-width-scale width height maxwidth maxheight))
(create-image imgpath))))
(when img
(save-excursion
(insert "\n")
(let ((size (image-size img))) ;; inspired by gnus..
(insert-char ?\n
(max 0 (round (- (window-height) (or maxheight (cdr size)) 1) 2)))
(insert-char ?\.
(max 0 (round (- (window-width) (or maxwidth (car size))) 2)))
(insert-image img))))))
(defun mu4e-hide-other-mu4e-buffers ()
"Bury mu4e-buffers (main, headers, view) (and delete all windows
displaying it). Do _not_ bury the current buffer, though."
(interactive)
(unless (eq mu4e-split-view 'single-window)
(let ((curbuf (current-buffer)))
;; note: 'walk-windows' does not seem to work correctly when modifying
;; windows; therefore, the doloops here
(dolist (frame (frame-list))
(dolist (win (window-list frame nil))
(with-current-buffer (window-buffer win)
(unless (eq curbuf (current-buffer))
(when (member major-mode '(mu4e-headers-mode mu4e-view-mode))
(when (eq t (window-deletable-p win))
(delete-window win))))))) t)))
(defun mu4e-get-time-date (prompt)
"Determine the emacs time value for the time/date entered by user
after PROMPT. Formats are all that are accepted by
`parse-time-string'."
(let ((timestr (read-string (mu4e-format "%s" prompt))))
(apply 'encode-time (org-parse-time-string timestr))))
;;; Mu4e-org-mode
(define-derived-mode mu4e-org-mode org-mode "mu4e:org"
"Major mode for mu4e documents, derived from
`org-mode'.")
(defun mu4e-info (path)
"Show a buffer with the information (an org-file) at PATH."
(unless (file-exists-p path)
(mu4e-error "Cannot find %s" path))
(let ((curbuf (current-buffer)))
(find-file path)
(mu4e-org-mode)
(setq buffer-read-only t)
(define-key mu4e-org-mode-map (kbd "q")
`(lambda ()
(interactive)
(bury-buffer)
(switch-to-buffer ,curbuf)))))
(defun mu4e-about ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/mu4e-about.org")))
(defun mu4e-news ()
"Show the mu4e 'about' page."
(interactive)
(mu4e-info (concat mu4e-doc-dir "/NEWS.org")))
;;; Misc 3
(defun mu4e-refresh-message (path)
"Re-parse message at PATH; if this works, we will
receive (:info add :path <path> :docid <docid>) as well as (:update
<msg-sexp>)."
(mu4e~proc-add path))
(defun mu4e~fontify-cited ()
"Colorize message content based on the citation level. This is
used in the view and compose modes."
(save-excursion
(goto-char (point-min))
(when (search-forward-regexp "^\n" nil t) ;; search the first empty line
(while (re-search-forward mu4e-cited-regexp nil t)
(let* ((level (string-width (replace-regexp-in-string
"[^>]" "" (match-string 0))))
(face (unless (zerop level)
(intern-soft (format "mu4e-cited-%d-face" level)))))
(when face
(add-text-properties (line-beginning-position 1)
(line-end-position 1) `(face ,face))))))))
(defun mu4e~fontify-signature ()
"Give the message signatures a distinctive color. This is used in
the view and compose modes and will color each signature in digest messages adhering to RFC 1153."
(let ((inhibit-read-only t))
(save-excursion
;; give the footer a different color...
(goto-char (point-min))
(while (re-search-forward "^-- *$" nil t)
(let ((p (point))
(end (or
(re-search-forward "\\(^-\\{30\\}.*$\\)" nil t) ;; 30 by RFC1153
(point-max))))
(add-text-properties p end '(face mu4e-footer-face)))))))
;;; Misc 4
(defun mu4e~quote-for-modeline (str)
"Quote a string to be used literally in the modeline. The
string will be shortened to fit if its length exceeds
`mu4e-modeline-max-width'."
(replace-regexp-in-string
"%" "%%"
(truncate-string-to-width str mu4e-modeline-max-width 0 nil t)))
(defun mu4e~active-composition-buffers ()
"Return all active mu4e composition buffers"
(let (buffers)
(save-excursion
(dolist (buffer (buffer-list t))
(set-buffer buffer)
(when (eq major-mode 'mu4e-compose-mode)
(push (buffer-name buffer) buffers))))
(nreverse buffers)))
;;
;; Loading messages
;;
(defvar mu4e-loading-mode-map nil "Keymap for *mu4e-loading* buffers.")
(unless mu4e-loading-mode-map
(setq mu4e-loading-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "n" 'ignore)
(define-key map "p" 'ignore)
(define-key map "q"
(lambda()(interactive)
(if (eq mu4e-split-view 'single-window)
'kill-buffer
'kill-buffer-and-window)))
map)))
(fset 'mu4e-loading-mode-map mu4e-loading-mode-map)
(define-derived-mode mu4e-loading-mode special-mode
"mu4e:loading"
(use-local-map mu4e-loading-mode-map)
(let ((inhibit-read-only t))
(erase-buffer)
(insert (propertize "Loading message..."
'face 'mu4e-system-face 'intangible t))))
;;
;; Bug Reference mode support
;;
;; This is Emacs 28 stuff but there is no need to guard it with some (f)boundp
;; checks (which would return nil if bug-reference.el is not loaded before
;; mu4e) since the function definition doesn't hurt and `add-hook' works fine
;; for not yet defined variables (by creating them).
(declare-function bug-reference-maybe-setup-from-mail "ext:bug-reference")
(defun mu4e-view--try-setup-bug-reference-mode ()
"Try to guess bug-reference setup from the current mu4e mail.
Looks at the maildir and the mail headers List, List-Id, Maildir,
To, From, Cc, and Subject and tries to guess suitable values for
`bug-reference-bug-regexp' and `bug-reference-url-format' by
matching the maildir name against GROUP-REGEXP and each header
value against HEADER-REGEXP in
`bug-reference-setup-from-mail-alist'."
(when (derived-mode-p 'mu4e-view-mode)
(let (header-values)
(save-excursion
(goto-char (point-min))
(dolist (field '("list" "list-id" "to" "from" "cc" "subject"))
(let ((val (mail-fetch-field field)))
(when val
(push val header-values)))))
(bug-reference-maybe-setup-from-mail
(mail-fetch-field "maildir")
header-values))))
(add-hook 'bug-reference-auto-setup-functions
#'mu4e-view--try-setup-bug-reference-mode)
;;; _
(provide 'mu4e-utils)
;;; mu4e-utils.el ends here
|
[
{
"context": " lexical-binding:t -*-\n\n;; Copyright (C) 2014-2015 Artur Malabarba <bruce.connor.am@gmail.com>\n\n;; Author: Artur Mal",
"end": 127,
"score": 0.9998934268951416,
"start": 112,
"tag": "NAME",
"value": "Artur Malabarba"
},
{
"context": " -*-\n\n;; Copyright (C) 2014-2015 Artur Malabarba <bruce.connor.am@gmail.com>\n\n;; Author: Artur Malabarba <bruce.connor.am@gma",
"end": 154,
"score": 0.9999351501464844,
"start": 129,
"tag": "EMAIL",
"value": "bruce.connor.am@gmail.com"
},
{
"context": " Malabarba <bruce.connor.am@gmail.com>\n\n;; Author: Artur Malabarba <bruce.connor.am@gmail.com>\n;; Prefix: paradox\n;;",
"end": 183,
"score": 0.9998936653137207,
"start": 168,
"tag": "NAME",
"value": "Artur Malabarba"
},
{
"context": "connor.am@gmail.com>\n\n;; Author: Artur Malabarba <bruce.connor.am@gmail.com>\n;; Prefix: paradox\n;; Separator: -\n\n;;; License:",
"end": 210,
"score": 0.9999347925186157,
"start": 185,
"tag": "EMAIL",
"value": "bruce.connor.am@gmail.com"
}
] | elpa/paradox-2.5.2/paradox-github.el | boylee1111/.emacs.d | 1 | ;;; paradox-github.el --- interacting with the Github API -*- lexical-binding:t -*-
;; Copyright (C) 2014-2015 Artur Malabarba <bruce.connor.am@gmail.com>
;; Author: Artur Malabarba <bruce.connor.am@gmail.com>
;; Prefix: paradox
;; Separator: -
;;; License:
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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.
;;
;;; Code:
(require 'cl-lib)
(require 'package)
(require 'paradox-core)
(defgroup paradox-github nil
"Paradox Github configurations."
:prefix "paradox-"
:package-version '(paradox . "2.0")
:group 'paradox)
(defvar paradox--user-starred-list nil)
(make-obsolete-variable
'paradox--user-starred-list 'paradox--user-starred-repos "2.1")
(defvar paradox--user-starred-repos (make-hash-table))
;;; Github token
(defcustom paradox-github-token nil
"Access token to use for github actions.
Currently, that means (un)starring repos.
To generate an access token:
1. Visit the page https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox
and login to github (if asked).
2. Click on \"Generate Token\", copy the generated token, and
save it to this variable by writing
(setq paradox-github-token TOKEN)
somewhere in your configuration and evaluating it (or just
restart emacs).
This is similar to how erc or jabber handle authentication in
emacs, but the following disclaimer always worth reminding.
DISCLAIMER
When you save this variable, DON'T WRITE IT ANYWHERE PUBLIC. This
token grants (very) limited access to your account.
END DISCLAIMER
Paradox will ask you whether you want github integration the
first time you start it. If you answer \"no\", it will remember
your choice via `customize-save-variable'. You can do this
manually by setting this variable to t. Setting it to nil means
it hasn't been configured yet."
:type '(choice (string :tag "Token")
(const :tag "Disable" t)
(const :tag "Ask me next time" nil))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defcustom paradox-automatically-star 'unconfigured
"When you install new packages, should they be automatically starred?
This variable has no effect if `paradox-github-token' isn't set
to a string.
Paradox is capable of automatically starring packages when you
install them, and unstarring when you delete them. This only
applies to actual installation/deletion, i.e. Paradox doesn't
auto (un)star packages that were simply upgraded.
If this variable is nil, this behaviour is disabled. \\<paradox-menu-mode-map>
On the Package Menu, you can always manually star packages with \\[paradox-menu-mark-star-unstar]."
:type '(choice (const :tag "Yes" t)
(const :tag "No" nil)
(const :tag "Ask later" unconfigured))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defmacro paradox--enforce-github-token (&rest forms)
"If a token is defined, perform FORMS, otherwise ignore forms ask for it be defined."
`(if (stringp paradox-github-token)
(progn ,@forms)
(setq paradox-github-token nil)
(paradox--check-github-token)))
(defun paradox--check-github-token ()
"Check that the user has either set or refused the github token.
If neither has happened, ask the user now whether he'd like to
configure or refuse the token."
(if (stringp paradox-github-token) t
(if paradox-github-token
t
(if (not (y-or-n-p "Would you like to set up GitHub integration?
This will allow you to star/unstar packages from the Package Menu. "))
(customize-save-variable 'paradox-github-token t)
(describe-variable 'paradox-github-token)
(when (get-buffer "*Help*")
(switch-to-buffer "*Help*")
(delete-other-windows))
(if (y-or-n-p "Follow the instructions on the `paradox-github-token' variable.
May I take you to the token generation page? ")
(browse-url "https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox"))
(message "Once you're finished, simply call `paradox-list-packages' again.")
nil))))
;;; Starring
(defun paradox-star-all-installed-packages ()
"Star all of your currently installed packages.
No questions asked."
(interactive)
(paradox--enforce-github-token
(mapc (lambda (x) (paradox--star-package-safe (car-safe x))) package-alist)))
(defun paradox--starred-repo-p (repo)
"Non-nil if REPO is starred by the user."
(gethash repo paradox--user-starred-repos))
(defun paradox--star-package-safe (pkg &optional delete query)
"Star PKG without throwing errors, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first."
(let ((repo (gethash pkg paradox--package-repo-list)))
(when (and repo (paradox--starred-repo-p repo))
(paradox--star-repo repo delete query))))
(defun paradox--star-repo (repo &optional delete query)
"Star REPO, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first.
Throws error if repo is malformed."
(when (or (not query)
(y-or-n-p (format "Really %sstar %s? "
(if delete "un" "") repo)))
(paradox--github-action-star repo delete)
(message "%starred %s." (if delete "Uns" "S") repo)
(if delete
(remhash repo paradox--user-starred-repos)
(puthash repo t paradox--user-starred-repos))))
(defun paradox--unstar-repo (repo &optional delete query)
"Unstar REPO.
Calls (paradox--star-repo REPO (not DELETE) QUERY)."
(paradox--star-repo repo (not delete) query))
(defun paradox--full-name-reader ()
"Return all \"full_name\" properties in the buffer.
Much faster than `json-read'."
(let (out)
(while (search-forward-regexp
"^ *\"full_name\" *: *\"\\(.*\\)\", *$" nil t)
(push (match-string-no-properties 1) out))
(goto-char (point-max))
out))
(defun paradox--refresh-user-starred-list (&optional async)
"Fetch the user's list of starred repos."
(paradox--github-action "user/starred?per_page=100"
:async (when async 'refresh)
:callback (lambda (res)
(setq paradox--user-starred-repos
(make-hash-table :size (length res)
:test #'equal))
(dolist (it res)
(puthash it t paradox--user-starred-repos)))
:reader #'paradox--full-name-reader))
(defun paradox--github-action-star (repo &optional delete)
"Call `paradox--github-action' with \"user/starred/REPO\" as the action.
DELETE and NO-RESULT are passed on."
(paradox--github-action (concat "user/starred/" repo)
:async t
:method (if (stringp delete) delete
(if delete "DELETE" "PUT"))))
;;; The Base (generic) function
(defun paradox--github-report (&rest text)
"Write TEXT to the *Paradox Github* buffer."
(with-current-buffer (get-buffer-create "*Paradox Report*")
(let ((inhibit-read-only t))
(erase-buffer)
(apply #'insert text))
(goto-char (point-min))))
(defun paradox--github-error (format &rest args)
"Throw an error using FORMAT and ARGS.
Also print contents of current buffer to *Paradox Github*."
(declare (indent 1))
(paradox--github-report (buffer-string))
(apply #'error
(concat format " See *Paradox Github* buffer for the full result")
args))
(defvar paradox--github-errors-to-ignore nil
"List of numbers to ignore when parsing the HTML return code.
`paradox--github-parse-response-code' normally returns nil on
200, t on 204, and emits messages or errors on other values.
Adding values to this list makes them be treated as a 200.")
(defun paradox--github-parse-response-code ()
"Non-nil if this reponse buffer looks ok.
Leave point at the return code on the first line."
(goto-char (point-min))
(unless (search-forward " " nil t)
(paradox--github-report (buffer-string))
(error "Tried contacting Github, but I can't understand the result. See *Paradox Github* buffer for the full result"))
(pcase (thing-at-point 'number)
((pred (lambda (n) (member n paradox--github-errors-to-ignore))) nil)
(`204 nil) ;; OK, but no content.
(`200 t) ;; OK, with content.
;; I'll implement redirection if anyone ever reports this.
;; For now, I haven't found a place where it's used.
((or `301 `302 `303 `304 `305 `306 `307)
(paradox--github-report "Redirect received:\n\n" (buffer-string))
;; (message "Received a redirect reply, please file a bug report (M-x `paradox-bug-report')")
nil)
((or `404) ;; Not found.
(paradox--github-report (buffer-string))
(message "This repo doesn't seem to exist, Github replied with: %s"
(substring (thing-at-point 'line) 0 -1))
nil)
((or `403) ;; Forbidden
(paradox--github-error
"Github wouldn't let me do this - does your token have the right permissions? They're here: https://github.com/settings/tokens"))
((or `400 `422) ;; Bad request.
(paradox--github-error
"Github didn't understand my request, please file a bug report (M-x `paradox-bug-report')"))
(`401 (paradox--github-error
(if (stringp paradox-github-token)
"Github says you're not authenticated, try creating a new Github token"
"Github says you're not authenticated, you need to configure `paradox-github-token'")))
(_ (paradox--github-error "Github returned: %S"
(substring (thing-at-point 'line) 0 -1)))))
(defvar paradox--github-next-page nil)
(defmacro paradox--with-github-buffer (method action async unwind-form
&rest body)
"Run BODY in a Github request buffer.
UNWIND-FORM is run no matter what, and doesn't affect the return
value."
(declare (indent 4)
(debug t))
(let ((call-name (make-symbol "callback")))
`(let ((,call-name
(lambda (&optional process event)
(cond
((or (not event)
(string-match "\\`finished" event))
(with-current-buffer (if (processp process)
(process-buffer process)
(current-buffer))
(unwind-protect
(when (paradox--github-parse-response-code)
(let ((next-page))
(when (search-forward-regexp
"^Link: .*<\\([^>]+\\)>; rel=\"next\"" nil t)
(setq next-page (match-string-no-properties 1))
(setq paradox--github-next-page next-page))
(ignore next-page)
(search-forward-regexp "^\r?$")
(skip-chars-forward "[:blank:]\n\r")
(delete-region (point-min) (point))
,@body))
,unwind-form
(kill-buffer (current-buffer)))))
((string-match "\\`exited abnormally" event)
,unwind-form
(paradox--github-report (buffer-string))
(message "async curl command %s\n method: %s\n action: %s"
event ,method ,action))))))
(if ,async
(condition-case nil
(set-process-sentinel
(apply #'start-process "paradox-github"
(generate-new-buffer "*Paradox http*")
"curl" "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
,call-name)
(error ,unwind-form))
(with-temp-buffer
;; Make the request.
(condition-case nil
(apply #'call-process
"curl" nil t nil "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
(error ,unwind-form))
;; Do the processing.
(funcall ,call-name))))))
(cl-defun paradox--github-action (action &key
(method "GET")
reader
max-pages
(callback #'identity)
async)
"Contact the github api performing ACTION with METHOD.
Default METHOD is \"GET\".
Action can be anything such as \"user/starred?per_page=100\". If
it's not a full url, it will be prepended with
\"https://api.github.com/\". The action might not work if
`paradox-github-token' isn't set.
This function also handles the pagination used in github results,
results of each page are appended together. Use MAX-PAGES to
limit the number of pages that are fetched.
Return value is always a list.
- If READER is nil, the result of the action is completely
ignored (no pagination is performed on this case, making it
much faster).
- Otherwise, READER is called as a function with point right
after the headers and should always return a list. As a special
exception, if READER is t, it is equivalent to a function that
returns (t).
CALLBACK, if provided, is a function to be called with the read
data as an argument. If the request succeeds with no data, it
will be given nil as an argument. Its return value is returned by
this function.
ASYNC determines to run the command asynchronously. In this case,
the function's return value is undefined. In particular, if ASYNC
is the symbol refresh, it means the package-menu should be
refreshed after the operation is done."
(declare (indent 1))
;; Make sure the token's configured.
(unless (string-match "\\`https?://" action)
(setq action (concat "https://api.github.com/" action)))
(let ((do-update (when (eq async 'refresh)
(make-symbol "paradox-github"))))
(when do-update
(add-to-list 'package--downloads-in-progress do-update))
(paradox--with-github-buffer method action async
(paradox--update-downloads-in-progress
do-update)
(cond
((not reader)
(funcall callback nil))
((or (not next-page)
(and max-pages (< max-pages 2)))
(funcall callback
(unless (eobp) (funcall reader))))
(t
(let ((result (unless (eobp) (funcall reader))))
(paradox--github-action next-page
:method method
:reader reader
:async async
:max-pages (when max-pages (1- max-pages))
:callback (lambda (res)
(funcall callback
(append result res))))))))))
(provide 'paradox-github)
;;; paradox-github.el ends here
| 42944 | ;;; paradox-github.el --- interacting with the Github API -*- lexical-binding:t -*-
;; Copyright (C) 2014-2015 <NAME> <<EMAIL>>
;; Author: <NAME> <<EMAIL>>
;; Prefix: paradox
;; Separator: -
;;; License:
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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.
;;
;;; Code:
(require 'cl-lib)
(require 'package)
(require 'paradox-core)
(defgroup paradox-github nil
"Paradox Github configurations."
:prefix "paradox-"
:package-version '(paradox . "2.0")
:group 'paradox)
(defvar paradox--user-starred-list nil)
(make-obsolete-variable
'paradox--user-starred-list 'paradox--user-starred-repos "2.1")
(defvar paradox--user-starred-repos (make-hash-table))
;;; Github token
(defcustom paradox-github-token nil
"Access token to use for github actions.
Currently, that means (un)starring repos.
To generate an access token:
1. Visit the page https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox
and login to github (if asked).
2. Click on \"Generate Token\", copy the generated token, and
save it to this variable by writing
(setq paradox-github-token TOKEN)
somewhere in your configuration and evaluating it (or just
restart emacs).
This is similar to how erc or jabber handle authentication in
emacs, but the following disclaimer always worth reminding.
DISCLAIMER
When you save this variable, DON'T WRITE IT ANYWHERE PUBLIC. This
token grants (very) limited access to your account.
END DISCLAIMER
Paradox will ask you whether you want github integration the
first time you start it. If you answer \"no\", it will remember
your choice via `customize-save-variable'. You can do this
manually by setting this variable to t. Setting it to nil means
it hasn't been configured yet."
:type '(choice (string :tag "Token")
(const :tag "Disable" t)
(const :tag "Ask me next time" nil))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defcustom paradox-automatically-star 'unconfigured
"When you install new packages, should they be automatically starred?
This variable has no effect if `paradox-github-token' isn't set
to a string.
Paradox is capable of automatically starring packages when you
install them, and unstarring when you delete them. This only
applies to actual installation/deletion, i.e. Paradox doesn't
auto (un)star packages that were simply upgraded.
If this variable is nil, this behaviour is disabled. \\<paradox-menu-mode-map>
On the Package Menu, you can always manually star packages with \\[paradox-menu-mark-star-unstar]."
:type '(choice (const :tag "Yes" t)
(const :tag "No" nil)
(const :tag "Ask later" unconfigured))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defmacro paradox--enforce-github-token (&rest forms)
"If a token is defined, perform FORMS, otherwise ignore forms ask for it be defined."
`(if (stringp paradox-github-token)
(progn ,@forms)
(setq paradox-github-token nil)
(paradox--check-github-token)))
(defun paradox--check-github-token ()
"Check that the user has either set or refused the github token.
If neither has happened, ask the user now whether he'd like to
configure or refuse the token."
(if (stringp paradox-github-token) t
(if paradox-github-token
t
(if (not (y-or-n-p "Would you like to set up GitHub integration?
This will allow you to star/unstar packages from the Package Menu. "))
(customize-save-variable 'paradox-github-token t)
(describe-variable 'paradox-github-token)
(when (get-buffer "*Help*")
(switch-to-buffer "*Help*")
(delete-other-windows))
(if (y-or-n-p "Follow the instructions on the `paradox-github-token' variable.
May I take you to the token generation page? ")
(browse-url "https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox"))
(message "Once you're finished, simply call `paradox-list-packages' again.")
nil))))
;;; Starring
(defun paradox-star-all-installed-packages ()
"Star all of your currently installed packages.
No questions asked."
(interactive)
(paradox--enforce-github-token
(mapc (lambda (x) (paradox--star-package-safe (car-safe x))) package-alist)))
(defun paradox--starred-repo-p (repo)
"Non-nil if REPO is starred by the user."
(gethash repo paradox--user-starred-repos))
(defun paradox--star-package-safe (pkg &optional delete query)
"Star PKG without throwing errors, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first."
(let ((repo (gethash pkg paradox--package-repo-list)))
(when (and repo (paradox--starred-repo-p repo))
(paradox--star-repo repo delete query))))
(defun paradox--star-repo (repo &optional delete query)
"Star REPO, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first.
Throws error if repo is malformed."
(when (or (not query)
(y-or-n-p (format "Really %sstar %s? "
(if delete "un" "") repo)))
(paradox--github-action-star repo delete)
(message "%starred %s." (if delete "Uns" "S") repo)
(if delete
(remhash repo paradox--user-starred-repos)
(puthash repo t paradox--user-starred-repos))))
(defun paradox--unstar-repo (repo &optional delete query)
"Unstar REPO.
Calls (paradox--star-repo REPO (not DELETE) QUERY)."
(paradox--star-repo repo (not delete) query))
(defun paradox--full-name-reader ()
"Return all \"full_name\" properties in the buffer.
Much faster than `json-read'."
(let (out)
(while (search-forward-regexp
"^ *\"full_name\" *: *\"\\(.*\\)\", *$" nil t)
(push (match-string-no-properties 1) out))
(goto-char (point-max))
out))
(defun paradox--refresh-user-starred-list (&optional async)
"Fetch the user's list of starred repos."
(paradox--github-action "user/starred?per_page=100"
:async (when async 'refresh)
:callback (lambda (res)
(setq paradox--user-starred-repos
(make-hash-table :size (length res)
:test #'equal))
(dolist (it res)
(puthash it t paradox--user-starred-repos)))
:reader #'paradox--full-name-reader))
(defun paradox--github-action-star (repo &optional delete)
"Call `paradox--github-action' with \"user/starred/REPO\" as the action.
DELETE and NO-RESULT are passed on."
(paradox--github-action (concat "user/starred/" repo)
:async t
:method (if (stringp delete) delete
(if delete "DELETE" "PUT"))))
;;; The Base (generic) function
(defun paradox--github-report (&rest text)
"Write TEXT to the *Paradox Github* buffer."
(with-current-buffer (get-buffer-create "*Paradox Report*")
(let ((inhibit-read-only t))
(erase-buffer)
(apply #'insert text))
(goto-char (point-min))))
(defun paradox--github-error (format &rest args)
"Throw an error using FORMAT and ARGS.
Also print contents of current buffer to *Paradox Github*."
(declare (indent 1))
(paradox--github-report (buffer-string))
(apply #'error
(concat format " See *Paradox Github* buffer for the full result")
args))
(defvar paradox--github-errors-to-ignore nil
"List of numbers to ignore when parsing the HTML return code.
`paradox--github-parse-response-code' normally returns nil on
200, t on 204, and emits messages or errors on other values.
Adding values to this list makes them be treated as a 200.")
(defun paradox--github-parse-response-code ()
"Non-nil if this reponse buffer looks ok.
Leave point at the return code on the first line."
(goto-char (point-min))
(unless (search-forward " " nil t)
(paradox--github-report (buffer-string))
(error "Tried contacting Github, but I can't understand the result. See *Paradox Github* buffer for the full result"))
(pcase (thing-at-point 'number)
((pred (lambda (n) (member n paradox--github-errors-to-ignore))) nil)
(`204 nil) ;; OK, but no content.
(`200 t) ;; OK, with content.
;; I'll implement redirection if anyone ever reports this.
;; For now, I haven't found a place where it's used.
((or `301 `302 `303 `304 `305 `306 `307)
(paradox--github-report "Redirect received:\n\n" (buffer-string))
;; (message "Received a redirect reply, please file a bug report (M-x `paradox-bug-report')")
nil)
((or `404) ;; Not found.
(paradox--github-report (buffer-string))
(message "This repo doesn't seem to exist, Github replied with: %s"
(substring (thing-at-point 'line) 0 -1))
nil)
((or `403) ;; Forbidden
(paradox--github-error
"Github wouldn't let me do this - does your token have the right permissions? They're here: https://github.com/settings/tokens"))
((or `400 `422) ;; Bad request.
(paradox--github-error
"Github didn't understand my request, please file a bug report (M-x `paradox-bug-report')"))
(`401 (paradox--github-error
(if (stringp paradox-github-token)
"Github says you're not authenticated, try creating a new Github token"
"Github says you're not authenticated, you need to configure `paradox-github-token'")))
(_ (paradox--github-error "Github returned: %S"
(substring (thing-at-point 'line) 0 -1)))))
(defvar paradox--github-next-page nil)
(defmacro paradox--with-github-buffer (method action async unwind-form
&rest body)
"Run BODY in a Github request buffer.
UNWIND-FORM is run no matter what, and doesn't affect the return
value."
(declare (indent 4)
(debug t))
(let ((call-name (make-symbol "callback")))
`(let ((,call-name
(lambda (&optional process event)
(cond
((or (not event)
(string-match "\\`finished" event))
(with-current-buffer (if (processp process)
(process-buffer process)
(current-buffer))
(unwind-protect
(when (paradox--github-parse-response-code)
(let ((next-page))
(when (search-forward-regexp
"^Link: .*<\\([^>]+\\)>; rel=\"next\"" nil t)
(setq next-page (match-string-no-properties 1))
(setq paradox--github-next-page next-page))
(ignore next-page)
(search-forward-regexp "^\r?$")
(skip-chars-forward "[:blank:]\n\r")
(delete-region (point-min) (point))
,@body))
,unwind-form
(kill-buffer (current-buffer)))))
((string-match "\\`exited abnormally" event)
,unwind-form
(paradox--github-report (buffer-string))
(message "async curl command %s\n method: %s\n action: %s"
event ,method ,action))))))
(if ,async
(condition-case nil
(set-process-sentinel
(apply #'start-process "paradox-github"
(generate-new-buffer "*Paradox http*")
"curl" "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
,call-name)
(error ,unwind-form))
(with-temp-buffer
;; Make the request.
(condition-case nil
(apply #'call-process
"curl" nil t nil "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
(error ,unwind-form))
;; Do the processing.
(funcall ,call-name))))))
(cl-defun paradox--github-action (action &key
(method "GET")
reader
max-pages
(callback #'identity)
async)
"Contact the github api performing ACTION with METHOD.
Default METHOD is \"GET\".
Action can be anything such as \"user/starred?per_page=100\". If
it's not a full url, it will be prepended with
\"https://api.github.com/\". The action might not work if
`paradox-github-token' isn't set.
This function also handles the pagination used in github results,
results of each page are appended together. Use MAX-PAGES to
limit the number of pages that are fetched.
Return value is always a list.
- If READER is nil, the result of the action is completely
ignored (no pagination is performed on this case, making it
much faster).
- Otherwise, READER is called as a function with point right
after the headers and should always return a list. As a special
exception, if READER is t, it is equivalent to a function that
returns (t).
CALLBACK, if provided, is a function to be called with the read
data as an argument. If the request succeeds with no data, it
will be given nil as an argument. Its return value is returned by
this function.
ASYNC determines to run the command asynchronously. In this case,
the function's return value is undefined. In particular, if ASYNC
is the symbol refresh, it means the package-menu should be
refreshed after the operation is done."
(declare (indent 1))
;; Make sure the token's configured.
(unless (string-match "\\`https?://" action)
(setq action (concat "https://api.github.com/" action)))
(let ((do-update (when (eq async 'refresh)
(make-symbol "paradox-github"))))
(when do-update
(add-to-list 'package--downloads-in-progress do-update))
(paradox--with-github-buffer method action async
(paradox--update-downloads-in-progress
do-update)
(cond
((not reader)
(funcall callback nil))
((or (not next-page)
(and max-pages (< max-pages 2)))
(funcall callback
(unless (eobp) (funcall reader))))
(t
(let ((result (unless (eobp) (funcall reader))))
(paradox--github-action next-page
:method method
:reader reader
:async async
:max-pages (when max-pages (1- max-pages))
:callback (lambda (res)
(funcall callback
(append result res))))))))))
(provide 'paradox-github)
;;; paradox-github.el ends here
| true | ;;; paradox-github.el --- interacting with the Github API -*- lexical-binding:t -*-
;; Copyright (C) 2014-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Prefix: paradox
;; Separator: -
;;; License:
;;
;; This file is NOT part of GNU Emacs.
;;
;; 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
;; of the License, 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.
;;
;;; Code:
(require 'cl-lib)
(require 'package)
(require 'paradox-core)
(defgroup paradox-github nil
"Paradox Github configurations."
:prefix "paradox-"
:package-version '(paradox . "2.0")
:group 'paradox)
(defvar paradox--user-starred-list nil)
(make-obsolete-variable
'paradox--user-starred-list 'paradox--user-starred-repos "2.1")
(defvar paradox--user-starred-repos (make-hash-table))
;;; Github token
(defcustom paradox-github-token nil
"Access token to use for github actions.
Currently, that means (un)starring repos.
To generate an access token:
1. Visit the page https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox
and login to github (if asked).
2. Click on \"Generate Token\", copy the generated token, and
save it to this variable by writing
(setq paradox-github-token TOKEN)
somewhere in your configuration and evaluating it (or just
restart emacs).
This is similar to how erc or jabber handle authentication in
emacs, but the following disclaimer always worth reminding.
DISCLAIMER
When you save this variable, DON'T WRITE IT ANYWHERE PUBLIC. This
token grants (very) limited access to your account.
END DISCLAIMER
Paradox will ask you whether you want github integration the
first time you start it. If you answer \"no\", it will remember
your choice via `customize-save-variable'. You can do this
manually by setting this variable to t. Setting it to nil means
it hasn't been configured yet."
:type '(choice (string :tag "Token")
(const :tag "Disable" t)
(const :tag "Ask me next time" nil))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defcustom paradox-automatically-star 'unconfigured
"When you install new packages, should they be automatically starred?
This variable has no effect if `paradox-github-token' isn't set
to a string.
Paradox is capable of automatically starring packages when you
install them, and unstarring when you delete them. This only
applies to actual installation/deletion, i.e. Paradox doesn't
auto (un)star packages that were simply upgraded.
If this variable is nil, this behaviour is disabled. \\<paradox-menu-mode-map>
On the Package Menu, you can always manually star packages with \\[paradox-menu-mark-star-unstar]."
:type '(choice (const :tag "Yes" t)
(const :tag "No" nil)
(const :tag "Ask later" unconfigured))
:group 'paradox-github
:package-version '(paradox . "0.2"))
(defmacro paradox--enforce-github-token (&rest forms)
"If a token is defined, perform FORMS, otherwise ignore forms ask for it be defined."
`(if (stringp paradox-github-token)
(progn ,@forms)
(setq paradox-github-token nil)
(paradox--check-github-token)))
(defun paradox--check-github-token ()
"Check that the user has either set or refused the github token.
If neither has happened, ask the user now whether he'd like to
configure or refuse the token."
(if (stringp paradox-github-token) t
(if paradox-github-token
t
(if (not (y-or-n-p "Would you like to set up GitHub integration?
This will allow you to star/unstar packages from the Package Menu. "))
(customize-save-variable 'paradox-github-token t)
(describe-variable 'paradox-github-token)
(when (get-buffer "*Help*")
(switch-to-buffer "*Help*")
(delete-other-windows))
(if (y-or-n-p "Follow the instructions on the `paradox-github-token' variable.
May I take you to the token generation page? ")
(browse-url "https://github.com/settings/tokens/new?scopes=public_repo&description=Paradox"))
(message "Once you're finished, simply call `paradox-list-packages' again.")
nil))))
;;; Starring
(defun paradox-star-all-installed-packages ()
"Star all of your currently installed packages.
No questions asked."
(interactive)
(paradox--enforce-github-token
(mapc (lambda (x) (paradox--star-package-safe (car-safe x))) package-alist)))
(defun paradox--starred-repo-p (repo)
"Non-nil if REPO is starred by the user."
(gethash repo paradox--user-starred-repos))
(defun paradox--star-package-safe (pkg &optional delete query)
"Star PKG without throwing errors, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first."
(let ((repo (gethash pkg paradox--package-repo-list)))
(when (and repo (paradox--starred-repo-p repo))
(paradox--star-repo repo delete query))))
(defun paradox--star-repo (repo &optional delete query)
"Star REPO, unless DELETE is non-nil, then unstar.
If QUERY is non-nil, ask the user first.
Throws error if repo is malformed."
(when (or (not query)
(y-or-n-p (format "Really %sstar %s? "
(if delete "un" "") repo)))
(paradox--github-action-star repo delete)
(message "%starred %s." (if delete "Uns" "S") repo)
(if delete
(remhash repo paradox--user-starred-repos)
(puthash repo t paradox--user-starred-repos))))
(defun paradox--unstar-repo (repo &optional delete query)
"Unstar REPO.
Calls (paradox--star-repo REPO (not DELETE) QUERY)."
(paradox--star-repo repo (not delete) query))
(defun paradox--full-name-reader ()
"Return all \"full_name\" properties in the buffer.
Much faster than `json-read'."
(let (out)
(while (search-forward-regexp
"^ *\"full_name\" *: *\"\\(.*\\)\", *$" nil t)
(push (match-string-no-properties 1) out))
(goto-char (point-max))
out))
(defun paradox--refresh-user-starred-list (&optional async)
"Fetch the user's list of starred repos."
(paradox--github-action "user/starred?per_page=100"
:async (when async 'refresh)
:callback (lambda (res)
(setq paradox--user-starred-repos
(make-hash-table :size (length res)
:test #'equal))
(dolist (it res)
(puthash it t paradox--user-starred-repos)))
:reader #'paradox--full-name-reader))
(defun paradox--github-action-star (repo &optional delete)
"Call `paradox--github-action' with \"user/starred/REPO\" as the action.
DELETE and NO-RESULT are passed on."
(paradox--github-action (concat "user/starred/" repo)
:async t
:method (if (stringp delete) delete
(if delete "DELETE" "PUT"))))
;;; The Base (generic) function
(defun paradox--github-report (&rest text)
"Write TEXT to the *Paradox Github* buffer."
(with-current-buffer (get-buffer-create "*Paradox Report*")
(let ((inhibit-read-only t))
(erase-buffer)
(apply #'insert text))
(goto-char (point-min))))
(defun paradox--github-error (format &rest args)
"Throw an error using FORMAT and ARGS.
Also print contents of current buffer to *Paradox Github*."
(declare (indent 1))
(paradox--github-report (buffer-string))
(apply #'error
(concat format " See *Paradox Github* buffer for the full result")
args))
(defvar paradox--github-errors-to-ignore nil
"List of numbers to ignore when parsing the HTML return code.
`paradox--github-parse-response-code' normally returns nil on
200, t on 204, and emits messages or errors on other values.
Adding values to this list makes them be treated as a 200.")
(defun paradox--github-parse-response-code ()
"Non-nil if this reponse buffer looks ok.
Leave point at the return code on the first line."
(goto-char (point-min))
(unless (search-forward " " nil t)
(paradox--github-report (buffer-string))
(error "Tried contacting Github, but I can't understand the result. See *Paradox Github* buffer for the full result"))
(pcase (thing-at-point 'number)
((pred (lambda (n) (member n paradox--github-errors-to-ignore))) nil)
(`204 nil) ;; OK, but no content.
(`200 t) ;; OK, with content.
;; I'll implement redirection if anyone ever reports this.
;; For now, I haven't found a place where it's used.
((or `301 `302 `303 `304 `305 `306 `307)
(paradox--github-report "Redirect received:\n\n" (buffer-string))
;; (message "Received a redirect reply, please file a bug report (M-x `paradox-bug-report')")
nil)
((or `404) ;; Not found.
(paradox--github-report (buffer-string))
(message "This repo doesn't seem to exist, Github replied with: %s"
(substring (thing-at-point 'line) 0 -1))
nil)
((or `403) ;; Forbidden
(paradox--github-error
"Github wouldn't let me do this - does your token have the right permissions? They're here: https://github.com/settings/tokens"))
((or `400 `422) ;; Bad request.
(paradox--github-error
"Github didn't understand my request, please file a bug report (M-x `paradox-bug-report')"))
(`401 (paradox--github-error
(if (stringp paradox-github-token)
"Github says you're not authenticated, try creating a new Github token"
"Github says you're not authenticated, you need to configure `paradox-github-token'")))
(_ (paradox--github-error "Github returned: %S"
(substring (thing-at-point 'line) 0 -1)))))
(defvar paradox--github-next-page nil)
(defmacro paradox--with-github-buffer (method action async unwind-form
&rest body)
"Run BODY in a Github request buffer.
UNWIND-FORM is run no matter what, and doesn't affect the return
value."
(declare (indent 4)
(debug t))
(let ((call-name (make-symbol "callback")))
`(let ((,call-name
(lambda (&optional process event)
(cond
((or (not event)
(string-match "\\`finished" event))
(with-current-buffer (if (processp process)
(process-buffer process)
(current-buffer))
(unwind-protect
(when (paradox--github-parse-response-code)
(let ((next-page))
(when (search-forward-regexp
"^Link: .*<\\([^>]+\\)>; rel=\"next\"" nil t)
(setq next-page (match-string-no-properties 1))
(setq paradox--github-next-page next-page))
(ignore next-page)
(search-forward-regexp "^\r?$")
(skip-chars-forward "[:blank:]\n\r")
(delete-region (point-min) (point))
,@body))
,unwind-form
(kill-buffer (current-buffer)))))
((string-match "\\`exited abnormally" event)
,unwind-form
(paradox--github-report (buffer-string))
(message "async curl command %s\n method: %s\n action: %s"
event ,method ,action))))))
(if ,async
(condition-case nil
(set-process-sentinel
(apply #'start-process "paradox-github"
(generate-new-buffer "*Paradox http*")
"curl" "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
,call-name)
(error ,unwind-form))
(with-temp-buffer
;; Make the request.
(condition-case nil
(apply #'call-process
"curl" nil t nil "-s" "-i" "-d" "" "-X" ,method ,action
(when (stringp paradox-github-token)
(list "-u" (concat paradox-github-token ":x-oauth-basic"))))
(error ,unwind-form))
;; Do the processing.
(funcall ,call-name))))))
(cl-defun paradox--github-action (action &key
(method "GET")
reader
max-pages
(callback #'identity)
async)
"Contact the github api performing ACTION with METHOD.
Default METHOD is \"GET\".
Action can be anything such as \"user/starred?per_page=100\". If
it's not a full url, it will be prepended with
\"https://api.github.com/\". The action might not work if
`paradox-github-token' isn't set.
This function also handles the pagination used in github results,
results of each page are appended together. Use MAX-PAGES to
limit the number of pages that are fetched.
Return value is always a list.
- If READER is nil, the result of the action is completely
ignored (no pagination is performed on this case, making it
much faster).
- Otherwise, READER is called as a function with point right
after the headers and should always return a list. As a special
exception, if READER is t, it is equivalent to a function that
returns (t).
CALLBACK, if provided, is a function to be called with the read
data as an argument. If the request succeeds with no data, it
will be given nil as an argument. Its return value is returned by
this function.
ASYNC determines to run the command asynchronously. In this case,
the function's return value is undefined. In particular, if ASYNC
is the symbol refresh, it means the package-menu should be
refreshed after the operation is done."
(declare (indent 1))
;; Make sure the token's configured.
(unless (string-match "\\`https?://" action)
(setq action (concat "https://api.github.com/" action)))
(let ((do-update (when (eq async 'refresh)
(make-symbol "paradox-github"))))
(when do-update
(add-to-list 'package--downloads-in-progress do-update))
(paradox--with-github-buffer method action async
(paradox--update-downloads-in-progress
do-update)
(cond
((not reader)
(funcall callback nil))
((or (not next-page)
(and max-pages (< max-pages 2)))
(funcall callback
(unless (eobp) (funcall reader))))
(t
(let ((result (unless (eobp) (funcall reader))))
(paradox--github-action next-page
:method method
:reader reader
:async async
:max-pages (when max-pages (1- max-pages))
:callback (lambda (res)
(funcall callback
(append result res))))))))))
(provide 'paradox-github)
;;; paradox-github.el ends here
|
[
{
"context": "EasyPG:\n;; # -*- mode:org; epa-file-encrypt-to: (\"me@mydomain.com\") -*-\n\n(require 'epa-file)\n(epa-file-enable)\n(set",
"end": 208,
"score": 0.9999282956123352,
"start": 193,
"tag": "EMAIL",
"value": "me@mydomain.com"
}
] | .emacs.d/config/post-package-load.d/epa.el | pw4ever/dotemacs | 0 | ;;
;; EasyPG Assistant encryption
;;
;; - https://orgmode.org/worg/org-tutorials/encrypting-files.html
;; -
;; Encrypting the Whole File Using EasyPG:
;; # -*- mode:org; epa-file-encrypt-to: ("me@mydomain.com") -*-
(require 'epa-file)
(epa-file-enable)
(setq epa-file-inhibit-auto-save t)
| 6314 | ;;
;; EasyPG Assistant encryption
;;
;; - https://orgmode.org/worg/org-tutorials/encrypting-files.html
;; -
;; Encrypting the Whole File Using EasyPG:
;; # -*- mode:org; epa-file-encrypt-to: ("<EMAIL>") -*-
(require 'epa-file)
(epa-file-enable)
(setq epa-file-inhibit-auto-save t)
| true | ;;
;; EasyPG Assistant encryption
;;
;; - https://orgmode.org/worg/org-tutorials/encrypting-files.html
;; -
;; Encrypting the Whole File Using EasyPG:
;; # -*- mode:org; epa-file-encrypt-to: ("PI:EMAIL:<EMAIL>END_PI") -*-
(require 'epa-file)
(epa-file-enable)
(setq epa-file-inhibit-auto-save t)
|
[
{
"context": "s\n\n;; Copyright (C) 2016 tequilasunset\n\n;; Author: tequilasunset <tequilasunset.mac@gmail.com> dawnxm <dawnxm@gma",
"end": 150,
"score": 0.9991406202316284,
"start": 137,
"tag": "USERNAME",
"value": "tequilasunset"
},
{
"context": "(C) 2016 tequilasunset\n\n;; Author: tequilasunset <tequilasunset.mac@gmail.com> dawnxm <dawnxm@gmail.com>\n;; Original Repositor",
"end": 179,
"score": 0.9999313354492188,
"start": 152,
"tag": "EMAIL",
"value": "tequilasunset.mac@gmail.com"
},
{
"context": "thor: tequilasunset <tequilasunset.mac@gmail.com> dawnxm <dawnxm@gmail.com>\n;; Original Repository: http:/",
"end": 188,
"score": 0.9996764063835144,
"start": 182,
"tag": "USERNAME",
"value": "dawnxm"
},
{
"context": "uilasunset <tequilasunset.mac@gmail.com> dawnxm <dawnxm@gmail.com>\n;; Original Repository: http://bitbucket.org/teq",
"end": 206,
"score": 0.9999285340309143,
"start": 190,
"tag": "EMAIL",
"value": "dawnxm@gmail.com"
},
{
"context": "-complete-latex\n;; Repository: https://github.com/dawnxm/emacs-auto-complete-latex\n;; Keywords: emacs, com",
"end": 327,
"score": 0.9944314956665039,
"start": 321,
"tag": "USERNAME",
"value": "dawnxm"
}
] | auto-complete-latex.el | dawnxm/emacs-auto-complete-latex | 0 | ;;; emacs-auto-complete-latex.el --- A LaTeX extention for auto-complete-mode for Emacs
;; Copyright (C) 2016 tequilasunset
;; Author: tequilasunset <tequilasunset.mac@gmail.com> dawnxm <dawnxm@gmail.com>
;; Original Repository: http://bitbucket.org/tequilasunset/auto-complete-latex
;; Repository: https://github.com/dawnxm/emacs-auto-complete-latex
;; Keywords: emacs, completion, LaTeX
(defconst ac-l-version "0.2.5")
;;; Requirements:
;; auto-complete-mode: https://github.com/auto-complete/auto-complete
;;; Installation:
;; - Put files into load-path, and add the following into init file for emacs.
;;
;; (setq tab-always-indent 'complete)
;; (ac-set-trigger-key "TAB")
;; (add-to-list 'ac-modes 'latex-mode)
;; (setq ac-l-dict-directory "/path/to/ac-l-dict/")
;; (setq auto-mode-alist
;; (cons '("\\.tex\\'" . latex-mode)
;; auto-mode-alist))
;; (add-hook 'latex-mode-hook 'ac-l-setup)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup)
;;
;; - If you get the error below
;;
;; `variable binding depth exceeds max-specpdl-size',
;;
;; add the following into init file.
;;
;; (setq max-specpdl-size (+ 500 max-specpdl-size))
;;; Commentary:
;; - Customize group:
;;
;; M-x customize-group RET auto-complete-latex RET
;;
;; - Don't use ac-sources:
;;
;; Use `ac-l-sources' instead.
;;
;; - Examples of configuration:
;;
;; * Setup for AUCTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'latex-mode)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup))
;;
;; * Setup for YaTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'yatex-mode)
;; (add-hook 'yatex-mode-hook 'ac-l-setup))
;;
;; If you want to use command help in Japanese, put
;; YATEXHLP.jp into ac-l-dict.
;;
;; - ac-l-dict:
;;
;; Files in it become sources, etc. Files are classified like below.
;; If there are unnecessary files, remove them.
;;
;; 1. Basic files
;;
;; basic-commands, basic-arguments, macro, latex-dot-ltx,
;; platex-commands, platex-arguments, primitives,
;; ptex-primitives
;;
;; Keywords in these files become candidates for basic sources.
;;
;; 2. User files
;;
;; user-commands, user-arguments
;;
;; These files become user sources.
;;
;; 3. Help file
;;
;; latex-help
;;
;; This file become a LaTeX command help.
;;
;; 4. External package files
;;
;; Files other than above become package sources. the
;; form is NAME-TYPE-SYMBOL-REQUIRES.
;;
;; NAME Package or class file name. You can set the
;; dependence with using `ac-l-package-dependences'.
;; TYPE `c' (command) or `a' (argument).
;; SYMBOL Symbol property. `*' => `p'.
;; REQUIRES Requires property. `*' => not set.
;;
;; - Commands that argument completion will work:
;;
;; `ac-l-argument-regexps'
;; `ac-l-file-regexps'
;; `ac-l-label-regexps'
;; `ac-l-bib-regexps'
;;
;; Above are related variables. If you want to complete label
;; names in argument of `\foo', write the following into init file.
;;
;; (add-to-list 'ac-l-label-regexps "foo")
;;
;; - Completion at point:
;;
;; Two commands `ac-l-complete-labels' and `ac-l-complete-bibs'
;; are provided to complete at point.
;;
;; - A table of symbol properties:
;;
;; SYMBOL | MEANING
;; --------+----------------------------------
;; l | LaTeX or pLaTeX
;; a | AMS packages
;; b | beamer
;; h | hyperlinks
;; g | graphics
;; m | math sign or equations
;; c | colors
;; t | tables
;; f | fonts
;; p | unclassified external packages
;; F | file names in a current directory
;; L | label names
;; B | bib keys
;; u | user-commands or user-arguments
;;
;; - Startup improvement:
;;
;; In case you use `ac-l-master-file', `ac-l-package-files' or
;; `ac-l-bib-files', startup will be slower. If you are using
;; ac-l-package-files, you can improve it with using the command
;; `ac-l-write-package-files'.
;;; Code:
(require 'cl)
(require 'auto-complete)
(defgroup auto-complete-latex nil
"Auto completion of LaTeX keywords."
:group 'auto-complete
:group 'tex
:prefix "ac-l-")
;;;; variables
(defcustom ac-l-update-delay 0.8
"Delay to update candidates."
:type 'float
:group 'auto-complete-latex)
(defcustom ac-l-master-file nil
"Specify LaTeX master file path as string.
Parse master file's \\input and \\include(only).
Then create candidates from master file and parsed files."
:type 'string
:group 'auto-complete-latex)
(defvaralias 'ac-l-target 'ac-l-master-file)
(defcustom ac-l-sources nil
"A list of user sources.
This is similar to `ac-sources', but you don't have to add
`ac-l-source-*' and below sources.
ac-source-dictionary
ac-source-files-in-current-dir
ac-source-filename
ac-source-words-in-*"
:type '(repeat symbol)
:group 'auto-complete-latex)
(defcustom ac-l-package-files nil
"A list of package files (valid suffixes are .sty and .cls).
Parse LaTeX command definitions in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-bib-files nil
"A list of bib files (valid suffix is .bib).
Parse bibliography keys in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-use-word-completion nil
"If non-nil, use sources for normal word (text) completion."
:type 'boolean
:group 'auto-complete-latex)
;;; internal
(defvar ac-l-major-mode nil)
(defvar ac-l-master-p nil)
(defconst ac-l-command-prefix "\\\\\\([a-zA-Z@]+\\)")
(defvar ac-l-update-timer nil)
;;;; functions
;;; DB
;; package-cmds, package-args, cur-bib-tables, all-bib-tables, latex-cmds,
;; latex-args, package-sources, user-noprefix-sources, user-prefix-sources,
;; label-cands, bibitem-cands, bib-cands, filenames, label-tables, sources,
;; bibitem-tables, file-cmds, file-words, children,
(defconst ac-l-db (make-hash-table :test 'eq))
(defsubst ac-l-db-get (sym)
(gethash sym ac-l-db))
(defsubst ac-l-db-set (sym value)
(puthash sym value ac-l-db))
(defsubst ac-l-db-push (value sym)
(puthash sym (cons value (gethash sym ac-l-db)) ac-l-db))
(defsubst ac-l-db-append (sym lst)
(puthash sym (append (gethash sym ac-l-db) lst) ac-l-db))
;;; prefixes for arguments
(defcustom ac-l-argument-regexps
'("\\(?:usep\\|RequireP\\)ackage" "documentclass" "begin" "end" "fnsymbol"
"\\(?:this\\)?pagestyle" "bibliography\\(?:style\\)?" "pagenumbering"
"\\(?:new\\|addto\\|set\\)counter" "[aA]lph" "arabic" "[rR]oman"
"@\\(?:addtoreset\\|startsection\\|namedef\\|definecounter\\)"
"addcontentsline" "numberwithin" "\\(?:text\\|page\\|f\\|define\\)color"
"colorbox" "\\(?:column\\|row\\|cell\\|arrayrule\\|doublerulesep\\)color"
"hypersetup" "include\\(?:graphics\\|slide\\)" "insert[a-z]+" "frame"
"lst[a-zDIMS]+" "resetcount\\(?:er\\)?onoverlays" "tableofcontents"
"movie" "hyperlink\\(?:movie\\|sound\\)" "multiinclude" "sound" "note"
"trans[a-z]+" "use[a-z]*theme" "[a-z]+beamertemplate[a-z]*"
"\\(?:use\\|set\\)beamer\\(?:color\\|font\\|covered\\)")
"A list of regexps to match commands which take arguments."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-file-regexps
'("include\\(?:only\\|graphics\\)?" "input" "hypersetup")
"A list of regexps to match commands which take file name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-label-regexps
'("\\(?:page\\|auto\\|eq\\)?ref" "label")
"A list of regexps to match commands which take label name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-bib-regexps
'("\\(?:no\\|short\\)?cite[a-zA-Z]*" "bibitem")
"A list of regexps to match commands which take bibliography argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defun ac-l-prefix-in-paren (regexps)
;; This doesn't work as omni completion because the return is ac-point.
(if (save-excursion
(re-search-backward
(concat "\\\\\\("
(mapconcat 'identity regexps "\\|")
"\\)\\*?\\(\\s([^]>}]*\\s)\\)*\\(\\s([^]>}]*\\)\\=") nil t))
ac-point))
;;; read file data
(defsubst ac-l-convert-filename-to-file (filename)
;; faster than file-name-sans-extension
(let ((nodir (file-name-nondirectory filename)))
(if (string-match "\\(.+\\)\\.[^.]*$" nodir)
(match-string 1 nodir)
nodir)))
(defun* ac-l-read-bibs
(&key (files ac-l-bib-files)
(regexp "^@[^{@]+{\\([^ =,\t\n]*\\),\n[^@]+\\(^}\\)"))
"Convert each bib file listed in FILES to a hash table."
(dolist (filename files)
(let* ((file (ac-l-convert-filename-to-file filename))
(table (make-hash-table :test 'equal)))
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward regexp nil t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table))))
(ac-l-db-push (cons file table) 'all-bib-tables)
(ac-l-db-push file 'filenames))))
;; k -> package name in `ac-l-package-files', v -> [cmds args]
(defconst ac-l-packages (make-hash-table :test 'equal))
(defun* ac-l-read-packages
(&key (files ac-l-package-files)
(cmd-re "\\\\\\(?:[a-z@]*def\\|let\\|new[a-z]+\\|providecommand\\|Declare[a-zA-Z@]+\\)\\*?[ \t]*{?\\\\\\([a-zA-Z]+\\)}?[ =\\#[{]")
(arg-re "\\\\\\(?:DeclareOption[a-zA-Z]*\\|new[a-z]+\\|@definecounter\\)\\*?[ \t]*{\\([a-zA-Z]+\\)}"))
"Convert each package listed in FILES to an element of `ac-l-packages'."
(dolist (filename files)
(let ((file (ac-l-convert-filename-to-file filename))
cand cmds args)
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward cmd-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand cmds)
(push cand cmds)))
(goto-char (point-min))
(while (re-search-forward arg-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand args)
(push cand args)))))
(puthash file (vector cmds args) ac-l-packages)
(ac-l-db-push file 'filenames))))
(defcustom ac-l-dict-directory "~/.emacs.d/ac-l-dict/"
"Path of the ac-l-dict."
:type 'string
:group 'auto-complete-latex)
(defun ac-l-write-package-files (dir)
"Output candidates collected from files listed in `ac-l-package-files'.
You can use them in the ac-l-dict."
(interactive (list (read-directory-name "Dir: " ac-l-dict-directory nil t)))
(maphash (lambda (k v)
(loop for (type cands) in `((c ,(aref v 0)) (a ,(aref v 1)))
when cands do
(with-temp-buffer
(insert (mapconcat 'identity (sort cands #'string<) "\n"))
(write-region (point-min) (point-max)
(format "%s%s-%s-*-*" dir k type)))))
ac-l-packages))
(defcustom ac-l-package-dependences
'(("hyperref" . "beamer")
("color" . "colortbl\\|beamer")
("array" . "tabularx\\|colortbl"))
"Alist of external package dependences.
Each element is the form (REQUIRED PACKAGE . PACKAGES). Package and
class files are treated equivalently. This is effective only for
files read from the ac-l-dict."
:type '(repeat (cons string regexp))
:group 'auto-complete-latex)
(defun* ac-l-set-help-doc
(&optional (sources '(ac-l-source-latex-commands
ac-l-source-latex-arguments)))
"Set document property to each source listed in SOURCES."
(let* ((files (directory-files ac-l-dict-directory))
(help-fn (cond
((member "YATEXHLP.jp" files)
;; `Warning: defvar ignored because kinsoku-limit is let-bound'.
(load "international/kinsoku")
'ac-l-yatex-jp-documentation)
((member "latex-help" files)
'ac-l-latex2e-documentation))))
(when help-fn
(dolist (source sources)
(push (cons 'document help-fn) (symbol-value source))))))
(defun ac-l-make-source-from-dir ()
(dolist (file (directory-files ac-l-dict-directory nil "^[^.]"))
(let ((sym "p")
(prx ac-l-command-prefix)
source package req)
;; parse file name
(cond
((string-match "^\\([^-]+\\)-\\([^-]\\)-\\([^-]\\)-\\([^-]\\)$" file)
(let* ((n (match-string 1 file))
(T (match-string 2 file))
(s (match-string 3 file))
(r (match-string 4 file))
(d (assoc-default n ac-l-package-dependences 'string=))
(filenames (ac-l-db-get 'filenames)))
(unless (member n filenames)
(ac-l-db-set 'filenames (cons n filenames)))
(if d (setq package (concat n "\\|" d)) (setq package n))
(unless (string= s "*") (setq sym s))
(unless (string= r "*") (setq req (string-to-number r)))
(if (string= T "a")
(setq prx 'ac-l-argument
source (intern (format "ac-l-source-%s-arguments" n)))
(setq source (intern (format "ac-l-source-%s-commands" n))))))
((or (string= "macro" file)
(string= "latex-dot-ltx" file)
(string-match "^\\(ptex-\\)?primitives$" file)
(string-match "^\\(basic\\|platex\\)-commands$" file))
(setq source 'latex-cmd))
((string-match "^\\(basic\\|platex\\)-arguments$" file)
(setq source 'latex-arg))
((cond ((string= "user-commands" file) t)
((string= "user-arguments" file) (setq prx 'ac-l-argument)))
(setq sym "u"
source (intern (concat "ac-l-source-" file)))))
;; read file contents
(when source
(let ((cands (with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory file))
(split-string (buffer-string) "\n"))))
(case source
(latex-cmd (ac-l-db-append 'latex-cmds cands))
(latex-arg (ac-l-db-append 'latex-args cands))
(otherwise
(set source (delq nil `(,(if package `(ac-l-package . ,package))
,(if (integerp req) `(requires . ,req))
(symbol . ,sym)
(prefix . ,prx)
(candidates . ',cands))))
(cond (package
(ac-l-db-push source 'package-sources))
((string= sym "u")
(ac-l-db-push source 'user-prefix-sources))))))))))
;;; update file's info
(defstruct ac-l-info
"Information about each tex file."
modification words commands packages labels bibitems bibs)
;; k -> filename (full path), v -> struct
(defconst ac-l-structs (make-hash-table :test 'equal))
(defconst ac-l-children (make-hash-table :test 'equal))
(defsubst ac-l-split-string (str)
(split-string str "\\([ \t\n]\\|%.*\n\\|,\\)+" t))
(defsubst ac-l-candidates-hash (regexp table beg end)
(goto-char beg)
(while (re-search-forward regexp end t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table)
(goto-char (1+ (match-beginning 0)))))
(defun ac-l-make-info (struct filename &optional master)
(let* ((word-re "[^\\,]\\(\\<[-'a-zA-Z]+\\>\\)")
(package-re "^[^%\n]*\\\\\\(?:\\(?:usep\\|RequireP\\)ackage\\|documentclass\\)\\(?:\\[[^]]*\\]\\)?{\\([^}]+\\)")
(lines ".*\n.*\n.*\n")
(label-re "\\\\label{\\(\\(?:[^ }\t\n]\\)+\\)}")
(label-re1 (concat "^[^%\n]*" label-re ".*$"))
(label-re2 (concat "^" lines "[^%\n]*" label-re lines ".*$"))
(bibitem-re "^[^%\n]*\\\\bibitem\\(?:\\[[^]]*\\]\\)?{\\(\\(?:[^ }\t\n]\\)+\\)}[^\\]*")
(bib-re "^[^%\n]*\\\\bibliography{\\([^}]+\\)")
(collect-p (not (or master (buffer-file-name))))
(beg (point-min))
(label-beg (save-excursion
(goto-char beg)
(forward-line 3)
(point)))
(label-end (save-excursion
(goto-char (point-max))
(forward-line -3)
(point)))
(label-ht (or (ignore-errors (clrhash (ac-l-info-labels struct)))
(make-hash-table :test 'equal)))
(bibitem-ht (or (ignore-errors (clrhash (ac-l-info-bibitems struct)))
(make-hash-table :test 'equal)))
(i 0)
words commands packages bibs cand)
(save-excursion
(when (and ac-l-use-word-completion collect-p)
(goto-char beg)
(while (and (re-search-forward word-re nil t) (<= i 100))
(setq cand (match-string-no-properties 1))
(when (and (not (member cand words))
(>= (length cand) 3))
(push cand words)
(incf i))))
(when collect-p
(let ((latex-cmds (ac-l-db-get 'latex-cmds)))
(goto-char beg)
(while (re-search-forward ac-l-command-prefix nil t)
(setq cand (match-string-no-properties 1))
(unless (or (member cand commands)
(member cand latex-cmds))
(push cand commands)))))
(when master
(goto-char beg)
(while (re-search-forward package-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name packages)
(push name packages)))))
(ac-l-candidates-hash label-re1 label-ht beg label-beg)
(ac-l-candidates-hash label-re2 label-ht beg nil)
(ac-l-candidates-hash label-re1 label-ht label-end nil)
(ac-l-candidates-hash bibitem-re bibitem-ht beg nil)
(when ac-l-bib-files
(goto-char beg)
(while (re-search-forward bib-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name bibs)
(push name bibs))))))
(puthash filename
(make-ac-l-info
:modification (ignore-errors (nth 5 (file-attributes filename)))
:words words
:commands commands
:packages packages
:labels label-ht
:bibitems bibitem-ht
:bibs bibs)
ac-l-structs)))
(defsubst ac-l-struct-master ()
(gethash ac-l-master-file ac-l-structs))
(defsubst ac-l-all-structs ()
(delq t (append (loop for v being the hash-values in ac-l-children collect v)
(list (ac-l-struct-master)))))
(defsubst ac-l-append-info (info-fn)
(apply 'append (mapcar info-fn (ac-l-all-structs))))
(defsubst ac-l-convert-file-to-filename (file base-dir suffix)
;; FILE -> BASE-DIR/FILE.SUFFIX
(let ((path (expand-file-name file base-dir)))
(concat (if (string-match "^\\(.+\\)\\.[^./]+$" path)
(match-string 1 path)
path)
"." suffix)))
(defun ac-l-update-children-names ()
;; parse file names in master and push them into DB
(let* ((beg-re "^[^%\n]*\\\\\\(?:")
(end-re "\\)[ {\t]+\\([^ }%\n]+\\)")
(regexp (concat beg-re "in\\(?:put\\|clude\\)" end-re))
(beg (point-min))
(dir (if (string-match "^\\(.+/\\).+$" ac-l-master-file)
(match-string 1 ac-l-master-file)
"/"))
names)
(save-excursion
(goto-char beg)
(when (re-search-forward (concat beg-re "includeonly" end-re) nil t)
(setq names (ac-l-split-string (match-string-no-properties 1))
regexp (concat beg-re "input" end-re)))
(goto-char beg)
(setq names (append names
(loop while (re-search-forward regexp nil t)
collect (match-string-no-properties 1)))))
(ac-l-db-set 'children
(loop for name in names
for filename = (ac-l-convert-file-to-filename name dir "tex")
if (file-exists-p filename)
collect filename))))
(defun ac-l-update-children (filenames)
(clrhash ac-l-children)
(dolist (filename filenames)
;; If struct is undefined, put t.
(puthash filename (or (gethash filename ac-l-structs) t) ac-l-children))
ac-l-children)
(defsubst ac-l-file-mod-p (struct filename)
(not (equal (ac-l-info-modification struct)
(nth 5 (file-attributes filename)))))
(defsubst ac-l-update-master-info ()
(ac-l-make-info (ac-l-struct-master) ac-l-master-file t))
(defun ac-l-update-info (&optional force)
"If necessary, update file's info."
(if ac-l-master-p
(let ((master-mod-p (or force (ac-l-file-mod-p (ac-l-struct-master) ac-l-master-file)))
(buf-list (buffer-list)))
;; master
(or (loop with master = (expand-file-name ac-l-master-file)
for buf in buf-list
if (string= master (buffer-file-name buf))
do (when (or (buffer-modified-p buf) master-mod-p)
(with-current-buffer buf
(ac-l-update-children-names)
(ac-l-update-master-info)))
and return t)
(when master-mod-p
(with-temp-buffer
(insert-file-contents ac-l-master-file)
(ac-l-update-children-names)
(ac-l-update-master-info))))
;; children
(let* ((filenames (ac-l-db-get 'children))
(table (ac-l-update-children filenames)))
(dolist (buf buf-list)
(let* ((filename (buffer-file-name buf))
(struct (gethash filename table)))
(when (and struct
(or (not (ac-l-info-p struct))
(buffer-modified-p buf)
(ac-l-file-mod-p struct filename)))
(with-current-buffer buf
(ac-l-make-info struct filename))
(remhash filename table))))
(maphash (lambda (filename struct)
(when (or (not (ac-l-info-p struct))
(ac-l-file-mod-p struct filename))
(with-temp-buffer
(insert-file-contents filename)
(ac-l-make-info struct filename))))
table)
(ac-l-update-children filenames)))
(when (or force (buffer-modified-p))
(ac-l-update-master-info))))
(defun ac-l-update ()
"Update `ac-sources' according to packages."
(ac-l-db-set 'package-cmds nil)
(ac-l-db-set 'package-args nil)
(let ((sources (ac-l-db-get 'sources))
cmd-sources arg-sources)
(dolist (name (ac-l-info-packages (ac-l-struct-master)))
;; sources
(dolist (source (ac-l-db-get 'package-sources))
(let* ((alist (symbol-value source))
(package (cdr (assq 'ac-l-package alist)))
(prefix (cdr (assq 'prefix alist))))
(when (string-match package name)
(cond
((string= prefix ac-l-command-prefix)
(unless (memq source cmd-sources)
(push source cmd-sources)))
((eq prefix 'ac-l-argument)
(unless (memq source arg-sources)
(push source arg-sources)))))))
;; candidates
(let* ((vec (or (gethash name ac-l-packages) '[nil nil]))
(cmd (aref vec 0))
(arg (aref vec 1)))
(if cmd (ac-l-db-append 'package-cmds cmd))
(if arg (ac-l-db-append 'package-args arg))))
(setq ac-sources (append (ac-l-db-get 'user-prefix-sources)
(nth 0 sources)
cmd-sources
(nth 1 sources)
arg-sources
(nth 2 sources)
(ac-l-db-get 'user-noprefix-sources)
(nth 3 sources)))))
(defun ac-l-set-sources ()
(let ((s0 `(ac-source-filename
ac-l-source-labels
ac-l-source-bibitems
,(if ac-l-bib-files 'ac-l-source-bibliographies)
,(if (ac-l-db-get 'latex-cmds) 'ac-l-source-latex-commands)))
(s1 `(,(if ac-l-package-files 'ac-l-source-package-commands)
ac-l-source-commands
ac-source-files-in-current-dir
,(if (ac-l-db-get 'latex-args) 'ac-l-source-latex-arguments)))
(s2 `(,(if ac-l-package-files 'ac-l-source-package-arguments)
,(if (ac-l-db-get 'filenames) 'ac-l-source-filenames)))
(s3 `(,(if ac-l-use-word-completion 'ac-l-source-words)
ac-source-dictionary)))
(ac-l-db-set 'sources
(mapcar (lambda (s) (delq nil s)) (list s0 s1 s2 s3)))))
;;; candidate
;; copied from auto-complete.el and added arguments
(defun ac-l-candidate (beg-re end-re)
(let ((i 0)
(regexp (concat beg-re (regexp-quote ac-prefix) end-re))
cand cands)
(save-excursion
;; Search backward
(goto-char ac-point)
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-backward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i)))
;; Search backward
(goto-char (+ ac-point (length ac-prefix)))
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-forward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i))))
(nreverse cands)))
(defun ac-l-incremental-update-index (idx cand-fn)
(let ((pair (symbol-value idx))
(ac-limit (or (and (integerp ac-limit) ac-limit) 10)))
(when (null pair)
(set idx (cons nil nil)))
;; Mark incomplete
(when (car pair)
(setcar pair nil))
(let ((list (cdr pair))
(words (funcall cand-fn)))
(dolist (word words)
(unless (member word list)
(push word list)
(setcdr pair list))))))
(defun ac-l-update-index (idx cand-fn)
(dolist (buf (buffer-list))
(when (and (eq ac-l-major-mode (buffer-local-value 'major-mode buf))
(or ac-fuzzy-enable
(not (eq buf (current-buffer)))))
(with-current-buffer buf
(when (and (not (car (symbol-value idx)))
(< (buffer-size) 1048576))
;; Complete index
(set idx (cons t (let ((ac-point (point-min))
(ac-prefix "")
ac-limit)
(funcall cand-fn)))))))))
(defun ac-l-candidates (idx cand-fn)
(loop initially (unless ac-fuzzy-enable
(ac-l-incremental-update-index idx cand-fn))
for buf in (buffer-list)
if (and (or (not (integerp ac-limit)) (< (length cands) ac-limit))
(derived-mode-p (buffer-local-value 'major-mode buf)))
append (funcall ac-match-function ac-prefix
(cdr (buffer-local-value idx buf)))
into cands
finally return cands))
;;;; sources
(defvar ac-l-word-index nil)
(make-variable-buffer-local 'ac-l-word-index)
(defun ac-l-smart-capitalize ()
;; Meadow/Emacs memo: http://www.bookshelf.jp/soft/meadow_34.html#SEC495
(when (and (looking-back "[[:space:][:cntrl:]]+[a-z']+")
(= (point) (save-excursion
(backward-sentence)
(forward-word)
(point))))
(capitalize-word -1)))
(defun ac-l-candidate-words-in-buffer ()
(ac-l-candidate "[^\\,]\\(\\<" "[-'a-zA-Z]+\\>\\)"))
(defvar ac-l-source-words
'((action . ac-l-smart-capitalize)
(requires . 3)))
(defvar ac-l-command-index nil)
(make-variable-buffer-local 'ac-l-command-index)
(defun ac-l-candidate-commands-in-buffer ()
(ac-l-candidate "\\\\\\(" "[a-zA-Z@]+\\)"))
(defvar ac-l-source-commands
`((prefix . ,ac-l-command-prefix)))
(defun ac-l-basic-sources-setup ()
;; Add properties into basic sources.
;; The sources work like ac-source-words-in-same-mode-buffers.
(let* ((cw-fn 'ac-l-candidate-words-in-buffer)
(cc-fn 'ac-l-candidate-commands-in-buffer)
(wc `(ac-l-candidates 'ac-l-word-index ',cw-fn))
(cc `(ac-l-candidates 'ac-l-command-index ',cc-fn))
(wi `(ac-l-update-index 'ac-l-word-index ',cw-fn))
(ci `(ac-l-update-index 'ac-l-command-index ',cc-fn)))
(labels ((pushprops (p1 p2 p3 p4)
(push `(candidates . ,p1) ac-l-source-words)
(push `(candidates . ,p2) ac-l-source-commands)
(push `(init . ,p3) ac-l-source-words)
(push `(init . ,p4) ac-l-source-commands)))
(if ac-l-master-p
;; add functions for file's candidates
(pushprops `(append ,wc (ac-l-db-get 'file-words))
`(append ,cc (ac-l-db-get 'file-cmds))
`(lambda ()
,wi
(ac-l-db-set 'file-words
(ac-l-append-info 'ac-l-info-words)))
`(lambda ()
,ci
(ac-l-db-set 'file-cmds
(ac-l-append-info 'ac-l-info-commands))))
(pushprops wc cc wi ci)))))
(defvar ac-l-source-latex-commands
`((candidates . (ac-l-db-get 'latex-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "l")))
(defvar ac-l-source-latex-arguments
`((candidates . (ac-l-db-get 'latex-args))
(prefix . ac-l-argument)
(symbol . "l")))
(defvar ac-l-source-filenames
'((candidates . (ac-l-db-get 'filenames))
(prefix . ac-l-argument))
"Source for package and bib file names.")
(defvar ac-l-source-package-commands
`((candidates . (ac-l-db-get 'package-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "p")))
(defvar ac-l-source-package-arguments
'((candidates . (ac-l-db-get 'package-args))
(prefix . ac-l-argument)
(symbol . "p")))
(defsubst ac-l-gethash (key tables)
(loop for table in tables thereis (gethash key table)))
(defsubst ac-l-append-keys (tables)
(apply 'append (mapcar (lambda (table)
(loop for k being the hash-keys in table collect k))
tables)))
(defun ac-l-update-labels ()
(let ((it (ac-l-db-set 'label-tables
(mapcar 'ac-l-info-labels (ac-l-all-structs)))))
(ac-l-db-set 'label-cands (ac-l-append-keys it))))
(defvar ac-l-source-labels
'((init . ac-l-update-labels)
(candidates . (ac-l-db-get 'label-cands))
(prefix . ac-l-label)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'label-tables))))
(symbol . "L")))
(defun ac-l-complete-labels ()
"Start label name completion at point."
(interactive)
(auto-complete (list (remove '(prefix . ac-l-label) ac-l-source-labels))))
(defun ac-l-update-bibitems ()
(let ((it (ac-l-db-set 'bibitem-tables
(mapcar 'ac-l-info-bibitems (ac-l-all-structs)))))
(ac-l-db-set 'bibitem-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibitems
'((init . ac-l-update-bibitems)
(candidates . (ac-l-db-get 'bibitem-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'bibitem-tables))))
(symbol . "B")))
(defun ac-l-update-bib ()
(let ((it (ac-l-db-set 'cur-bib-tables
(loop with tables = (ac-l-db-get 'all-bib-tables)
for name in (ac-l-append-info 'ac-l-info-bibs)
if (assoc-default name tables 'string=)
collect it))))
(ac-l-db-set 'bib-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibliographies
'((init . ac-l-update-bib)
(candidates . (ac-l-db-get 'bib-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'cur-bib-tables))))
(symbol . "B")))
(defun ac-l-complete-bibs ()
"Start bibliography completion at point."
(interactive)
(auto-complete `(,(remove '(prefix . ac-l-bib) ac-l-source-bibitems)
,(remove '(prefix . ac-l-bib) ac-l-source-bibliographies))))
;;; help
(defconst ac-l-help (make-hash-table :test 'equal))
(defmacro ac-l-define-help-doc (name file beg-re end-re)
(declare (indent 1))
`(defun ,(intern (format "ac-l-%s-documentation" name)) (str)
(or (gethash str ac-l-help)
(unless (string-match "@" str)
(with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory ,file))
(if (re-search-forward (concat ,beg-re str ,end-re) nil t)
(puthash str (match-string-no-properties 1) ac-l-help)
(puthash str t ac-l-help)))))))
(ac-l-define-help-doc latex2e
"latex-help"
"\\(?:\f\n\\)\\([^\f]*\\(?:^[`\\]"
"\\(?:\\s(\\|[ '\n]\\)[^\f]+\\)\\)")
(ac-l-define-help-doc yatex-jp
"YATEXHLP.jp"
"^\\(\\\\?"
"\n[^]+\\)")
;;;; clear
(defvar ac-l-clear-timer nil)
(defun ac-l-clear ()
(clrhash ac-l-help))
(defun* ac-l-cancel-timers
(&optional (timers '(ac-l-update-timer
ac-l-clear-timer)))
(interactive)
(dolist (timer timers)
(let ((val (symbol-value timer)))
(when (timerp val)
(cancel-timer val)
(set timer nil)))))
;;;; setup
(defun ac-l-update-all (&optional force)
(when (eq ac-l-major-mode major-mode)
(ac-l-update-info force)
(ac-l-update)))
(defun ac-l-master-p ()
(setq ac-l-master-p (and (stringp ac-l-master-file)
(file-exists-p ac-l-master-file))))
(defmacro ac-l-set-local-variable (var val)
(declare (indent 1))
`(unless (local-variable-p ',var)
(set (make-local-variable ',var) ,val)))
(defun ac-l-set-local-variables ()
(ac-l-set-local-variable ac-prefix-definitions
(append '((ac-l-argument . (ac-l-prefix-in-paren ac-l-argument-regexps))
(ac-l-file . (ac-l-prefix-in-paren ac-l-file-regexps))
(ac-l-label . (ac-l-prefix-in-paren ac-l-label-regexps))
(ac-l-bib . (ac-l-prefix-in-paren ac-l-bib-regexps)))
ac-prefix-definitions))
(ac-l-set-local-variable ac-source-files-in-current-dir
(append '((prefix . ac-l-file)
(symbol . "F"))
ac-source-files-in-current-dir)))
(defun* ac-l-user-sources-setup (&optional (sources ac-l-sources))
(dolist (source sources)
(ac-l-db-push source (if (assq 'prefix (symbol-value source))
'user-prefix-sources
'user-noprefix-sources))))
(defun ac-l-set-timers ()
(setq ac-l-update-timer (run-with-idle-timer ac-l-update-delay t 'ac-l-update-all)
ac-l-clear-timer (run-with-timer 600 600 'ac-l-clear)))
(defun ac-l-setup ()
"Set up Auto Complete LaTeX."
(let ((msg "Loading auto-complete-latex...")
(initial-p (not (ac-l-struct-master))))
(message "%s" msg)
(setq ac-l-major-mode major-mode)
(ac-l-set-local-variables)
(when initial-p
(ac-l-master-p)
(ac-l-basic-sources-setup)
(ac-l-user-sources-setup)
(ac-l-read-packages)
(ac-l-read-bibs)
(ac-l-make-source-from-dir)
(ac-l-set-help-doc)
(ac-l-set-sources)
(ac-l-set-timers))
(when (or initial-p (not ac-l-master-p))
(ac-l-update-all t))
(message "%sdone" msg)))
(provide 'auto-complete-latex)
;;; auto-complete-latex.el ends here | 8146 | ;;; emacs-auto-complete-latex.el --- A LaTeX extention for auto-complete-mode for Emacs
;; Copyright (C) 2016 tequilasunset
;; Author: tequilasunset <<EMAIL>> dawnxm <<EMAIL>>
;; Original Repository: http://bitbucket.org/tequilasunset/auto-complete-latex
;; Repository: https://github.com/dawnxm/emacs-auto-complete-latex
;; Keywords: emacs, completion, LaTeX
(defconst ac-l-version "0.2.5")
;;; Requirements:
;; auto-complete-mode: https://github.com/auto-complete/auto-complete
;;; Installation:
;; - Put files into load-path, and add the following into init file for emacs.
;;
;; (setq tab-always-indent 'complete)
;; (ac-set-trigger-key "TAB")
;; (add-to-list 'ac-modes 'latex-mode)
;; (setq ac-l-dict-directory "/path/to/ac-l-dict/")
;; (setq auto-mode-alist
;; (cons '("\\.tex\\'" . latex-mode)
;; auto-mode-alist))
;; (add-hook 'latex-mode-hook 'ac-l-setup)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup)
;;
;; - If you get the error below
;;
;; `variable binding depth exceeds max-specpdl-size',
;;
;; add the following into init file.
;;
;; (setq max-specpdl-size (+ 500 max-specpdl-size))
;;; Commentary:
;; - Customize group:
;;
;; M-x customize-group RET auto-complete-latex RET
;;
;; - Don't use ac-sources:
;;
;; Use `ac-l-sources' instead.
;;
;; - Examples of configuration:
;;
;; * Setup for AUCTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'latex-mode)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup))
;;
;; * Setup for YaTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'yatex-mode)
;; (add-hook 'yatex-mode-hook 'ac-l-setup))
;;
;; If you want to use command help in Japanese, put
;; YATEXHLP.jp into ac-l-dict.
;;
;; - ac-l-dict:
;;
;; Files in it become sources, etc. Files are classified like below.
;; If there are unnecessary files, remove them.
;;
;; 1. Basic files
;;
;; basic-commands, basic-arguments, macro, latex-dot-ltx,
;; platex-commands, platex-arguments, primitives,
;; ptex-primitives
;;
;; Keywords in these files become candidates for basic sources.
;;
;; 2. User files
;;
;; user-commands, user-arguments
;;
;; These files become user sources.
;;
;; 3. Help file
;;
;; latex-help
;;
;; This file become a LaTeX command help.
;;
;; 4. External package files
;;
;; Files other than above become package sources. the
;; form is NAME-TYPE-SYMBOL-REQUIRES.
;;
;; NAME Package or class file name. You can set the
;; dependence with using `ac-l-package-dependences'.
;; TYPE `c' (command) or `a' (argument).
;; SYMBOL Symbol property. `*' => `p'.
;; REQUIRES Requires property. `*' => not set.
;;
;; - Commands that argument completion will work:
;;
;; `ac-l-argument-regexps'
;; `ac-l-file-regexps'
;; `ac-l-label-regexps'
;; `ac-l-bib-regexps'
;;
;; Above are related variables. If you want to complete label
;; names in argument of `\foo', write the following into init file.
;;
;; (add-to-list 'ac-l-label-regexps "foo")
;;
;; - Completion at point:
;;
;; Two commands `ac-l-complete-labels' and `ac-l-complete-bibs'
;; are provided to complete at point.
;;
;; - A table of symbol properties:
;;
;; SYMBOL | MEANING
;; --------+----------------------------------
;; l | LaTeX or pLaTeX
;; a | AMS packages
;; b | beamer
;; h | hyperlinks
;; g | graphics
;; m | math sign or equations
;; c | colors
;; t | tables
;; f | fonts
;; p | unclassified external packages
;; F | file names in a current directory
;; L | label names
;; B | bib keys
;; u | user-commands or user-arguments
;;
;; - Startup improvement:
;;
;; In case you use `ac-l-master-file', `ac-l-package-files' or
;; `ac-l-bib-files', startup will be slower. If you are using
;; ac-l-package-files, you can improve it with using the command
;; `ac-l-write-package-files'.
;;; Code:
(require 'cl)
(require 'auto-complete)
(defgroup auto-complete-latex nil
"Auto completion of LaTeX keywords."
:group 'auto-complete
:group 'tex
:prefix "ac-l-")
;;;; variables
(defcustom ac-l-update-delay 0.8
"Delay to update candidates."
:type 'float
:group 'auto-complete-latex)
(defcustom ac-l-master-file nil
"Specify LaTeX master file path as string.
Parse master file's \\input and \\include(only).
Then create candidates from master file and parsed files."
:type 'string
:group 'auto-complete-latex)
(defvaralias 'ac-l-target 'ac-l-master-file)
(defcustom ac-l-sources nil
"A list of user sources.
This is similar to `ac-sources', but you don't have to add
`ac-l-source-*' and below sources.
ac-source-dictionary
ac-source-files-in-current-dir
ac-source-filename
ac-source-words-in-*"
:type '(repeat symbol)
:group 'auto-complete-latex)
(defcustom ac-l-package-files nil
"A list of package files (valid suffixes are .sty and .cls).
Parse LaTeX command definitions in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-bib-files nil
"A list of bib files (valid suffix is .bib).
Parse bibliography keys in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-use-word-completion nil
"If non-nil, use sources for normal word (text) completion."
:type 'boolean
:group 'auto-complete-latex)
;;; internal
(defvar ac-l-major-mode nil)
(defvar ac-l-master-p nil)
(defconst ac-l-command-prefix "\\\\\\([a-zA-Z@]+\\)")
(defvar ac-l-update-timer nil)
;;;; functions
;;; DB
;; package-cmds, package-args, cur-bib-tables, all-bib-tables, latex-cmds,
;; latex-args, package-sources, user-noprefix-sources, user-prefix-sources,
;; label-cands, bibitem-cands, bib-cands, filenames, label-tables, sources,
;; bibitem-tables, file-cmds, file-words, children,
(defconst ac-l-db (make-hash-table :test 'eq))
(defsubst ac-l-db-get (sym)
(gethash sym ac-l-db))
(defsubst ac-l-db-set (sym value)
(puthash sym value ac-l-db))
(defsubst ac-l-db-push (value sym)
(puthash sym (cons value (gethash sym ac-l-db)) ac-l-db))
(defsubst ac-l-db-append (sym lst)
(puthash sym (append (gethash sym ac-l-db) lst) ac-l-db))
;;; prefixes for arguments
(defcustom ac-l-argument-regexps
'("\\(?:usep\\|RequireP\\)ackage" "documentclass" "begin" "end" "fnsymbol"
"\\(?:this\\)?pagestyle" "bibliography\\(?:style\\)?" "pagenumbering"
"\\(?:new\\|addto\\|set\\)counter" "[aA]lph" "arabic" "[rR]oman"
"@\\(?:addtoreset\\|startsection\\|namedef\\|definecounter\\)"
"addcontentsline" "numberwithin" "\\(?:text\\|page\\|f\\|define\\)color"
"colorbox" "\\(?:column\\|row\\|cell\\|arrayrule\\|doublerulesep\\)color"
"hypersetup" "include\\(?:graphics\\|slide\\)" "insert[a-z]+" "frame"
"lst[a-zDIMS]+" "resetcount\\(?:er\\)?onoverlays" "tableofcontents"
"movie" "hyperlink\\(?:movie\\|sound\\)" "multiinclude" "sound" "note"
"trans[a-z]+" "use[a-z]*theme" "[a-z]+beamertemplate[a-z]*"
"\\(?:use\\|set\\)beamer\\(?:color\\|font\\|covered\\)")
"A list of regexps to match commands which take arguments."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-file-regexps
'("include\\(?:only\\|graphics\\)?" "input" "hypersetup")
"A list of regexps to match commands which take file name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-label-regexps
'("\\(?:page\\|auto\\|eq\\)?ref" "label")
"A list of regexps to match commands which take label name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-bib-regexps
'("\\(?:no\\|short\\)?cite[a-zA-Z]*" "bibitem")
"A list of regexps to match commands which take bibliography argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defun ac-l-prefix-in-paren (regexps)
;; This doesn't work as omni completion because the return is ac-point.
(if (save-excursion
(re-search-backward
(concat "\\\\\\("
(mapconcat 'identity regexps "\\|")
"\\)\\*?\\(\\s([^]>}]*\\s)\\)*\\(\\s([^]>}]*\\)\\=") nil t))
ac-point))
;;; read file data
(defsubst ac-l-convert-filename-to-file (filename)
;; faster than file-name-sans-extension
(let ((nodir (file-name-nondirectory filename)))
(if (string-match "\\(.+\\)\\.[^.]*$" nodir)
(match-string 1 nodir)
nodir)))
(defun* ac-l-read-bibs
(&key (files ac-l-bib-files)
(regexp "^@[^{@]+{\\([^ =,\t\n]*\\),\n[^@]+\\(^}\\)"))
"Convert each bib file listed in FILES to a hash table."
(dolist (filename files)
(let* ((file (ac-l-convert-filename-to-file filename))
(table (make-hash-table :test 'equal)))
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward regexp nil t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table))))
(ac-l-db-push (cons file table) 'all-bib-tables)
(ac-l-db-push file 'filenames))))
;; k -> package name in `ac-l-package-files', v -> [cmds args]
(defconst ac-l-packages (make-hash-table :test 'equal))
(defun* ac-l-read-packages
(&key (files ac-l-package-files)
(cmd-re "\\\\\\(?:[a-z@]*def\\|let\\|new[a-z]+\\|providecommand\\|Declare[a-zA-Z@]+\\)\\*?[ \t]*{?\\\\\\([a-zA-Z]+\\)}?[ =\\#[{]")
(arg-re "\\\\\\(?:DeclareOption[a-zA-Z]*\\|new[a-z]+\\|@definecounter\\)\\*?[ \t]*{\\([a-zA-Z]+\\)}"))
"Convert each package listed in FILES to an element of `ac-l-packages'."
(dolist (filename files)
(let ((file (ac-l-convert-filename-to-file filename))
cand cmds args)
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward cmd-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand cmds)
(push cand cmds)))
(goto-char (point-min))
(while (re-search-forward arg-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand args)
(push cand args)))))
(puthash file (vector cmds args) ac-l-packages)
(ac-l-db-push file 'filenames))))
(defcustom ac-l-dict-directory "~/.emacs.d/ac-l-dict/"
"Path of the ac-l-dict."
:type 'string
:group 'auto-complete-latex)
(defun ac-l-write-package-files (dir)
"Output candidates collected from files listed in `ac-l-package-files'.
You can use them in the ac-l-dict."
(interactive (list (read-directory-name "Dir: " ac-l-dict-directory nil t)))
(maphash (lambda (k v)
(loop for (type cands) in `((c ,(aref v 0)) (a ,(aref v 1)))
when cands do
(with-temp-buffer
(insert (mapconcat 'identity (sort cands #'string<) "\n"))
(write-region (point-min) (point-max)
(format "%s%s-%s-*-*" dir k type)))))
ac-l-packages))
(defcustom ac-l-package-dependences
'(("hyperref" . "beamer")
("color" . "colortbl\\|beamer")
("array" . "tabularx\\|colortbl"))
"Alist of external package dependences.
Each element is the form (REQUIRED PACKAGE . PACKAGES). Package and
class files are treated equivalently. This is effective only for
files read from the ac-l-dict."
:type '(repeat (cons string regexp))
:group 'auto-complete-latex)
(defun* ac-l-set-help-doc
(&optional (sources '(ac-l-source-latex-commands
ac-l-source-latex-arguments)))
"Set document property to each source listed in SOURCES."
(let* ((files (directory-files ac-l-dict-directory))
(help-fn (cond
((member "YATEXHLP.jp" files)
;; `Warning: defvar ignored because kinsoku-limit is let-bound'.
(load "international/kinsoku")
'ac-l-yatex-jp-documentation)
((member "latex-help" files)
'ac-l-latex2e-documentation))))
(when help-fn
(dolist (source sources)
(push (cons 'document help-fn) (symbol-value source))))))
(defun ac-l-make-source-from-dir ()
(dolist (file (directory-files ac-l-dict-directory nil "^[^.]"))
(let ((sym "p")
(prx ac-l-command-prefix)
source package req)
;; parse file name
(cond
((string-match "^\\([^-]+\\)-\\([^-]\\)-\\([^-]\\)-\\([^-]\\)$" file)
(let* ((n (match-string 1 file))
(T (match-string 2 file))
(s (match-string 3 file))
(r (match-string 4 file))
(d (assoc-default n ac-l-package-dependences 'string=))
(filenames (ac-l-db-get 'filenames)))
(unless (member n filenames)
(ac-l-db-set 'filenames (cons n filenames)))
(if d (setq package (concat n "\\|" d)) (setq package n))
(unless (string= s "*") (setq sym s))
(unless (string= r "*") (setq req (string-to-number r)))
(if (string= T "a")
(setq prx 'ac-l-argument
source (intern (format "ac-l-source-%s-arguments" n)))
(setq source (intern (format "ac-l-source-%s-commands" n))))))
((or (string= "macro" file)
(string= "latex-dot-ltx" file)
(string-match "^\\(ptex-\\)?primitives$" file)
(string-match "^\\(basic\\|platex\\)-commands$" file))
(setq source 'latex-cmd))
((string-match "^\\(basic\\|platex\\)-arguments$" file)
(setq source 'latex-arg))
((cond ((string= "user-commands" file) t)
((string= "user-arguments" file) (setq prx 'ac-l-argument)))
(setq sym "u"
source (intern (concat "ac-l-source-" file)))))
;; read file contents
(when source
(let ((cands (with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory file))
(split-string (buffer-string) "\n"))))
(case source
(latex-cmd (ac-l-db-append 'latex-cmds cands))
(latex-arg (ac-l-db-append 'latex-args cands))
(otherwise
(set source (delq nil `(,(if package `(ac-l-package . ,package))
,(if (integerp req) `(requires . ,req))
(symbol . ,sym)
(prefix . ,prx)
(candidates . ',cands))))
(cond (package
(ac-l-db-push source 'package-sources))
((string= sym "u")
(ac-l-db-push source 'user-prefix-sources))))))))))
;;; update file's info
(defstruct ac-l-info
"Information about each tex file."
modification words commands packages labels bibitems bibs)
;; k -> filename (full path), v -> struct
(defconst ac-l-structs (make-hash-table :test 'equal))
(defconst ac-l-children (make-hash-table :test 'equal))
(defsubst ac-l-split-string (str)
(split-string str "\\([ \t\n]\\|%.*\n\\|,\\)+" t))
(defsubst ac-l-candidates-hash (regexp table beg end)
(goto-char beg)
(while (re-search-forward regexp end t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table)
(goto-char (1+ (match-beginning 0)))))
(defun ac-l-make-info (struct filename &optional master)
(let* ((word-re "[^\\,]\\(\\<[-'a-zA-Z]+\\>\\)")
(package-re "^[^%\n]*\\\\\\(?:\\(?:usep\\|RequireP\\)ackage\\|documentclass\\)\\(?:\\[[^]]*\\]\\)?{\\([^}]+\\)")
(lines ".*\n.*\n.*\n")
(label-re "\\\\label{\\(\\(?:[^ }\t\n]\\)+\\)}")
(label-re1 (concat "^[^%\n]*" label-re ".*$"))
(label-re2 (concat "^" lines "[^%\n]*" label-re lines ".*$"))
(bibitem-re "^[^%\n]*\\\\bibitem\\(?:\\[[^]]*\\]\\)?{\\(\\(?:[^ }\t\n]\\)+\\)}[^\\]*")
(bib-re "^[^%\n]*\\\\bibliography{\\([^}]+\\)")
(collect-p (not (or master (buffer-file-name))))
(beg (point-min))
(label-beg (save-excursion
(goto-char beg)
(forward-line 3)
(point)))
(label-end (save-excursion
(goto-char (point-max))
(forward-line -3)
(point)))
(label-ht (or (ignore-errors (clrhash (ac-l-info-labels struct)))
(make-hash-table :test 'equal)))
(bibitem-ht (or (ignore-errors (clrhash (ac-l-info-bibitems struct)))
(make-hash-table :test 'equal)))
(i 0)
words commands packages bibs cand)
(save-excursion
(when (and ac-l-use-word-completion collect-p)
(goto-char beg)
(while (and (re-search-forward word-re nil t) (<= i 100))
(setq cand (match-string-no-properties 1))
(when (and (not (member cand words))
(>= (length cand) 3))
(push cand words)
(incf i))))
(when collect-p
(let ((latex-cmds (ac-l-db-get 'latex-cmds)))
(goto-char beg)
(while (re-search-forward ac-l-command-prefix nil t)
(setq cand (match-string-no-properties 1))
(unless (or (member cand commands)
(member cand latex-cmds))
(push cand commands)))))
(when master
(goto-char beg)
(while (re-search-forward package-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name packages)
(push name packages)))))
(ac-l-candidates-hash label-re1 label-ht beg label-beg)
(ac-l-candidates-hash label-re2 label-ht beg nil)
(ac-l-candidates-hash label-re1 label-ht label-end nil)
(ac-l-candidates-hash bibitem-re bibitem-ht beg nil)
(when ac-l-bib-files
(goto-char beg)
(while (re-search-forward bib-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name bibs)
(push name bibs))))))
(puthash filename
(make-ac-l-info
:modification (ignore-errors (nth 5 (file-attributes filename)))
:words words
:commands commands
:packages packages
:labels label-ht
:bibitems bibitem-ht
:bibs bibs)
ac-l-structs)))
(defsubst ac-l-struct-master ()
(gethash ac-l-master-file ac-l-structs))
(defsubst ac-l-all-structs ()
(delq t (append (loop for v being the hash-values in ac-l-children collect v)
(list (ac-l-struct-master)))))
(defsubst ac-l-append-info (info-fn)
(apply 'append (mapcar info-fn (ac-l-all-structs))))
(defsubst ac-l-convert-file-to-filename (file base-dir suffix)
;; FILE -> BASE-DIR/FILE.SUFFIX
(let ((path (expand-file-name file base-dir)))
(concat (if (string-match "^\\(.+\\)\\.[^./]+$" path)
(match-string 1 path)
path)
"." suffix)))
(defun ac-l-update-children-names ()
;; parse file names in master and push them into DB
(let* ((beg-re "^[^%\n]*\\\\\\(?:")
(end-re "\\)[ {\t]+\\([^ }%\n]+\\)")
(regexp (concat beg-re "in\\(?:put\\|clude\\)" end-re))
(beg (point-min))
(dir (if (string-match "^\\(.+/\\).+$" ac-l-master-file)
(match-string 1 ac-l-master-file)
"/"))
names)
(save-excursion
(goto-char beg)
(when (re-search-forward (concat beg-re "includeonly" end-re) nil t)
(setq names (ac-l-split-string (match-string-no-properties 1))
regexp (concat beg-re "input" end-re)))
(goto-char beg)
(setq names (append names
(loop while (re-search-forward regexp nil t)
collect (match-string-no-properties 1)))))
(ac-l-db-set 'children
(loop for name in names
for filename = (ac-l-convert-file-to-filename name dir "tex")
if (file-exists-p filename)
collect filename))))
(defun ac-l-update-children (filenames)
(clrhash ac-l-children)
(dolist (filename filenames)
;; If struct is undefined, put t.
(puthash filename (or (gethash filename ac-l-structs) t) ac-l-children))
ac-l-children)
(defsubst ac-l-file-mod-p (struct filename)
(not (equal (ac-l-info-modification struct)
(nth 5 (file-attributes filename)))))
(defsubst ac-l-update-master-info ()
(ac-l-make-info (ac-l-struct-master) ac-l-master-file t))
(defun ac-l-update-info (&optional force)
"If necessary, update file's info."
(if ac-l-master-p
(let ((master-mod-p (or force (ac-l-file-mod-p (ac-l-struct-master) ac-l-master-file)))
(buf-list (buffer-list)))
;; master
(or (loop with master = (expand-file-name ac-l-master-file)
for buf in buf-list
if (string= master (buffer-file-name buf))
do (when (or (buffer-modified-p buf) master-mod-p)
(with-current-buffer buf
(ac-l-update-children-names)
(ac-l-update-master-info)))
and return t)
(when master-mod-p
(with-temp-buffer
(insert-file-contents ac-l-master-file)
(ac-l-update-children-names)
(ac-l-update-master-info))))
;; children
(let* ((filenames (ac-l-db-get 'children))
(table (ac-l-update-children filenames)))
(dolist (buf buf-list)
(let* ((filename (buffer-file-name buf))
(struct (gethash filename table)))
(when (and struct
(or (not (ac-l-info-p struct))
(buffer-modified-p buf)
(ac-l-file-mod-p struct filename)))
(with-current-buffer buf
(ac-l-make-info struct filename))
(remhash filename table))))
(maphash (lambda (filename struct)
(when (or (not (ac-l-info-p struct))
(ac-l-file-mod-p struct filename))
(with-temp-buffer
(insert-file-contents filename)
(ac-l-make-info struct filename))))
table)
(ac-l-update-children filenames)))
(when (or force (buffer-modified-p))
(ac-l-update-master-info))))
(defun ac-l-update ()
"Update `ac-sources' according to packages."
(ac-l-db-set 'package-cmds nil)
(ac-l-db-set 'package-args nil)
(let ((sources (ac-l-db-get 'sources))
cmd-sources arg-sources)
(dolist (name (ac-l-info-packages (ac-l-struct-master)))
;; sources
(dolist (source (ac-l-db-get 'package-sources))
(let* ((alist (symbol-value source))
(package (cdr (assq 'ac-l-package alist)))
(prefix (cdr (assq 'prefix alist))))
(when (string-match package name)
(cond
((string= prefix ac-l-command-prefix)
(unless (memq source cmd-sources)
(push source cmd-sources)))
((eq prefix 'ac-l-argument)
(unless (memq source arg-sources)
(push source arg-sources)))))))
;; candidates
(let* ((vec (or (gethash name ac-l-packages) '[nil nil]))
(cmd (aref vec 0))
(arg (aref vec 1)))
(if cmd (ac-l-db-append 'package-cmds cmd))
(if arg (ac-l-db-append 'package-args arg))))
(setq ac-sources (append (ac-l-db-get 'user-prefix-sources)
(nth 0 sources)
cmd-sources
(nth 1 sources)
arg-sources
(nth 2 sources)
(ac-l-db-get 'user-noprefix-sources)
(nth 3 sources)))))
(defun ac-l-set-sources ()
(let ((s0 `(ac-source-filename
ac-l-source-labels
ac-l-source-bibitems
,(if ac-l-bib-files 'ac-l-source-bibliographies)
,(if (ac-l-db-get 'latex-cmds) 'ac-l-source-latex-commands)))
(s1 `(,(if ac-l-package-files 'ac-l-source-package-commands)
ac-l-source-commands
ac-source-files-in-current-dir
,(if (ac-l-db-get 'latex-args) 'ac-l-source-latex-arguments)))
(s2 `(,(if ac-l-package-files 'ac-l-source-package-arguments)
,(if (ac-l-db-get 'filenames) 'ac-l-source-filenames)))
(s3 `(,(if ac-l-use-word-completion 'ac-l-source-words)
ac-source-dictionary)))
(ac-l-db-set 'sources
(mapcar (lambda (s) (delq nil s)) (list s0 s1 s2 s3)))))
;;; candidate
;; copied from auto-complete.el and added arguments
(defun ac-l-candidate (beg-re end-re)
(let ((i 0)
(regexp (concat beg-re (regexp-quote ac-prefix) end-re))
cand cands)
(save-excursion
;; Search backward
(goto-char ac-point)
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-backward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i)))
;; Search backward
(goto-char (+ ac-point (length ac-prefix)))
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-forward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i))))
(nreverse cands)))
(defun ac-l-incremental-update-index (idx cand-fn)
(let ((pair (symbol-value idx))
(ac-limit (or (and (integerp ac-limit) ac-limit) 10)))
(when (null pair)
(set idx (cons nil nil)))
;; Mark incomplete
(when (car pair)
(setcar pair nil))
(let ((list (cdr pair))
(words (funcall cand-fn)))
(dolist (word words)
(unless (member word list)
(push word list)
(setcdr pair list))))))
(defun ac-l-update-index (idx cand-fn)
(dolist (buf (buffer-list))
(when (and (eq ac-l-major-mode (buffer-local-value 'major-mode buf))
(or ac-fuzzy-enable
(not (eq buf (current-buffer)))))
(with-current-buffer buf
(when (and (not (car (symbol-value idx)))
(< (buffer-size) 1048576))
;; Complete index
(set idx (cons t (let ((ac-point (point-min))
(ac-prefix "")
ac-limit)
(funcall cand-fn)))))))))
(defun ac-l-candidates (idx cand-fn)
(loop initially (unless ac-fuzzy-enable
(ac-l-incremental-update-index idx cand-fn))
for buf in (buffer-list)
if (and (or (not (integerp ac-limit)) (< (length cands) ac-limit))
(derived-mode-p (buffer-local-value 'major-mode buf)))
append (funcall ac-match-function ac-prefix
(cdr (buffer-local-value idx buf)))
into cands
finally return cands))
;;;; sources
(defvar ac-l-word-index nil)
(make-variable-buffer-local 'ac-l-word-index)
(defun ac-l-smart-capitalize ()
;; Meadow/Emacs memo: http://www.bookshelf.jp/soft/meadow_34.html#SEC495
(when (and (looking-back "[[:space:][:cntrl:]]+[a-z']+")
(= (point) (save-excursion
(backward-sentence)
(forward-word)
(point))))
(capitalize-word -1)))
(defun ac-l-candidate-words-in-buffer ()
(ac-l-candidate "[^\\,]\\(\\<" "[-'a-zA-Z]+\\>\\)"))
(defvar ac-l-source-words
'((action . ac-l-smart-capitalize)
(requires . 3)))
(defvar ac-l-command-index nil)
(make-variable-buffer-local 'ac-l-command-index)
(defun ac-l-candidate-commands-in-buffer ()
(ac-l-candidate "\\\\\\(" "[a-zA-Z@]+\\)"))
(defvar ac-l-source-commands
`((prefix . ,ac-l-command-prefix)))
(defun ac-l-basic-sources-setup ()
;; Add properties into basic sources.
;; The sources work like ac-source-words-in-same-mode-buffers.
(let* ((cw-fn 'ac-l-candidate-words-in-buffer)
(cc-fn 'ac-l-candidate-commands-in-buffer)
(wc `(ac-l-candidates 'ac-l-word-index ',cw-fn))
(cc `(ac-l-candidates 'ac-l-command-index ',cc-fn))
(wi `(ac-l-update-index 'ac-l-word-index ',cw-fn))
(ci `(ac-l-update-index 'ac-l-command-index ',cc-fn)))
(labels ((pushprops (p1 p2 p3 p4)
(push `(candidates . ,p1) ac-l-source-words)
(push `(candidates . ,p2) ac-l-source-commands)
(push `(init . ,p3) ac-l-source-words)
(push `(init . ,p4) ac-l-source-commands)))
(if ac-l-master-p
;; add functions for file's candidates
(pushprops `(append ,wc (ac-l-db-get 'file-words))
`(append ,cc (ac-l-db-get 'file-cmds))
`(lambda ()
,wi
(ac-l-db-set 'file-words
(ac-l-append-info 'ac-l-info-words)))
`(lambda ()
,ci
(ac-l-db-set 'file-cmds
(ac-l-append-info 'ac-l-info-commands))))
(pushprops wc cc wi ci)))))
(defvar ac-l-source-latex-commands
`((candidates . (ac-l-db-get 'latex-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "l")))
(defvar ac-l-source-latex-arguments
`((candidates . (ac-l-db-get 'latex-args))
(prefix . ac-l-argument)
(symbol . "l")))
(defvar ac-l-source-filenames
'((candidates . (ac-l-db-get 'filenames))
(prefix . ac-l-argument))
"Source for package and bib file names.")
(defvar ac-l-source-package-commands
`((candidates . (ac-l-db-get 'package-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "p")))
(defvar ac-l-source-package-arguments
'((candidates . (ac-l-db-get 'package-args))
(prefix . ac-l-argument)
(symbol . "p")))
(defsubst ac-l-gethash (key tables)
(loop for table in tables thereis (gethash key table)))
(defsubst ac-l-append-keys (tables)
(apply 'append (mapcar (lambda (table)
(loop for k being the hash-keys in table collect k))
tables)))
(defun ac-l-update-labels ()
(let ((it (ac-l-db-set 'label-tables
(mapcar 'ac-l-info-labels (ac-l-all-structs)))))
(ac-l-db-set 'label-cands (ac-l-append-keys it))))
(defvar ac-l-source-labels
'((init . ac-l-update-labels)
(candidates . (ac-l-db-get 'label-cands))
(prefix . ac-l-label)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'label-tables))))
(symbol . "L")))
(defun ac-l-complete-labels ()
"Start label name completion at point."
(interactive)
(auto-complete (list (remove '(prefix . ac-l-label) ac-l-source-labels))))
(defun ac-l-update-bibitems ()
(let ((it (ac-l-db-set 'bibitem-tables
(mapcar 'ac-l-info-bibitems (ac-l-all-structs)))))
(ac-l-db-set 'bibitem-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibitems
'((init . ac-l-update-bibitems)
(candidates . (ac-l-db-get 'bibitem-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'bibitem-tables))))
(symbol . "B")))
(defun ac-l-update-bib ()
(let ((it (ac-l-db-set 'cur-bib-tables
(loop with tables = (ac-l-db-get 'all-bib-tables)
for name in (ac-l-append-info 'ac-l-info-bibs)
if (assoc-default name tables 'string=)
collect it))))
(ac-l-db-set 'bib-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibliographies
'((init . ac-l-update-bib)
(candidates . (ac-l-db-get 'bib-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'cur-bib-tables))))
(symbol . "B")))
(defun ac-l-complete-bibs ()
"Start bibliography completion at point."
(interactive)
(auto-complete `(,(remove '(prefix . ac-l-bib) ac-l-source-bibitems)
,(remove '(prefix . ac-l-bib) ac-l-source-bibliographies))))
;;; help
(defconst ac-l-help (make-hash-table :test 'equal))
(defmacro ac-l-define-help-doc (name file beg-re end-re)
(declare (indent 1))
`(defun ,(intern (format "ac-l-%s-documentation" name)) (str)
(or (gethash str ac-l-help)
(unless (string-match "@" str)
(with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory ,file))
(if (re-search-forward (concat ,beg-re str ,end-re) nil t)
(puthash str (match-string-no-properties 1) ac-l-help)
(puthash str t ac-l-help)))))))
(ac-l-define-help-doc latex2e
"latex-help"
"\\(?:\f\n\\)\\([^\f]*\\(?:^[`\\]"
"\\(?:\\s(\\|[ '\n]\\)[^\f]+\\)\\)")
(ac-l-define-help-doc yatex-jp
"YATEXHLP.jp"
"^\\(\\\\?"
"\n[^]+\\)")
;;;; clear
(defvar ac-l-clear-timer nil)
(defun ac-l-clear ()
(clrhash ac-l-help))
(defun* ac-l-cancel-timers
(&optional (timers '(ac-l-update-timer
ac-l-clear-timer)))
(interactive)
(dolist (timer timers)
(let ((val (symbol-value timer)))
(when (timerp val)
(cancel-timer val)
(set timer nil)))))
;;;; setup
(defun ac-l-update-all (&optional force)
(when (eq ac-l-major-mode major-mode)
(ac-l-update-info force)
(ac-l-update)))
(defun ac-l-master-p ()
(setq ac-l-master-p (and (stringp ac-l-master-file)
(file-exists-p ac-l-master-file))))
(defmacro ac-l-set-local-variable (var val)
(declare (indent 1))
`(unless (local-variable-p ',var)
(set (make-local-variable ',var) ,val)))
(defun ac-l-set-local-variables ()
(ac-l-set-local-variable ac-prefix-definitions
(append '((ac-l-argument . (ac-l-prefix-in-paren ac-l-argument-regexps))
(ac-l-file . (ac-l-prefix-in-paren ac-l-file-regexps))
(ac-l-label . (ac-l-prefix-in-paren ac-l-label-regexps))
(ac-l-bib . (ac-l-prefix-in-paren ac-l-bib-regexps)))
ac-prefix-definitions))
(ac-l-set-local-variable ac-source-files-in-current-dir
(append '((prefix . ac-l-file)
(symbol . "F"))
ac-source-files-in-current-dir)))
(defun* ac-l-user-sources-setup (&optional (sources ac-l-sources))
(dolist (source sources)
(ac-l-db-push source (if (assq 'prefix (symbol-value source))
'user-prefix-sources
'user-noprefix-sources))))
(defun ac-l-set-timers ()
(setq ac-l-update-timer (run-with-idle-timer ac-l-update-delay t 'ac-l-update-all)
ac-l-clear-timer (run-with-timer 600 600 'ac-l-clear)))
(defun ac-l-setup ()
"Set up Auto Complete LaTeX."
(let ((msg "Loading auto-complete-latex...")
(initial-p (not (ac-l-struct-master))))
(message "%s" msg)
(setq ac-l-major-mode major-mode)
(ac-l-set-local-variables)
(when initial-p
(ac-l-master-p)
(ac-l-basic-sources-setup)
(ac-l-user-sources-setup)
(ac-l-read-packages)
(ac-l-read-bibs)
(ac-l-make-source-from-dir)
(ac-l-set-help-doc)
(ac-l-set-sources)
(ac-l-set-timers))
(when (or initial-p (not ac-l-master-p))
(ac-l-update-all t))
(message "%sdone" msg)))
(provide 'auto-complete-latex)
;;; auto-complete-latex.el ends here | true | ;;; emacs-auto-complete-latex.el --- A LaTeX extention for auto-complete-mode for Emacs
;; Copyright (C) 2016 tequilasunset
;; Author: tequilasunset <PI:EMAIL:<EMAIL>END_PI> dawnxm <PI:EMAIL:<EMAIL>END_PI>
;; Original Repository: http://bitbucket.org/tequilasunset/auto-complete-latex
;; Repository: https://github.com/dawnxm/emacs-auto-complete-latex
;; Keywords: emacs, completion, LaTeX
(defconst ac-l-version "0.2.5")
;;; Requirements:
;; auto-complete-mode: https://github.com/auto-complete/auto-complete
;;; Installation:
;; - Put files into load-path, and add the following into init file for emacs.
;;
;; (setq tab-always-indent 'complete)
;; (ac-set-trigger-key "TAB")
;; (add-to-list 'ac-modes 'latex-mode)
;; (setq ac-l-dict-directory "/path/to/ac-l-dict/")
;; (setq auto-mode-alist
;; (cons '("\\.tex\\'" . latex-mode)
;; auto-mode-alist))
;; (add-hook 'latex-mode-hook 'ac-l-setup)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup)
;;
;; - If you get the error below
;;
;; `variable binding depth exceeds max-specpdl-size',
;;
;; add the following into init file.
;;
;; (setq max-specpdl-size (+ 500 max-specpdl-size))
;;; Commentary:
;; - Customize group:
;;
;; M-x customize-group RET auto-complete-latex RET
;;
;; - Don't use ac-sources:
;;
;; Use `ac-l-sources' instead.
;;
;; - Examples of configuration:
;;
;; * Setup for AUCTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'latex-mode)
;; (add-hook 'LaTeX-mode-hook 'ac-l-setup))
;;
;; * Setup for YaTeX
;;
;; (when (require 'auto-complete-latex nil t)
;; (setq ac-l-dict-directory "~/.emacs.d/ac-l-dict/")
;; (add-to-list 'ac-modes 'yatex-mode)
;; (add-hook 'yatex-mode-hook 'ac-l-setup))
;;
;; If you want to use command help in Japanese, put
;; YATEXHLP.jp into ac-l-dict.
;;
;; - ac-l-dict:
;;
;; Files in it become sources, etc. Files are classified like below.
;; If there are unnecessary files, remove them.
;;
;; 1. Basic files
;;
;; basic-commands, basic-arguments, macro, latex-dot-ltx,
;; platex-commands, platex-arguments, primitives,
;; ptex-primitives
;;
;; Keywords in these files become candidates for basic sources.
;;
;; 2. User files
;;
;; user-commands, user-arguments
;;
;; These files become user sources.
;;
;; 3. Help file
;;
;; latex-help
;;
;; This file become a LaTeX command help.
;;
;; 4. External package files
;;
;; Files other than above become package sources. the
;; form is NAME-TYPE-SYMBOL-REQUIRES.
;;
;; NAME Package or class file name. You can set the
;; dependence with using `ac-l-package-dependences'.
;; TYPE `c' (command) or `a' (argument).
;; SYMBOL Symbol property. `*' => `p'.
;; REQUIRES Requires property. `*' => not set.
;;
;; - Commands that argument completion will work:
;;
;; `ac-l-argument-regexps'
;; `ac-l-file-regexps'
;; `ac-l-label-regexps'
;; `ac-l-bib-regexps'
;;
;; Above are related variables. If you want to complete label
;; names in argument of `\foo', write the following into init file.
;;
;; (add-to-list 'ac-l-label-regexps "foo")
;;
;; - Completion at point:
;;
;; Two commands `ac-l-complete-labels' and `ac-l-complete-bibs'
;; are provided to complete at point.
;;
;; - A table of symbol properties:
;;
;; SYMBOL | MEANING
;; --------+----------------------------------
;; l | LaTeX or pLaTeX
;; a | AMS packages
;; b | beamer
;; h | hyperlinks
;; g | graphics
;; m | math sign or equations
;; c | colors
;; t | tables
;; f | fonts
;; p | unclassified external packages
;; F | file names in a current directory
;; L | label names
;; B | bib keys
;; u | user-commands or user-arguments
;;
;; - Startup improvement:
;;
;; In case you use `ac-l-master-file', `ac-l-package-files' or
;; `ac-l-bib-files', startup will be slower. If you are using
;; ac-l-package-files, you can improve it with using the command
;; `ac-l-write-package-files'.
;;; Code:
(require 'cl)
(require 'auto-complete)
(defgroup auto-complete-latex nil
"Auto completion of LaTeX keywords."
:group 'auto-complete
:group 'tex
:prefix "ac-l-")
;;;; variables
(defcustom ac-l-update-delay 0.8
"Delay to update candidates."
:type 'float
:group 'auto-complete-latex)
(defcustom ac-l-master-file nil
"Specify LaTeX master file path as string.
Parse master file's \\input and \\include(only).
Then create candidates from master file and parsed files."
:type 'string
:group 'auto-complete-latex)
(defvaralias 'ac-l-target 'ac-l-master-file)
(defcustom ac-l-sources nil
"A list of user sources.
This is similar to `ac-sources', but you don't have to add
`ac-l-source-*' and below sources.
ac-source-dictionary
ac-source-files-in-current-dir
ac-source-filename
ac-source-words-in-*"
:type '(repeat symbol)
:group 'auto-complete-latex)
(defcustom ac-l-package-files nil
"A list of package files (valid suffixes are .sty and .cls).
Parse LaTeX command definitions in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-bib-files nil
"A list of bib files (valid suffix is .bib).
Parse bibliography keys in them, and create candidates."
:type '(repeat string)
:group 'auto-complete-latex)
(defcustom ac-l-use-word-completion nil
"If non-nil, use sources for normal word (text) completion."
:type 'boolean
:group 'auto-complete-latex)
;;; internal
(defvar ac-l-major-mode nil)
(defvar ac-l-master-p nil)
(defconst ac-l-command-prefix "\\\\\\([a-zA-Z@]+\\)")
(defvar ac-l-update-timer nil)
;;;; functions
;;; DB
;; package-cmds, package-args, cur-bib-tables, all-bib-tables, latex-cmds,
;; latex-args, package-sources, user-noprefix-sources, user-prefix-sources,
;; label-cands, bibitem-cands, bib-cands, filenames, label-tables, sources,
;; bibitem-tables, file-cmds, file-words, children,
(defconst ac-l-db (make-hash-table :test 'eq))
(defsubst ac-l-db-get (sym)
(gethash sym ac-l-db))
(defsubst ac-l-db-set (sym value)
(puthash sym value ac-l-db))
(defsubst ac-l-db-push (value sym)
(puthash sym (cons value (gethash sym ac-l-db)) ac-l-db))
(defsubst ac-l-db-append (sym lst)
(puthash sym (append (gethash sym ac-l-db) lst) ac-l-db))
;;; prefixes for arguments
(defcustom ac-l-argument-regexps
'("\\(?:usep\\|RequireP\\)ackage" "documentclass" "begin" "end" "fnsymbol"
"\\(?:this\\)?pagestyle" "bibliography\\(?:style\\)?" "pagenumbering"
"\\(?:new\\|addto\\|set\\)counter" "[aA]lph" "arabic" "[rR]oman"
"@\\(?:addtoreset\\|startsection\\|namedef\\|definecounter\\)"
"addcontentsline" "numberwithin" "\\(?:text\\|page\\|f\\|define\\)color"
"colorbox" "\\(?:column\\|row\\|cell\\|arrayrule\\|doublerulesep\\)color"
"hypersetup" "include\\(?:graphics\\|slide\\)" "insert[a-z]+" "frame"
"lst[a-zDIMS]+" "resetcount\\(?:er\\)?onoverlays" "tableofcontents"
"movie" "hyperlink\\(?:movie\\|sound\\)" "multiinclude" "sound" "note"
"trans[a-z]+" "use[a-z]*theme" "[a-z]+beamertemplate[a-z]*"
"\\(?:use\\|set\\)beamer\\(?:color\\|font\\|covered\\)")
"A list of regexps to match commands which take arguments."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-file-regexps
'("include\\(?:only\\|graphics\\)?" "input" "hypersetup")
"A list of regexps to match commands which take file name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-label-regexps
'("\\(?:page\\|auto\\|eq\\)?ref" "label")
"A list of regexps to match commands which take label name argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defcustom ac-l-bib-regexps
'("\\(?:no\\|short\\)?cite[a-zA-Z]*" "bibitem")
"A list of regexps to match commands which take bibliography argument."
:type '(repeat regexp)
:group 'auto-complete-latex)
(defun ac-l-prefix-in-paren (regexps)
;; This doesn't work as omni completion because the return is ac-point.
(if (save-excursion
(re-search-backward
(concat "\\\\\\("
(mapconcat 'identity regexps "\\|")
"\\)\\*?\\(\\s([^]>}]*\\s)\\)*\\(\\s([^]>}]*\\)\\=") nil t))
ac-point))
;;; read file data
(defsubst ac-l-convert-filename-to-file (filename)
;; faster than file-name-sans-extension
(let ((nodir (file-name-nondirectory filename)))
(if (string-match "\\(.+\\)\\.[^.]*$" nodir)
(match-string 1 nodir)
nodir)))
(defun* ac-l-read-bibs
(&key (files ac-l-bib-files)
(regexp "^@[^{@]+{\\([^ =,\t\n]*\\),\n[^@]+\\(^}\\)"))
"Convert each bib file listed in FILES to a hash table."
(dolist (filename files)
(let* ((file (ac-l-convert-filename-to-file filename))
(table (make-hash-table :test 'equal)))
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward regexp nil t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table))))
(ac-l-db-push (cons file table) 'all-bib-tables)
(ac-l-db-push file 'filenames))))
;; k -> package name in `ac-l-package-files', v -> [cmds args]
(defconst ac-l-packages (make-hash-table :test 'equal))
(defun* ac-l-read-packages
(&key (files ac-l-package-files)
(cmd-re "\\\\\\(?:[a-z@]*def\\|let\\|new[a-z]+\\|providecommand\\|Declare[a-zA-Z@]+\\)\\*?[ \t]*{?\\\\\\([a-zA-Z]+\\)}?[ =\\#[{]")
(arg-re "\\\\\\(?:DeclareOption[a-zA-Z]*\\|new[a-z]+\\|@definecounter\\)\\*?[ \t]*{\\([a-zA-Z]+\\)}"))
"Convert each package listed in FILES to an element of `ac-l-packages'."
(dolist (filename files)
(let ((file (ac-l-convert-filename-to-file filename))
cand cmds args)
(ignore-errors
(with-temp-buffer
(insert-file-contents filename)
(while (re-search-forward cmd-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand cmds)
(push cand cmds)))
(goto-char (point-min))
(while (re-search-forward arg-re nil t)
(setq cand (match-string-no-properties 1))
(unless (member cand args)
(push cand args)))))
(puthash file (vector cmds args) ac-l-packages)
(ac-l-db-push file 'filenames))))
(defcustom ac-l-dict-directory "~/.emacs.d/ac-l-dict/"
"Path of the ac-l-dict."
:type 'string
:group 'auto-complete-latex)
(defun ac-l-write-package-files (dir)
"Output candidates collected from files listed in `ac-l-package-files'.
You can use them in the ac-l-dict."
(interactive (list (read-directory-name "Dir: " ac-l-dict-directory nil t)))
(maphash (lambda (k v)
(loop for (type cands) in `((c ,(aref v 0)) (a ,(aref v 1)))
when cands do
(with-temp-buffer
(insert (mapconcat 'identity (sort cands #'string<) "\n"))
(write-region (point-min) (point-max)
(format "%s%s-%s-*-*" dir k type)))))
ac-l-packages))
(defcustom ac-l-package-dependences
'(("hyperref" . "beamer")
("color" . "colortbl\\|beamer")
("array" . "tabularx\\|colortbl"))
"Alist of external package dependences.
Each element is the form (REQUIRED PACKAGE . PACKAGES). Package and
class files are treated equivalently. This is effective only for
files read from the ac-l-dict."
:type '(repeat (cons string regexp))
:group 'auto-complete-latex)
(defun* ac-l-set-help-doc
(&optional (sources '(ac-l-source-latex-commands
ac-l-source-latex-arguments)))
"Set document property to each source listed in SOURCES."
(let* ((files (directory-files ac-l-dict-directory))
(help-fn (cond
((member "YATEXHLP.jp" files)
;; `Warning: defvar ignored because kinsoku-limit is let-bound'.
(load "international/kinsoku")
'ac-l-yatex-jp-documentation)
((member "latex-help" files)
'ac-l-latex2e-documentation))))
(when help-fn
(dolist (source sources)
(push (cons 'document help-fn) (symbol-value source))))))
(defun ac-l-make-source-from-dir ()
(dolist (file (directory-files ac-l-dict-directory nil "^[^.]"))
(let ((sym "p")
(prx ac-l-command-prefix)
source package req)
;; parse file name
(cond
((string-match "^\\([^-]+\\)-\\([^-]\\)-\\([^-]\\)-\\([^-]\\)$" file)
(let* ((n (match-string 1 file))
(T (match-string 2 file))
(s (match-string 3 file))
(r (match-string 4 file))
(d (assoc-default n ac-l-package-dependences 'string=))
(filenames (ac-l-db-get 'filenames)))
(unless (member n filenames)
(ac-l-db-set 'filenames (cons n filenames)))
(if d (setq package (concat n "\\|" d)) (setq package n))
(unless (string= s "*") (setq sym s))
(unless (string= r "*") (setq req (string-to-number r)))
(if (string= T "a")
(setq prx 'ac-l-argument
source (intern (format "ac-l-source-%s-arguments" n)))
(setq source (intern (format "ac-l-source-%s-commands" n))))))
((or (string= "macro" file)
(string= "latex-dot-ltx" file)
(string-match "^\\(ptex-\\)?primitives$" file)
(string-match "^\\(basic\\|platex\\)-commands$" file))
(setq source 'latex-cmd))
((string-match "^\\(basic\\|platex\\)-arguments$" file)
(setq source 'latex-arg))
((cond ((string= "user-commands" file) t)
((string= "user-arguments" file) (setq prx 'ac-l-argument)))
(setq sym "u"
source (intern (concat "ac-l-source-" file)))))
;; read file contents
(when source
(let ((cands (with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory file))
(split-string (buffer-string) "\n"))))
(case source
(latex-cmd (ac-l-db-append 'latex-cmds cands))
(latex-arg (ac-l-db-append 'latex-args cands))
(otherwise
(set source (delq nil `(,(if package `(ac-l-package . ,package))
,(if (integerp req) `(requires . ,req))
(symbol . ,sym)
(prefix . ,prx)
(candidates . ',cands))))
(cond (package
(ac-l-db-push source 'package-sources))
((string= sym "u")
(ac-l-db-push source 'user-prefix-sources))))))))))
;;; update file's info
(defstruct ac-l-info
"Information about each tex file."
modification words commands packages labels bibitems bibs)
;; k -> filename (full path), v -> struct
(defconst ac-l-structs (make-hash-table :test 'equal))
(defconst ac-l-children (make-hash-table :test 'equal))
(defsubst ac-l-split-string (str)
(split-string str "\\([ \t\n]\\|%.*\n\\|,\\)+" t))
(defsubst ac-l-candidates-hash (regexp table beg end)
(goto-char beg)
(while (re-search-forward regexp end t)
(puthash (match-string-no-properties 1)
(match-string-no-properties 0)
table)
(goto-char (1+ (match-beginning 0)))))
(defun ac-l-make-info (struct filename &optional master)
(let* ((word-re "[^\\,]\\(\\<[-'a-zA-Z]+\\>\\)")
(package-re "^[^%\n]*\\\\\\(?:\\(?:usep\\|RequireP\\)ackage\\|documentclass\\)\\(?:\\[[^]]*\\]\\)?{\\([^}]+\\)")
(lines ".*\n.*\n.*\n")
(label-re "\\\\label{\\(\\(?:[^ }\t\n]\\)+\\)}")
(label-re1 (concat "^[^%\n]*" label-re ".*$"))
(label-re2 (concat "^" lines "[^%\n]*" label-re lines ".*$"))
(bibitem-re "^[^%\n]*\\\\bibitem\\(?:\\[[^]]*\\]\\)?{\\(\\(?:[^ }\t\n]\\)+\\)}[^\\]*")
(bib-re "^[^%\n]*\\\\bibliography{\\([^}]+\\)")
(collect-p (not (or master (buffer-file-name))))
(beg (point-min))
(label-beg (save-excursion
(goto-char beg)
(forward-line 3)
(point)))
(label-end (save-excursion
(goto-char (point-max))
(forward-line -3)
(point)))
(label-ht (or (ignore-errors (clrhash (ac-l-info-labels struct)))
(make-hash-table :test 'equal)))
(bibitem-ht (or (ignore-errors (clrhash (ac-l-info-bibitems struct)))
(make-hash-table :test 'equal)))
(i 0)
words commands packages bibs cand)
(save-excursion
(when (and ac-l-use-word-completion collect-p)
(goto-char beg)
(while (and (re-search-forward word-re nil t) (<= i 100))
(setq cand (match-string-no-properties 1))
(when (and (not (member cand words))
(>= (length cand) 3))
(push cand words)
(incf i))))
(when collect-p
(let ((latex-cmds (ac-l-db-get 'latex-cmds)))
(goto-char beg)
(while (re-search-forward ac-l-command-prefix nil t)
(setq cand (match-string-no-properties 1))
(unless (or (member cand commands)
(member cand latex-cmds))
(push cand commands)))))
(when master
(goto-char beg)
(while (re-search-forward package-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name packages)
(push name packages)))))
(ac-l-candidates-hash label-re1 label-ht beg label-beg)
(ac-l-candidates-hash label-re2 label-ht beg nil)
(ac-l-candidates-hash label-re1 label-ht label-end nil)
(ac-l-candidates-hash bibitem-re bibitem-ht beg nil)
(when ac-l-bib-files
(goto-char beg)
(while (re-search-forward bib-re nil t)
(dolist (name (ac-l-split-string (match-string-no-properties 1)))
(unless (member name bibs)
(push name bibs))))))
(puthash filename
(make-ac-l-info
:modification (ignore-errors (nth 5 (file-attributes filename)))
:words words
:commands commands
:packages packages
:labels label-ht
:bibitems bibitem-ht
:bibs bibs)
ac-l-structs)))
(defsubst ac-l-struct-master ()
(gethash ac-l-master-file ac-l-structs))
(defsubst ac-l-all-structs ()
(delq t (append (loop for v being the hash-values in ac-l-children collect v)
(list (ac-l-struct-master)))))
(defsubst ac-l-append-info (info-fn)
(apply 'append (mapcar info-fn (ac-l-all-structs))))
(defsubst ac-l-convert-file-to-filename (file base-dir suffix)
;; FILE -> BASE-DIR/FILE.SUFFIX
(let ((path (expand-file-name file base-dir)))
(concat (if (string-match "^\\(.+\\)\\.[^./]+$" path)
(match-string 1 path)
path)
"." suffix)))
(defun ac-l-update-children-names ()
;; parse file names in master and push them into DB
(let* ((beg-re "^[^%\n]*\\\\\\(?:")
(end-re "\\)[ {\t]+\\([^ }%\n]+\\)")
(regexp (concat beg-re "in\\(?:put\\|clude\\)" end-re))
(beg (point-min))
(dir (if (string-match "^\\(.+/\\).+$" ac-l-master-file)
(match-string 1 ac-l-master-file)
"/"))
names)
(save-excursion
(goto-char beg)
(when (re-search-forward (concat beg-re "includeonly" end-re) nil t)
(setq names (ac-l-split-string (match-string-no-properties 1))
regexp (concat beg-re "input" end-re)))
(goto-char beg)
(setq names (append names
(loop while (re-search-forward regexp nil t)
collect (match-string-no-properties 1)))))
(ac-l-db-set 'children
(loop for name in names
for filename = (ac-l-convert-file-to-filename name dir "tex")
if (file-exists-p filename)
collect filename))))
(defun ac-l-update-children (filenames)
(clrhash ac-l-children)
(dolist (filename filenames)
;; If struct is undefined, put t.
(puthash filename (or (gethash filename ac-l-structs) t) ac-l-children))
ac-l-children)
(defsubst ac-l-file-mod-p (struct filename)
(not (equal (ac-l-info-modification struct)
(nth 5 (file-attributes filename)))))
(defsubst ac-l-update-master-info ()
(ac-l-make-info (ac-l-struct-master) ac-l-master-file t))
(defun ac-l-update-info (&optional force)
"If necessary, update file's info."
(if ac-l-master-p
(let ((master-mod-p (or force (ac-l-file-mod-p (ac-l-struct-master) ac-l-master-file)))
(buf-list (buffer-list)))
;; master
(or (loop with master = (expand-file-name ac-l-master-file)
for buf in buf-list
if (string= master (buffer-file-name buf))
do (when (or (buffer-modified-p buf) master-mod-p)
(with-current-buffer buf
(ac-l-update-children-names)
(ac-l-update-master-info)))
and return t)
(when master-mod-p
(with-temp-buffer
(insert-file-contents ac-l-master-file)
(ac-l-update-children-names)
(ac-l-update-master-info))))
;; children
(let* ((filenames (ac-l-db-get 'children))
(table (ac-l-update-children filenames)))
(dolist (buf buf-list)
(let* ((filename (buffer-file-name buf))
(struct (gethash filename table)))
(when (and struct
(or (not (ac-l-info-p struct))
(buffer-modified-p buf)
(ac-l-file-mod-p struct filename)))
(with-current-buffer buf
(ac-l-make-info struct filename))
(remhash filename table))))
(maphash (lambda (filename struct)
(when (or (not (ac-l-info-p struct))
(ac-l-file-mod-p struct filename))
(with-temp-buffer
(insert-file-contents filename)
(ac-l-make-info struct filename))))
table)
(ac-l-update-children filenames)))
(when (or force (buffer-modified-p))
(ac-l-update-master-info))))
(defun ac-l-update ()
"Update `ac-sources' according to packages."
(ac-l-db-set 'package-cmds nil)
(ac-l-db-set 'package-args nil)
(let ((sources (ac-l-db-get 'sources))
cmd-sources arg-sources)
(dolist (name (ac-l-info-packages (ac-l-struct-master)))
;; sources
(dolist (source (ac-l-db-get 'package-sources))
(let* ((alist (symbol-value source))
(package (cdr (assq 'ac-l-package alist)))
(prefix (cdr (assq 'prefix alist))))
(when (string-match package name)
(cond
((string= prefix ac-l-command-prefix)
(unless (memq source cmd-sources)
(push source cmd-sources)))
((eq prefix 'ac-l-argument)
(unless (memq source arg-sources)
(push source arg-sources)))))))
;; candidates
(let* ((vec (or (gethash name ac-l-packages) '[nil nil]))
(cmd (aref vec 0))
(arg (aref vec 1)))
(if cmd (ac-l-db-append 'package-cmds cmd))
(if arg (ac-l-db-append 'package-args arg))))
(setq ac-sources (append (ac-l-db-get 'user-prefix-sources)
(nth 0 sources)
cmd-sources
(nth 1 sources)
arg-sources
(nth 2 sources)
(ac-l-db-get 'user-noprefix-sources)
(nth 3 sources)))))
(defun ac-l-set-sources ()
(let ((s0 `(ac-source-filename
ac-l-source-labels
ac-l-source-bibitems
,(if ac-l-bib-files 'ac-l-source-bibliographies)
,(if (ac-l-db-get 'latex-cmds) 'ac-l-source-latex-commands)))
(s1 `(,(if ac-l-package-files 'ac-l-source-package-commands)
ac-l-source-commands
ac-source-files-in-current-dir
,(if (ac-l-db-get 'latex-args) 'ac-l-source-latex-arguments)))
(s2 `(,(if ac-l-package-files 'ac-l-source-package-arguments)
,(if (ac-l-db-get 'filenames) 'ac-l-source-filenames)))
(s3 `(,(if ac-l-use-word-completion 'ac-l-source-words)
ac-source-dictionary)))
(ac-l-db-set 'sources
(mapcar (lambda (s) (delq nil s)) (list s0 s1 s2 s3)))))
;;; candidate
;; copied from auto-complete.el and added arguments
(defun ac-l-candidate (beg-re end-re)
(let ((i 0)
(regexp (concat beg-re (regexp-quote ac-prefix) end-re))
cand cands)
(save-excursion
;; Search backward
(goto-char ac-point)
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-backward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i)))
;; Search backward
(goto-char (+ ac-point (length ac-prefix)))
(while (and (or (not (integerp ac-limit)) (< i ac-limit))
(re-search-forward regexp nil t))
(setq cand (match-string-no-properties 1))
(unless (member cand cands)
(push cand cands)
(incf i))))
(nreverse cands)))
(defun ac-l-incremental-update-index (idx cand-fn)
(let ((pair (symbol-value idx))
(ac-limit (or (and (integerp ac-limit) ac-limit) 10)))
(when (null pair)
(set idx (cons nil nil)))
;; Mark incomplete
(when (car pair)
(setcar pair nil))
(let ((list (cdr pair))
(words (funcall cand-fn)))
(dolist (word words)
(unless (member word list)
(push word list)
(setcdr pair list))))))
(defun ac-l-update-index (idx cand-fn)
(dolist (buf (buffer-list))
(when (and (eq ac-l-major-mode (buffer-local-value 'major-mode buf))
(or ac-fuzzy-enable
(not (eq buf (current-buffer)))))
(with-current-buffer buf
(when (and (not (car (symbol-value idx)))
(< (buffer-size) 1048576))
;; Complete index
(set idx (cons t (let ((ac-point (point-min))
(ac-prefix "")
ac-limit)
(funcall cand-fn)))))))))
(defun ac-l-candidates (idx cand-fn)
(loop initially (unless ac-fuzzy-enable
(ac-l-incremental-update-index idx cand-fn))
for buf in (buffer-list)
if (and (or (not (integerp ac-limit)) (< (length cands) ac-limit))
(derived-mode-p (buffer-local-value 'major-mode buf)))
append (funcall ac-match-function ac-prefix
(cdr (buffer-local-value idx buf)))
into cands
finally return cands))
;;;; sources
(defvar ac-l-word-index nil)
(make-variable-buffer-local 'ac-l-word-index)
(defun ac-l-smart-capitalize ()
;; Meadow/Emacs memo: http://www.bookshelf.jp/soft/meadow_34.html#SEC495
(when (and (looking-back "[[:space:][:cntrl:]]+[a-z']+")
(= (point) (save-excursion
(backward-sentence)
(forward-word)
(point))))
(capitalize-word -1)))
(defun ac-l-candidate-words-in-buffer ()
(ac-l-candidate "[^\\,]\\(\\<" "[-'a-zA-Z]+\\>\\)"))
(defvar ac-l-source-words
'((action . ac-l-smart-capitalize)
(requires . 3)))
(defvar ac-l-command-index nil)
(make-variable-buffer-local 'ac-l-command-index)
(defun ac-l-candidate-commands-in-buffer ()
(ac-l-candidate "\\\\\\(" "[a-zA-Z@]+\\)"))
(defvar ac-l-source-commands
`((prefix . ,ac-l-command-prefix)))
(defun ac-l-basic-sources-setup ()
;; Add properties into basic sources.
;; The sources work like ac-source-words-in-same-mode-buffers.
(let* ((cw-fn 'ac-l-candidate-words-in-buffer)
(cc-fn 'ac-l-candidate-commands-in-buffer)
(wc `(ac-l-candidates 'ac-l-word-index ',cw-fn))
(cc `(ac-l-candidates 'ac-l-command-index ',cc-fn))
(wi `(ac-l-update-index 'ac-l-word-index ',cw-fn))
(ci `(ac-l-update-index 'ac-l-command-index ',cc-fn)))
(labels ((pushprops (p1 p2 p3 p4)
(push `(candidates . ,p1) ac-l-source-words)
(push `(candidates . ,p2) ac-l-source-commands)
(push `(init . ,p3) ac-l-source-words)
(push `(init . ,p4) ac-l-source-commands)))
(if ac-l-master-p
;; add functions for file's candidates
(pushprops `(append ,wc (ac-l-db-get 'file-words))
`(append ,cc (ac-l-db-get 'file-cmds))
`(lambda ()
,wi
(ac-l-db-set 'file-words
(ac-l-append-info 'ac-l-info-words)))
`(lambda ()
,ci
(ac-l-db-set 'file-cmds
(ac-l-append-info 'ac-l-info-commands))))
(pushprops wc cc wi ci)))))
(defvar ac-l-source-latex-commands
`((candidates . (ac-l-db-get 'latex-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "l")))
(defvar ac-l-source-latex-arguments
`((candidates . (ac-l-db-get 'latex-args))
(prefix . ac-l-argument)
(symbol . "l")))
(defvar ac-l-source-filenames
'((candidates . (ac-l-db-get 'filenames))
(prefix . ac-l-argument))
"Source for package and bib file names.")
(defvar ac-l-source-package-commands
`((candidates . (ac-l-db-get 'package-cmds))
(prefix . ,ac-l-command-prefix)
(symbol . "p")))
(defvar ac-l-source-package-arguments
'((candidates . (ac-l-db-get 'package-args))
(prefix . ac-l-argument)
(symbol . "p")))
(defsubst ac-l-gethash (key tables)
(loop for table in tables thereis (gethash key table)))
(defsubst ac-l-append-keys (tables)
(apply 'append (mapcar (lambda (table)
(loop for k being the hash-keys in table collect k))
tables)))
(defun ac-l-update-labels ()
(let ((it (ac-l-db-set 'label-tables
(mapcar 'ac-l-info-labels (ac-l-all-structs)))))
(ac-l-db-set 'label-cands (ac-l-append-keys it))))
(defvar ac-l-source-labels
'((init . ac-l-update-labels)
(candidates . (ac-l-db-get 'label-cands))
(prefix . ac-l-label)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'label-tables))))
(symbol . "L")))
(defun ac-l-complete-labels ()
"Start label name completion at point."
(interactive)
(auto-complete (list (remove '(prefix . ac-l-label) ac-l-source-labels))))
(defun ac-l-update-bibitems ()
(let ((it (ac-l-db-set 'bibitem-tables
(mapcar 'ac-l-info-bibitems (ac-l-all-structs)))))
(ac-l-db-set 'bibitem-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibitems
'((init . ac-l-update-bibitems)
(candidates . (ac-l-db-get 'bibitem-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'bibitem-tables))))
(symbol . "B")))
(defun ac-l-update-bib ()
(let ((it (ac-l-db-set 'cur-bib-tables
(loop with tables = (ac-l-db-get 'all-bib-tables)
for name in (ac-l-append-info 'ac-l-info-bibs)
if (assoc-default name tables 'string=)
collect it))))
(ac-l-db-set 'bib-cands (ac-l-append-keys it))))
(defvar ac-l-source-bibliographies
'((init . ac-l-update-bib)
(candidates . (ac-l-db-get 'bib-cands))
(prefix . ac-l-bib)
(document . (lambda (k) (ac-l-gethash k (ac-l-db-get 'cur-bib-tables))))
(symbol . "B")))
(defun ac-l-complete-bibs ()
"Start bibliography completion at point."
(interactive)
(auto-complete `(,(remove '(prefix . ac-l-bib) ac-l-source-bibitems)
,(remove '(prefix . ac-l-bib) ac-l-source-bibliographies))))
;;; help
(defconst ac-l-help (make-hash-table :test 'equal))
(defmacro ac-l-define-help-doc (name file beg-re end-re)
(declare (indent 1))
`(defun ,(intern (format "ac-l-%s-documentation" name)) (str)
(or (gethash str ac-l-help)
(unless (string-match "@" str)
(with-temp-buffer
(insert-file-contents (concat ac-l-dict-directory ,file))
(if (re-search-forward (concat ,beg-re str ,end-re) nil t)
(puthash str (match-string-no-properties 1) ac-l-help)
(puthash str t ac-l-help)))))))
(ac-l-define-help-doc latex2e
"latex-help"
"\\(?:\f\n\\)\\([^\f]*\\(?:^[`\\]"
"\\(?:\\s(\\|[ '\n]\\)[^\f]+\\)\\)")
(ac-l-define-help-doc yatex-jp
"YATEXHLP.jp"
"^\\(\\\\?"
"\n[^]+\\)")
;;;; clear
(defvar ac-l-clear-timer nil)
(defun ac-l-clear ()
(clrhash ac-l-help))
(defun* ac-l-cancel-timers
(&optional (timers '(ac-l-update-timer
ac-l-clear-timer)))
(interactive)
(dolist (timer timers)
(let ((val (symbol-value timer)))
(when (timerp val)
(cancel-timer val)
(set timer nil)))))
;;;; setup
(defun ac-l-update-all (&optional force)
(when (eq ac-l-major-mode major-mode)
(ac-l-update-info force)
(ac-l-update)))
(defun ac-l-master-p ()
(setq ac-l-master-p (and (stringp ac-l-master-file)
(file-exists-p ac-l-master-file))))
(defmacro ac-l-set-local-variable (var val)
(declare (indent 1))
`(unless (local-variable-p ',var)
(set (make-local-variable ',var) ,val)))
(defun ac-l-set-local-variables ()
(ac-l-set-local-variable ac-prefix-definitions
(append '((ac-l-argument . (ac-l-prefix-in-paren ac-l-argument-regexps))
(ac-l-file . (ac-l-prefix-in-paren ac-l-file-regexps))
(ac-l-label . (ac-l-prefix-in-paren ac-l-label-regexps))
(ac-l-bib . (ac-l-prefix-in-paren ac-l-bib-regexps)))
ac-prefix-definitions))
(ac-l-set-local-variable ac-source-files-in-current-dir
(append '((prefix . ac-l-file)
(symbol . "F"))
ac-source-files-in-current-dir)))
(defun* ac-l-user-sources-setup (&optional (sources ac-l-sources))
(dolist (source sources)
(ac-l-db-push source (if (assq 'prefix (symbol-value source))
'user-prefix-sources
'user-noprefix-sources))))
(defun ac-l-set-timers ()
(setq ac-l-update-timer (run-with-idle-timer ac-l-update-delay t 'ac-l-update-all)
ac-l-clear-timer (run-with-timer 600 600 'ac-l-clear)))
(defun ac-l-setup ()
"Set up Auto Complete LaTeX."
(let ((msg "Loading auto-complete-latex...")
(initial-p (not (ac-l-struct-master))))
(message "%s" msg)
(setq ac-l-major-mode major-mode)
(ac-l-set-local-variables)
(when initial-p
(ac-l-master-p)
(ac-l-basic-sources-setup)
(ac-l-user-sources-setup)
(ac-l-read-packages)
(ac-l-read-bibs)
(ac-l-make-source-from-dir)
(ac-l-set-help-doc)
(ac-l-set-sources)
(ac-l-set-timers))
(when (or initial-p (not ac-l-master-p))
(ac-l-update-all t))
(message "%sdone" msg)))
(provide 'auto-complete-latex)
;;; auto-complete-latex.el ends here |
[
{
"context": "3, 1996 Free Software Foundation, Inc.\n\n;; Author: rms@gnu.ai.mit.edu\n;; Maintainer: FSF\n;; Keywords: languages, faces\n",
"end": 133,
"score": 0.9999276399612427,
"start": 115,
"tag": "EMAIL",
"value": "rms@gnu.ai.mit.edu"
},
{
"context": "c.\n\n;; Author: rms@gnu.ai.mit.edu\n;; Maintainer: FSF\n;; Keywords: languages, faces\n\n;; This file is pa",
"end": 152,
"score": 0.5515463948249817,
"start": 150,
"tag": "USERNAME",
"value": "SF"
}
] | make_1.4/make/inputs/sdir-cov11/lisp/paren.el | m-zakeri/benchmark | 0 | ;;; paren.el --- highlight matching paren.
;; Copyright (C) 1993, 1996 Free Software Foundation, Inc.
;; Author: rms@gnu.ai.mit.edu
;; 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; Load this and it will display highlighting on whatever
;; paren matches the one before or after point.
;;; Code:
(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)
;;;###autoload
(defcustom show-paren-mode nil
"Toggle Show Paren mode.
When Show Paren mode is enabled, any matching parenthesis is highlighted
after `show-paren-delay' seconds of Emacs idle time.
Setting this variable directly does not take effect;
use either \\[customize] or the function `show-paren-mode'."
:set (lambda (symbol value)
(show-paren-mode (or value 0)))
:initialize 'custom-initialize-default
:type 'boolean
:group 'paren-showing
:require 'paren)
(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-ring-bell-on-mismatch nil
"*If non-nil, beep if mismatched paren is detected."
:type 'boolean
:group 'paren-showing
:version "20.3")
(defface show-paren-match-face
'((((class color)) (:background "turquoise"))
(t (:background "gray")))
"Show Paren mode face used for a matching paren."
:group 'faces
:group 'paren-showing)
(defface show-paren-mismatch-face
'((((class color)) (:foreground "white" :background "purple"))
(t (:reverse-video t)))
"Show Paren mode face used for a mismatching paren."
:group 'faces
:group 'paren-showing)
(defvar show-paren-idle-timer nil)
;;;###autoload
(defun show-paren-mode (&optional arg)
"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."
(interactive "P")
(when window-system
(let ((on-p (if arg
(> (prefix-numeric-value arg) 0)
(not show-paren-mode))))
(setq blink-matching-paren-on-screen (not on-p))
(when show-paren-idle-timer
(cancel-timer show-paren-idle-timer))
(if on-p
(setq show-paren-idle-timer (run-with-idle-timer
show-paren-delay t
'show-paren-function))
(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)))
(setq show-paren-mode on-p))))
;; Find the place to show, if there is one,
;; and show it until input arrives.
(defun show-paren-function ()
;; Do nothing if no window system to display results with.
;; Do nothing if executing keyboard macro.
;; Do nothing if input is pending.
(when window-system
(let (pos dir mismatch face (oldpos (point)))
(cond ((eq (char-syntax (preceding-char)) ?\))
(setq dir -1))
((eq (char-syntax (following-char)) ?\()
(setq dir 1)))
;;
;; 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)))
;; 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)))
(when (/= (char-syntax (char-after beg)) ?\$)
(setq mismatch
(not (eq (char-before end)
;; This can give nil.
(matching-paren (char-after beg)))))))))))
;;
;; Highlight the other end of the sexp, or unhighlight if none.
(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.
(if mismatch
(progn
(if show-paren-ring-bell-on-mismatch
(beep))
(setq face 'show-paren-mismatch-face))
(setq face 'show-paren-match-face))
;;
;; 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.
(if (and (= dir 1) (integerp pos))
(when (and show-paren-overlay-1
(overlay-buffer show-paren-overlay-1))
(delete-overlay show-paren-overlay-1))
(let ((from (if (= dir 1)
(point)
(forward-point -1)))
(to (if (= dir 1)
(forward-point 1)
(point))))
(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 '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 (if (or (eq show-paren-style 'expression)
(and (eq show-paren-style 'mixed)
(not (pos-visible-in-window-p pos))))
(point)
pos))
(from (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))))))
(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 'face face)))))
(provide 'paren)
(if show-paren-mode
(show-paren-mode t))
;;; paren.el ends here
| 11754 | ;;; paren.el --- highlight matching paren.
;; Copyright (C) 1993, 1996 Free Software Foundation, Inc.
;; Author: <EMAIL>
;; 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; Load this and it will display highlighting on whatever
;; paren matches the one before or after point.
;;; Code:
(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)
;;;###autoload
(defcustom show-paren-mode nil
"Toggle Show Paren mode.
When Show Paren mode is enabled, any matching parenthesis is highlighted
after `show-paren-delay' seconds of Emacs idle time.
Setting this variable directly does not take effect;
use either \\[customize] or the function `show-paren-mode'."
:set (lambda (symbol value)
(show-paren-mode (or value 0)))
:initialize 'custom-initialize-default
:type 'boolean
:group 'paren-showing
:require 'paren)
(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-ring-bell-on-mismatch nil
"*If non-nil, beep if mismatched paren is detected."
:type 'boolean
:group 'paren-showing
:version "20.3")
(defface show-paren-match-face
'((((class color)) (:background "turquoise"))
(t (:background "gray")))
"Show Paren mode face used for a matching paren."
:group 'faces
:group 'paren-showing)
(defface show-paren-mismatch-face
'((((class color)) (:foreground "white" :background "purple"))
(t (:reverse-video t)))
"Show Paren mode face used for a mismatching paren."
:group 'faces
:group 'paren-showing)
(defvar show-paren-idle-timer nil)
;;;###autoload
(defun show-paren-mode (&optional arg)
"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."
(interactive "P")
(when window-system
(let ((on-p (if arg
(> (prefix-numeric-value arg) 0)
(not show-paren-mode))))
(setq blink-matching-paren-on-screen (not on-p))
(when show-paren-idle-timer
(cancel-timer show-paren-idle-timer))
(if on-p
(setq show-paren-idle-timer (run-with-idle-timer
show-paren-delay t
'show-paren-function))
(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)))
(setq show-paren-mode on-p))))
;; Find the place to show, if there is one,
;; and show it until input arrives.
(defun show-paren-function ()
;; Do nothing if no window system to display results with.
;; Do nothing if executing keyboard macro.
;; Do nothing if input is pending.
(when window-system
(let (pos dir mismatch face (oldpos (point)))
(cond ((eq (char-syntax (preceding-char)) ?\))
(setq dir -1))
((eq (char-syntax (following-char)) ?\()
(setq dir 1)))
;;
;; 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)))
;; 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)))
(when (/= (char-syntax (char-after beg)) ?\$)
(setq mismatch
(not (eq (char-before end)
;; This can give nil.
(matching-paren (char-after beg)))))))))))
;;
;; Highlight the other end of the sexp, or unhighlight if none.
(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.
(if mismatch
(progn
(if show-paren-ring-bell-on-mismatch
(beep))
(setq face 'show-paren-mismatch-face))
(setq face 'show-paren-match-face))
;;
;; 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.
(if (and (= dir 1) (integerp pos))
(when (and show-paren-overlay-1
(overlay-buffer show-paren-overlay-1))
(delete-overlay show-paren-overlay-1))
(let ((from (if (= dir 1)
(point)
(forward-point -1)))
(to (if (= dir 1)
(forward-point 1)
(point))))
(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 '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 (if (or (eq show-paren-style 'expression)
(and (eq show-paren-style 'mixed)
(not (pos-visible-in-window-p pos))))
(point)
pos))
(from (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))))))
(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 'face face)))))
(provide 'paren)
(if show-paren-mode
(show-paren-mode t))
;;; paren.el ends here
| true | ;;; paren.el --- highlight matching paren.
;; Copyright (C) 1993, 1996 Free Software Foundation, Inc.
;; Author: PI:EMAIL:<EMAIL>END_PI
;; 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; Load this and it will display highlighting on whatever
;; paren matches the one before or after point.
;;; Code:
(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)
;;;###autoload
(defcustom show-paren-mode nil
"Toggle Show Paren mode.
When Show Paren mode is enabled, any matching parenthesis is highlighted
after `show-paren-delay' seconds of Emacs idle time.
Setting this variable directly does not take effect;
use either \\[customize] or the function `show-paren-mode'."
:set (lambda (symbol value)
(show-paren-mode (or value 0)))
:initialize 'custom-initialize-default
:type 'boolean
:group 'paren-showing
:require 'paren)
(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-ring-bell-on-mismatch nil
"*If non-nil, beep if mismatched paren is detected."
:type 'boolean
:group 'paren-showing
:version "20.3")
(defface show-paren-match-face
'((((class color)) (:background "turquoise"))
(t (:background "gray")))
"Show Paren mode face used for a matching paren."
:group 'faces
:group 'paren-showing)
(defface show-paren-mismatch-face
'((((class color)) (:foreground "white" :background "purple"))
(t (:reverse-video t)))
"Show Paren mode face used for a mismatching paren."
:group 'faces
:group 'paren-showing)
(defvar show-paren-idle-timer nil)
;;;###autoload
(defun show-paren-mode (&optional arg)
"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."
(interactive "P")
(when window-system
(let ((on-p (if arg
(> (prefix-numeric-value arg) 0)
(not show-paren-mode))))
(setq blink-matching-paren-on-screen (not on-p))
(when show-paren-idle-timer
(cancel-timer show-paren-idle-timer))
(if on-p
(setq show-paren-idle-timer (run-with-idle-timer
show-paren-delay t
'show-paren-function))
(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)))
(setq show-paren-mode on-p))))
;; Find the place to show, if there is one,
;; and show it until input arrives.
(defun show-paren-function ()
;; Do nothing if no window system to display results with.
;; Do nothing if executing keyboard macro.
;; Do nothing if input is pending.
(when window-system
(let (pos dir mismatch face (oldpos (point)))
(cond ((eq (char-syntax (preceding-char)) ?\))
(setq dir -1))
((eq (char-syntax (following-char)) ?\()
(setq dir 1)))
;;
;; 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)))
;; 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)))
(when (/= (char-syntax (char-after beg)) ?\$)
(setq mismatch
(not (eq (char-before end)
;; This can give nil.
(matching-paren (char-after beg)))))))))))
;;
;; Highlight the other end of the sexp, or unhighlight if none.
(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.
(if mismatch
(progn
(if show-paren-ring-bell-on-mismatch
(beep))
(setq face 'show-paren-mismatch-face))
(setq face 'show-paren-match-face))
;;
;; 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.
(if (and (= dir 1) (integerp pos))
(when (and show-paren-overlay-1
(overlay-buffer show-paren-overlay-1))
(delete-overlay show-paren-overlay-1))
(let ((from (if (= dir 1)
(point)
(forward-point -1)))
(to (if (= dir 1)
(forward-point 1)
(point))))
(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 '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 (if (or (eq show-paren-style 'expression)
(and (eq show-paren-style 'mixed)
(not (pos-visible-in-window-p pos))))
(point)
pos))
(from (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))))))
(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 'face face)))))
(provide 'paren)
(if show-paren-mode
(show-paren-mode t))
;;; paren.el ends here
|
[
{
"context": "ts, programatically\n;;\n;; Copyright (C) 2008, 2009 Jonathan Rockway <jon@jrock.us>\n;;\n;; Author: Jonathan Rockway <jo",
"end": 109,
"score": 0.9998883008956909,
"start": 93,
"tag": "NAME",
"value": "Jonathan Rockway"
},
{
"context": "\n;;\n;; Copyright (C) 2008, 2009 Jonathan Rockway <jon@jrock.us>\n;;\n;; Author: Jonathan Rockway <jon@jrock.us>\n;;",
"end": 123,
"score": 0.9999310374259949,
"start": 111,
"tag": "EMAIL",
"value": "jon@jrock.us"
},
{
"context": "2009 Jonathan Rockway <jon@jrock.us>\n;;\n;; Author: Jonathan Rockway <jon@jrock.us>\n;; Maintainer: Jonathan Rockway <j",
"end": 155,
"score": 0.9998876452445984,
"start": 139,
"tag": "NAME",
"value": "Jonathan Rockway"
},
{
"context": "ay <jon@jrock.us>\n;;\n;; Author: Jonathan Rockway <jon@jrock.us>\n;; Maintainer: Jonathan Rockway <jon@jrock.us>\n;",
"end": 169,
"score": 0.9999321103096008,
"start": 157,
"tag": "EMAIL",
"value": "jon@jrock.us"
},
{
"context": "or: Jonathan Rockway <jon@jrock.us>\n;; Maintainer: Jonathan Rockway <jon@jrock.us>\n;; Created: 20 Nov 2008\n;; Version",
"end": 202,
"score": 0.9998855590820312,
"start": 186,
"tag": "NAME",
"value": "Jonathan Rockway"
},
{
"context": "y <jon@jrock.us>\n;; Maintainer: Jonathan Rockway <jon@jrock.us>\n;; Created: 20 Nov 2008\n;; Version: 1.5\n;; Packa",
"end": 216,
"score": 0.9999331831932068,
"start": 204,
"tag": "EMAIL",
"value": "jon@jrock.us"
},
{
"context": "eds.\n;;\n;; Please e-mail me or find me on #emacs (jrockway) if you have\n;; questions. If you'd like to send",
"end": 4921,
"score": 0.9996369481086731,
"start": 4913,
"tag": "USERNAME",
"value": "jrockway"
},
{
"context": "le by running:\n;;\n;; $ git clone git://github.com/jrockway/eproject\n;;\n;; Share and enjoy.\n\n;;; Public API:\n",
"end": 5114,
"score": 0.9996125102043152,
"start": 5106,
"tag": "USERNAME",
"value": "jrockway"
},
{
"context": "test version is on github at\n;; http://github.com/jrockway/eproject/tree/master\n;;\n;; The wiki has lots more",
"end": 6598,
"score": 0.9996166825294495,
"start": 6590,
"tag": "USERNAME",
"value": "jrockway"
},
{
"context": "ots more documentation:\n;; http://wiki.github.com/jrockway/eproject\n;;\n\n;;; The Changelog section documents ",
"end": 6698,
"score": 0.9995813369750977,
"start": 6690,
"tag": "USERNAME",
"value": "jrockway"
},
{
"context": "l-link :tag \"Github wiki\" \"http://wiki.github.com/jrockway/eproject\"))\n\n(defcustom eproject-keybind-prefix\n ",
"end": 7962,
"score": 0.999607503414154,
"start": 7954,
"tag": "USERNAME",
"value": "jrockway"
}
] | elpa/eproject-20180312.1642/eproject.el | briang/dotemacs | 0 | ;;; eproject.el --- assign files to projects, programatically
;;
;; Copyright (C) 2008, 2009 Jonathan Rockway <jon@jrock.us>
;;
;; Author: Jonathan Rockway <jon@jrock.us>
;; Maintainer: Jonathan Rockway <jon@jrock.us>
;; Created: 20 Nov 2008
;; Version: 1.5
;; Package-Requires: ((helm "1.6.4"))
;; Keywords: programming, projects
;;
;; This file is not a part of GNU Emacs.
;;
;; 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 of
;; the License, 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., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.
;;
;;; Commentary:
;;
;; Eproject is an extension that lets you group related files together
;; as projects. It aims to be as unobtrusive as possible -- no new
;; files are created (or required to exist) on disk, and buffers that
;; aren't a member of a project are not affected in any way.
;;
;; The main starting point for eproject is defining project types.
;; There is a macro for this, define-project-type, that accepts four
;; arguments, the type name (a symbol), a list of supertypes (for
;; inheriting properties), a form that is executed to determine
;; whether a file is a member of a project, and then a free-form
;; property list. An example will clear things up.
;;
;; Let's create a "perl" project type, for Perl projects that have a
;; Makefile.PL.
;;
;; (define-project-type perl (generic)
;; (look-for "Makefile.PL")
;; :relevant-files ("\\.pm$" "\\.t$"))
;;
;; Now when you open a file and somewhere above in the directory tree
;; there is a Makefile.PL, it will be a "perl project".
;;
;; There are a few things you get with this. A hook called
;; perl-project-file-visit-hook will be run, and the buffer will have
;; the "eproject-mode" minor-mode turned on. You can also read and
;; set metadata via the eproject-attribute and
;; eproject-add-project-metadatum calls.
;;
;; (This is mostly helpful to Lisp programmers rather than end-users;
;; if you want tools for visiting and managing projects (and ibuffer
;; integration), load `eproject-extras'. These extras are great
;; examples of the eproject API in action, so please take a look even
;; if you don't want those exact features.)
;;
;; Let's look at the mechanics of the define-project-type call. The
;; first argument is the name of the project type -- it can be any
;; symbol. The next argument is a list of other projects types that
;; this project will inherit from. That means that if you call
;; eproject-get-project-metadatum and the current project doesn't
;; define a value, we'll look at the supertypes until we get something
;; non-nil. Usually you will want to set this to (generic), which
;; will make your type work correctly even if you don't define any of
;; your own metadata.
;;
;; The next argument is a form that will be executed with the filename
;; that was just opened bound to FILE. It is expected to return the
;; project root, or nil if FILE is not in a project of this type. The
;; look-for function will look up the directory tree for a file that
;; is named the same as its argument (see the docstring for
;; `eproject--look-for-impl' for all the details). You can write any
;; Lisp here you like; we'll see some more examples later. (You only
;; get one form, so if you need to execute more than one, just wrap it
;; in a progn.)
;;
;; The final (&rest-style) argument is a property list of initial project
;; metadata. You can put anything you want here, as long as it is in the
;; form of a property list (keyword, value, keyword, value, ...).
;;
;; After this form runs, eproject will be able to recognize files in
;; the type of the project you defined. It also creates a hook named
;; <type>-project-file-visit-hook. You can do anything you want here,
;; including access (eproject-type) and (eproject-root).
;;
;; As an example, in my perl-project-file-visit-hook, I do this:
;;
;; (lambda ()
;; (ignore-errors
;; (stylish-repl-eval-perl
;; (format "use lib '%s'" (car (perl-project-includes)))))))
;;
;; This will add the library directory of this project to my current
;; stylish-repl session, so that I can use my project in the REPL
;; immediately. (I do something similar for Lisp + SLIME projects)
;;
;; That's basically all there is. eproject is designed to be minimal and
;; extensible, so I hope it meets your needs.
;;
;; Please e-mail me or find me on #emacs (jrockway) if you have
;; questions. If you'd like to send a patch (always appreciated),
;; please diff against the latest git version, available by running:
;;
;; $ git clone git://github.com/jrockway/eproject
;;
;; Share and enjoy.
;;; Public API:
;; eproject-root (&optional buffer)
;;
;; - returns the project root for the project that buffer is a member
;; of. defaults to the current buffer
;; eproject-attribute (key &optional root)
;;
;; - returns the value of key for the project that buffer is a member
;; of. root defaults to the current buffer's eproject-root
;; eproject-list-project-files
;; define-project-type
;; define-project-attribute
;; eproject-projects
;; Everything else is mostly used internally, and may change.
;;; Public commands:
;; eproject-maybe-turn-on
;;
;; - turn on eproject for the current buffer, if possible
;; (if it's turned on, the hooks will be run)
;; eproject-reinitialize-project
;;
;; - re-read config for the current project, then run
;; eproject-maybe-turn-on
;;
;; this is bound to C-c C-c when editing .eproject files, which is
;; very convenient for testing.
;; See eproject-extras.el for more interesting / useful commands.
;; This file is mostly "plumbing".
;;; Bugs:
;;
;; You can't forward reference supertypes -- this will mess things up
;; internally, but you won't get a warning. This can be easily fixed
;; by using a smarter algorithm for eproject--all-types.
;;
;; The "linearized isa" (i.e. "class precedence list") is computed
;; with a depth-first search. This is bad; we should really use the
;; C3 ordering.
;;; Website:
;;
;; The latest version is on github at
;; http://github.com/jrockway/eproject/tree/master
;;
;; The wiki has lots more documentation:
;; http://wiki.github.com/jrockway/eproject
;;
;;; The Changelog section documents major changes. Minor non-breaking
;;; updates are regularly committed to git.
;;; Changelog:
;;
;; 1.6 (Sat Aug 28 22:21:39 CDT 2010)
;;
;; * Remove eproject-project-names variable and add some proper
;; introspection for project sets.
;;
;; 1.5 (Thu May 28 21:38:08 MST 2009)
;;
;; * Split out the non-core stuff into eproject-extras.el.
;; (slime-contrib style)
;;
;; 1.4 (Thu May 28 02:21:40 MST 2009)
;;
;; * Add support for "instance" metadata, instead of "class" (project)
;; metadata
;;
;; 1.3 (Wed May 27 20:47:48 MST 2009)
;;
;; * Officially support w32
;;
;; 1.2 (Thu May 7 02:18:01 CDT 2009)
;;
;; * Add ibuffer support
;;
;; 1.1 (Sat Jan 31 20:03:56 CST 2009)
;;
;; * Make the completing-read function customizable
;;
;; 1.0 (Nov 28 2008)
;;
;; * Initial release
;;
;;; Code:
(require 'cl)
(require 'eshell) ;; For portable path handling
(defgroup eproject nil
"Eproject; provide support for grouping files and buffers into projects"
:prefix "eproject-"
:group 'convenience
:link '(emacs-commentary-link :tag "Commentary" "eproject.el")
:link '(emacs-library-link :tag "Optional extras" "eproject-extras.el")
:link '(url-link :tag "Github wiki" "http://wiki.github.com/jrockway/eproject"))
(defcustom eproject-keybind-prefix
"C-c"
"The keybind prefix for eproject"
:type 'string
:group 'eproject)
(defvar eproject-root nil
"A buffer-local variable set to the root of its eproject
project. NIL if it isn't in an eproject. Your code should
call the function `eproject-root` instead of accessing this
variable directly. It should also not set it; only
`eproject-maybe-turn-on' can do that.")
(make-variable-buffer-local 'eproject-root)
(defvar eproject-project-types nil
"An alist of project type name to (supertypes selector metadata-plist) pairs.")
(defvar eproject-extra-attributes nil
"A list of pairs used to assign attributes to projects.
Each entry can be in the form of `(FUNCTION (ATTRIBUTES))'
or `((KEY . TYPE) (ATTRIBUTES))'.
If FUNCTION is specified, it will be evaluated for each project
root. If it returns a non-nil value, ATTRIBUTES will be added to
the project attributes.
If `(KEY . TYPE)' is specified, then TYPE is either
`:root-regexp' or `:project-name' and KEY is interpreted
accordingly. If KEY matches a project root, its ATTRIBUTES are
applied.
ATTRIBUTES is a plist of attributes.")
(defvar eproject-attributes-alist nil
"An alist of project root -> plist of project metadata.")
(defvar eproject-first-buffer-hook nil
"Hook to run when the first buffer in a new project is opened.
Called after the project is initialized, so it's safe to call
eproject functions.")
(defvar eproject-projects-hook nil
"Hook that's run when a list of projects is requested. Hook may return a list of new (name . root) pairs to be added to eproject's internal list.")
(defvar eproject-project-change-hook nil
"Hook that's run when a project is changed; currently this means when a file in the project is saved.")
(defun define-project-attribute (key attributes)
"Define extra attributes to be applied to projects.
See `eproject-extra-attributes' for details on the format of KEY
and ATTRIBUTES."
(check-type key (or function cons))
(check-type attributes list)
(add-to-list 'eproject-extra-attributes (list key attributes)))
(defmacro define-project-type (type supertypes selector &rest metadata)
"Define a new project type TYPE that inherits from SUPERTYPES.
SELECTOR is a form that is given a filename FILE and returns the
project root if it is of this type of project, or NIL otherwise.
Optional argument METADATA is a plist of metadata that will
become project attributes."
`(progn
(defvar ,(intern (format "%s-project-file-visit-hook" type)) nil
,(format "Hooks that will be run when a file in a %s project is opened." type))
(setq eproject-project-types
(nconc (assq-delete-all ',type eproject-project-types)
(list
(list ',type ',supertypes
(lambda (file) ,selector)
',metadata))))))
(defun eproject--build-parent-candidates (start-at)
"Given directory START-AT, return a list of parent directories, including START-AT."
(loop for x on (reverse (eshell-split-path start-at)) by #'cdr
;; i think eshell-split-path guarantees the
;; file-name-as-directory application, but i don't want to
;; debug it if it doesn't :)
collect (file-name-as-directory (apply #'concat (reverse x)))))
(defun eproject--scan-parents-for (start-at predicate)
"Call PREDICATE with each parent directory of START-AT, returning the path to the first directory where PREDICATE returns T."
(find-if predicate (eproject--build-parent-candidates
(file-name-as-directory start-at))))
(defun eproject--find-file-named (start-at filename)
"Starting in directory START-AT, recursively check parent directories for a file named FILENAME. Return the directory where the file is first found; return NIL otherwise."
(eproject--scan-parents-for start-at
(lambda (directory) ; note that directory always has the path separator on the end
(file-exists-p (concat directory filename)))))
;; TODO: sugar around lambda/lambda, which is ugly
(define-project-type generic () nil
:relevant-files (".*")
:irrelevant-files ("^[.]" "^[#]")
:file-name-map (lambda (root) (lambda (root file) file))
:local-variables (lambda (root) (lambda (root file) nil))
:config-file ".eproject")
(define-project-type generic-eproject (generic) (look-for ".eproject"))
(define-project-type generic-git (generic) (look-for ".git")
:irrelevant-files ("^[.]" "^[#]" ".git/"))
(define-project-type generic-hg (generic) (look-for ".hg")
:irrelevant-files ("^[.]" "^[#]" ".hg/"))
(define-project-type generic-bzr (generic) (look-for ".bzr")
:irrelevant-files ("^[.]" "^[#]" ".bzr/"))
(define-project-type generic-darcs (generic) (look-for "_darcs")
:irrelevant-files ("^[.]" "^[#]" "_darcs/"))
(defun eproject--type-info (type)
(or
(assoc type eproject-project-types)
(error "No type %s" type)))
(defun eproject--project-supertypes (type)
(nth 1 (eproject--type-info type)))
(defun eproject--project-selector (type)
(nth 2 (eproject--type-info type)))
(defun* eproject--look-for-impl (file expression &optional (type :filename))
"Implements the LOOK-FOR function that is flet-bound during
`eproject--run-project-selector'. EXPRESSION and TYPE specify
what to look for. Some examples:
(look-for \"Makefile.PL\") ; look up the directory tree for a file called Makefile.PL
(look-for \"*.PL\" :glob) ; look for a file matching *.PL
"
(case type
(:filename (eproject--find-file-named file expression))
(:glob (eproject--scan-parents-for (file-name-directory file)
(lambda (current-directory)
(let ((default-directory current-directory))
(and (not (equal file current-directory))
(> (length (file-expand-wildcards expression)) 0))))))
(otherwise (error "Don't know how to handle %s in LOOK-FOR!" type))))
(defun eproject--buffer-file-name ()
(or (buffer-file-name) (and (derived-mode-p 'dired-mode)
(expand-file-name (if (consp dired-directory)
(car dired-directory)
dired-directory)))))
(defun* eproject--run-project-selector (type &optional (file (eproject--buffer-file-name)))
"Run the selector associated with project type TYPE."
(when (not file)
(error "Buffer '%s' has no file name" (current-buffer)))
(flet ((look-for (expr &optional (expr-type :filename))
(funcall #'eproject--look-for-impl file expr expr-type)))
(funcall (eproject--project-selector type) file)))
(defun eproject--linearized-isa (type &optional include-self)
(delete-duplicates
(append
(if include-self (list type))
(eproject--project-supertypes type)
(loop for stype in (eproject--project-supertypes type)
append (eproject--linearized-isa stype)))))
(defun eproject--all-types ()
;; this should be most specific to least specific, as long as nothing
;; is forward-referenced.
(reverse (mapcar #'car eproject-project-types)))
;; metadata vs. attributes:
;; * metadata is per-project-type
;; * attributes are per-project-root (and includes the project-type metadata)
(defun eproject--compute-all-applicable-metadata (type)
(loop for next-type in (eproject--linearized-isa type t)
append (nth 3 (eproject--type-info next-type))))
(defun eproject-get-project-metadatum (type key)
(getf (eproject--compute-all-applicable-metadata type) key))
(defun eproject-add-project-metadatum (type key value)
(setf (getf (nth 3 (assoc type eproject-project-types)) key) value))
(defmacro* eproject--do-in-buffer ((buffer) &body forms)
`(with-current-buffer ,buffer
(when (not eproject-mode)
(error "Buffer is not an eproject buffer!"))
,@forms))
(defun* eproject-root (&optional (buffer (current-buffer)))
"Return the value of the eproject variable root.
BUFFER defaults to the current buffer"
(eproject--do-in-buffer (buffer) eproject-root))
(defun* eproject-attribute (key &optional (root (eproject-root)))
"Lookup the attribute KEY for the eproject ROOT
ROOT defaults to the current buffer's project-root."
(getf (cdr (assoc root eproject-attributes-alist)) key))
(defun eproject--known-project-roots ()
"Return a list of projects roots that have been visisted this session."
(loop for (key . value) in eproject-attributes-alist collect key))
(defmacro define-eproject-accessor (variable)
"Create a function named eproject-VARIABLE that return the value of VARIABLE in the context of the current project."
(let ((sym (intern (format "eproject-%s" variable))))
`(defun* ,sym
(&optional (buffer (current-buffer)))
,(format "Return the value of the eproject variable %s. BUFFER defaults to the current buffer." variable)
(eproject-attribute ,(intern (format ":%s" variable))))))
(define-eproject-accessor type)
(define-eproject-accessor name)
(defun eproject-reinitialize-project ()
"Forget all project settings for the current eproject, then reload them."
(interactive)
(let ((root (eproject-root)))
(setf eproject-attributes-alist
(delete-if (lambda (x) (equal (car x) root))
eproject-attributes-alist)))
(eproject-maybe-turn-on)
(if (ignore-errors (eproject-root))
(message "Project `%s' reinitialized successfully." (eproject-name))
(message "Error reinitializing project!")))
(defun eproject--maybe-reinitialize ()
"Run by `eproject-project-change-hook' to reinit the project after .eproject is modified."
(when (and (eq major-mode 'dot-eproject-mode)
(boundp 'eproject-root) eproject-root)
(eproject-reinitialize-project)))
(defun eproject--eval-user-data (project-name root)
"Interpret EPROJECT-EXTRA-ATTRIBUTES for PROJECT-NAME (in ROOT)."
(loop for (key attributes) in eproject-extra-attributes append
(cond ((functionp key)
(if (funcall key root) attributes nil))
((not (listp key))
(error "Bad eproject user data (%s %s), %s must be a list/function"
key attributes key))
((and (eq (cdr key) :project-name)
(equal (car key) project-name))
attributes)
((and (eq (cdr key) :root-regexp)
(string-match (car key) root))
attributes)
(t nil))))
(defun eproject--interpret-metadata (data root)
"Interpret DATA with respect to ROOT.
This mostly means evaluating functions and passing everything
else through unchanged."
(loop for i in data collect (if (functionp i) (funcall i root) i)))
(defun eproject--init-attributes (root type)
"Update the EPROJECT-ATTRIBUTES-ALIST for the project rooted at ROOT (of TYPE)."
(let ((project-data (assoc root eproject-attributes-alist)))
(when (null project-data)
(let* ((class-data (eproject--interpret-metadata
(eproject--compute-all-applicable-metadata type)
root))
;; read the .eproject (or whatever) file
(config-file
(concat root (getf class-data :config-file ".eproject")))
(config-file-contents
(with-temp-buffer
(ignore-errors (insert-file-contents config-file nil nil nil t))
(buffer-substring-no-properties (point-min) (point-max))))
(config-file-sexp
(read (format "(list %s)" config-file-contents)))
(data-is-unsafe (unsafep config-file-sexp))
(config-file-data
(cond (data-is-unsafe
(warn "Config file %s contains unsafe data (%s), ignoring!"
config-file data-is-unsafe)
nil)
(t (let ((data (eval config-file-sexp)))
(if data (nconc
(list :loaded-from-config-file config-file)
data)
nil)))))
;; combine class and config data; config overriding class
(class-and-config-data (cond
;; ensure that the config-file-data is really a plist
((evenp (length config-file-data))
(nconc config-file-data class-data))
(t class-data)))
;; calculate the project name, as it's used by "user
;; data"
;; backcompat note: not sure why i looked in
;; :project-name for the value to set the :name attribute
;; to. so now we look in both, preferring the new way.
(name (or (getf class-and-config-data :name)
(getf class-and-config-data :project-name)
(directory-file-name
(elt (reverse (eshell-split-path root)) 0))))
;; finally, merge in the "user data"
(user-data
(eproject--interpret-metadata
(eproject--eval-user-data name root) root))
;; now compute the final list of attributes
(data (nconc user-data class-and-config-data)))
(add-to-list 'eproject-attributes-alist
(cons root (nconc (list :type type :name name) data)))))))
(defvar eproject-mode-map (make-sparse-keymap)
"Keybindings while in eproject-mode")
(define-minor-mode eproject-mode
"A minor mode for buffers that are a member of an eproject project."
nil " Project" eproject-mode-map
(when (null eproject-root)
(error "Please do not use this directly. Call eproject-maybe-turn-on instead.")))
(defun eproject-maybe-turn-on ()
"Turn on eproject for the current buffer, if it is in a project."
(interactive)
(let (bestroot besttype (set-before (mapcar #'car eproject-attributes-alist)))
(loop for type in (eproject--all-types)
do (let ((root (eproject--run-project-selector type)))
(when (and root
(or (not bestroot)
;; longest filename == best match (XXX:
;; need to canonicalize?)
(> (length root) (length bestroot))))
(setq bestroot root)
(setq besttype type))))
(when bestroot
(setq eproject-root (file-name-as-directory bestroot))
;; read .eproject file (etc.) and initialize at least :name and
;; :type
(condition-case e
(eproject--init-attributes eproject-root besttype)
(error (display-warning 'warning
(format "There was a problem setting up the eproject attributes for this project: %s" e))))
;; with :name and :type set, it's now safe to turn on eproject
(eproject-mode 1)
;; initialize buffer-local variables that the project defines
;; (called after we turn on eproject-mode, so we can call
;; eproject-* functions cleanly)
(condition-case e
(eproject--setup-local-variables)
(error (display-warning 'warning
(format "Problem initializing project-specific local-variables in %s: %s"
(eproject--buffer-file-name) e))))
;; run the first-buffer hooks if this is the first time we've
;; seen this particular project root.
(when (not (member eproject-root set-before))
(run-hooks 'eproject-first-buffer-hook))
;; run project-type hooks, which may also call into eproject-*
;; functions
(mapc (lambda (x) (run-hooks (intern (format "%s-project-file-visit-hook" x))))
(eproject--project-supertypes besttype))
(run-hooks (intern (format "%s-project-file-visit-hook" besttype)))
;; return the project root; it's occasionally useful for the caller
bestroot)))
(defun eproject--setup-local-variables ()
"Setup local variables as specified by the project attribute :local-variables."
(let* ((var-maker (eproject-attribute :local-variables))
(vars (cond ((functionp var-maker)
(funcall var-maker
(eproject-root)
(file-relative-name (eproject--buffer-file-name)
(eproject-root))))
((listp var-maker) var-maker))))
(loop for (name val) on vars by #'cddr do
(set (make-local-variable name) val))))
(defun eproject--search-directory-tree (directory file-regexp ignore-regexp)
(loop for file in (directory-files (file-name-as-directory directory) t "^[^.]" t)
unless (string-match ignore-regexp file)
if (not (file-directory-p file))
when (and (not (string-match ignore-regexp
(file-name-nondirectory file)))
(string-match file-regexp file))
collect file into files end
else
collect file into directories
finally return
(nconc files
(loop for dir in directories
nconc (eproject--search-directory-tree dir file-regexp
ignore-regexp)))))
(defun eproject-assert-type (type)
"Assert that the current buffer is in a project of type TYPE."
(when (not (memq type (eproject--linearized-isa (eproject-type) t)))
(error (format "%s is not in a project of type %s!"
(current-buffer) type))))
(defun eproject--combine-regexps (regexp-list)
"Combine regexps like `regexp-opt', but without quoting anything.
Argument REGEXP-LIST is a list of regexps to combine."
(format "\\(?:%s\\)"
(reduce (lambda (a b) (concat a "\\|" b))
(mapcar (lambda (f) (format "\\(?:%s\\)" f)) regexp-list))))
;;; TODO: cache this?
(defun eproject--file-check-regexps (root)
"Return a pair (matcher . ignore) for the project in ROOT."
(let ((matcher (eproject--combine-regexps
(eproject-attribute :relevant-files root)))
(ignore (eproject--combine-regexps
(cons
(concat (regexp-opt completion-ignored-extensions t) "$")
(eproject-attribute :irrelevant-files root)))))
(cons matcher ignore)))
(defun* eproject-classify-file (file &optional (root (eproject-root)))
"Return T if FILE would belong to the project in ROOT.
No check is done to ensure that the root subsumes FILE or even
that FILE is an absolute path."
;; XXX: this logic is sort of copied from search-directory-tree.
;; maybe combine?
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(and (not (string-match ignore file))
(not (string-match ignore (file-name-nondirectory file)))
(string-match matcher file)
t)))
(defun* eproject-list-project-files (&optional (root (eproject-root)))
"Return a list of all project files in PROJECT-ROOT."
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(eproject--search-directory-tree root matcher ignore)))
(defun* eproject-list-project-files-relative (&optional (root (eproject-root)))
(mapcar (lambda (file)
(file-relative-name file root))
(eproject-list-project-files root)))
;;; dot-eproject mode
(define-derived-mode dot-eproject-mode emacs-lisp-mode "dot-eproject"
"Major mode for editing .eproject files."
(define-key dot-eproject-mode-map (kbd (concat eproject-keybind-prefix " C-c")) #'eproject-reinitialize-project))
;; introspect sets of projects
(defun eproject-projects ()
"Return a list of (name . root) pairs of all known eproject projects."
(let ((hash (make-hash-table :test 'equal)))
(loop for f in eproject-projects-hook do
(loop for (name . root) in (funcall f)
do (puthash name root hash)))
(loop for (root . rest)
in eproject-attributes-alist
do (puthash (or (getf rest :name) (getf rest :project-name))
root hash))
(loop for name being each hash-key in hash
collect (cons name (gethash name hash)))))
(defun eproject-project-names ()
"Return a list of project names known to eproject."
(mapcar #'car (eproject-projects)))
;; Finish up
(defun eproject--after-change-major-mode-hook ()
(when (and (buffer-file-name)
(not eproject-root))
(eproject-maybe-turn-on)))
(defun eproject--after-save-hook ()
;; TODO: perhaps check against relevant-files or irrelevant-files
;; regex? I'm avoiding this now because I'd rather not force the
;; speed hit -- if the user wants to do something slow after save,
;; fine... but I'd rather not make the decision for him.
(when (and (boundp 'eproject-root) eproject-root)
(run-hooks 'eproject-project-change-hook)))
(add-hook 'find-file-hook #'eproject-maybe-turn-on)
(add-hook 'dired-mode-hook #'eproject-maybe-turn-on)
(add-hook 'after-change-major-mode-hook #'eproject--after-change-major-mode-hook)
(add-hook 'after-save-hook #'eproject--after-save-hook)
(add-hook 'eproject-project-change-hook #'eproject--maybe-reinitialize)
(add-to-list 'auto-mode-alist '("\\.eproject\\'" . dot-eproject-mode))
(provide 'eproject)
;;; eproject.el ends here
| 13482 | ;;; eproject.el --- assign files to projects, programatically
;;
;; Copyright (C) 2008, 2009 <NAME> <<EMAIL>>
;;
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; Created: 20 Nov 2008
;; Version: 1.5
;; Package-Requires: ((helm "1.6.4"))
;; Keywords: programming, projects
;;
;; This file is not a part of GNU Emacs.
;;
;; 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 of
;; the License, 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., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.
;;
;;; Commentary:
;;
;; Eproject is an extension that lets you group related files together
;; as projects. It aims to be as unobtrusive as possible -- no new
;; files are created (or required to exist) on disk, and buffers that
;; aren't a member of a project are not affected in any way.
;;
;; The main starting point for eproject is defining project types.
;; There is a macro for this, define-project-type, that accepts four
;; arguments, the type name (a symbol), a list of supertypes (for
;; inheriting properties), a form that is executed to determine
;; whether a file is a member of a project, and then a free-form
;; property list. An example will clear things up.
;;
;; Let's create a "perl" project type, for Perl projects that have a
;; Makefile.PL.
;;
;; (define-project-type perl (generic)
;; (look-for "Makefile.PL")
;; :relevant-files ("\\.pm$" "\\.t$"))
;;
;; Now when you open a file and somewhere above in the directory tree
;; there is a Makefile.PL, it will be a "perl project".
;;
;; There are a few things you get with this. A hook called
;; perl-project-file-visit-hook will be run, and the buffer will have
;; the "eproject-mode" minor-mode turned on. You can also read and
;; set metadata via the eproject-attribute and
;; eproject-add-project-metadatum calls.
;;
;; (This is mostly helpful to Lisp programmers rather than end-users;
;; if you want tools for visiting and managing projects (and ibuffer
;; integration), load `eproject-extras'. These extras are great
;; examples of the eproject API in action, so please take a look even
;; if you don't want those exact features.)
;;
;; Let's look at the mechanics of the define-project-type call. The
;; first argument is the name of the project type -- it can be any
;; symbol. The next argument is a list of other projects types that
;; this project will inherit from. That means that if you call
;; eproject-get-project-metadatum and the current project doesn't
;; define a value, we'll look at the supertypes until we get something
;; non-nil. Usually you will want to set this to (generic), which
;; will make your type work correctly even if you don't define any of
;; your own metadata.
;;
;; The next argument is a form that will be executed with the filename
;; that was just opened bound to FILE. It is expected to return the
;; project root, or nil if FILE is not in a project of this type. The
;; look-for function will look up the directory tree for a file that
;; is named the same as its argument (see the docstring for
;; `eproject--look-for-impl' for all the details). You can write any
;; Lisp here you like; we'll see some more examples later. (You only
;; get one form, so if you need to execute more than one, just wrap it
;; in a progn.)
;;
;; The final (&rest-style) argument is a property list of initial project
;; metadata. You can put anything you want here, as long as it is in the
;; form of a property list (keyword, value, keyword, value, ...).
;;
;; After this form runs, eproject will be able to recognize files in
;; the type of the project you defined. It also creates a hook named
;; <type>-project-file-visit-hook. You can do anything you want here,
;; including access (eproject-type) and (eproject-root).
;;
;; As an example, in my perl-project-file-visit-hook, I do this:
;;
;; (lambda ()
;; (ignore-errors
;; (stylish-repl-eval-perl
;; (format "use lib '%s'" (car (perl-project-includes)))))))
;;
;; This will add the library directory of this project to my current
;; stylish-repl session, so that I can use my project in the REPL
;; immediately. (I do something similar for Lisp + SLIME projects)
;;
;; That's basically all there is. eproject is designed to be minimal and
;; extensible, so I hope it meets your needs.
;;
;; Please e-mail me or find me on #emacs (jrockway) if you have
;; questions. If you'd like to send a patch (always appreciated),
;; please diff against the latest git version, available by running:
;;
;; $ git clone git://github.com/jrockway/eproject
;;
;; Share and enjoy.
;;; Public API:
;; eproject-root (&optional buffer)
;;
;; - returns the project root for the project that buffer is a member
;; of. defaults to the current buffer
;; eproject-attribute (key &optional root)
;;
;; - returns the value of key for the project that buffer is a member
;; of. root defaults to the current buffer's eproject-root
;; eproject-list-project-files
;; define-project-type
;; define-project-attribute
;; eproject-projects
;; Everything else is mostly used internally, and may change.
;;; Public commands:
;; eproject-maybe-turn-on
;;
;; - turn on eproject for the current buffer, if possible
;; (if it's turned on, the hooks will be run)
;; eproject-reinitialize-project
;;
;; - re-read config for the current project, then run
;; eproject-maybe-turn-on
;;
;; this is bound to C-c C-c when editing .eproject files, which is
;; very convenient for testing.
;; See eproject-extras.el for more interesting / useful commands.
;; This file is mostly "plumbing".
;;; Bugs:
;;
;; You can't forward reference supertypes -- this will mess things up
;; internally, but you won't get a warning. This can be easily fixed
;; by using a smarter algorithm for eproject--all-types.
;;
;; The "linearized isa" (i.e. "class precedence list") is computed
;; with a depth-first search. This is bad; we should really use the
;; C3 ordering.
;;; Website:
;;
;; The latest version is on github at
;; http://github.com/jrockway/eproject/tree/master
;;
;; The wiki has lots more documentation:
;; http://wiki.github.com/jrockway/eproject
;;
;;; The Changelog section documents major changes. Minor non-breaking
;;; updates are regularly committed to git.
;;; Changelog:
;;
;; 1.6 (Sat Aug 28 22:21:39 CDT 2010)
;;
;; * Remove eproject-project-names variable and add some proper
;; introspection for project sets.
;;
;; 1.5 (Thu May 28 21:38:08 MST 2009)
;;
;; * Split out the non-core stuff into eproject-extras.el.
;; (slime-contrib style)
;;
;; 1.4 (Thu May 28 02:21:40 MST 2009)
;;
;; * Add support for "instance" metadata, instead of "class" (project)
;; metadata
;;
;; 1.3 (Wed May 27 20:47:48 MST 2009)
;;
;; * Officially support w32
;;
;; 1.2 (Thu May 7 02:18:01 CDT 2009)
;;
;; * Add ibuffer support
;;
;; 1.1 (Sat Jan 31 20:03:56 CST 2009)
;;
;; * Make the completing-read function customizable
;;
;; 1.0 (Nov 28 2008)
;;
;; * Initial release
;;
;;; Code:
(require 'cl)
(require 'eshell) ;; For portable path handling
(defgroup eproject nil
"Eproject; provide support for grouping files and buffers into projects"
:prefix "eproject-"
:group 'convenience
:link '(emacs-commentary-link :tag "Commentary" "eproject.el")
:link '(emacs-library-link :tag "Optional extras" "eproject-extras.el")
:link '(url-link :tag "Github wiki" "http://wiki.github.com/jrockway/eproject"))
(defcustom eproject-keybind-prefix
"C-c"
"The keybind prefix for eproject"
:type 'string
:group 'eproject)
(defvar eproject-root nil
"A buffer-local variable set to the root of its eproject
project. NIL if it isn't in an eproject. Your code should
call the function `eproject-root` instead of accessing this
variable directly. It should also not set it; only
`eproject-maybe-turn-on' can do that.")
(make-variable-buffer-local 'eproject-root)
(defvar eproject-project-types nil
"An alist of project type name to (supertypes selector metadata-plist) pairs.")
(defvar eproject-extra-attributes nil
"A list of pairs used to assign attributes to projects.
Each entry can be in the form of `(FUNCTION (ATTRIBUTES))'
or `((KEY . TYPE) (ATTRIBUTES))'.
If FUNCTION is specified, it will be evaluated for each project
root. If it returns a non-nil value, ATTRIBUTES will be added to
the project attributes.
If `(KEY . TYPE)' is specified, then TYPE is either
`:root-regexp' or `:project-name' and KEY is interpreted
accordingly. If KEY matches a project root, its ATTRIBUTES are
applied.
ATTRIBUTES is a plist of attributes.")
(defvar eproject-attributes-alist nil
"An alist of project root -> plist of project metadata.")
(defvar eproject-first-buffer-hook nil
"Hook to run when the first buffer in a new project is opened.
Called after the project is initialized, so it's safe to call
eproject functions.")
(defvar eproject-projects-hook nil
"Hook that's run when a list of projects is requested. Hook may return a list of new (name . root) pairs to be added to eproject's internal list.")
(defvar eproject-project-change-hook nil
"Hook that's run when a project is changed; currently this means when a file in the project is saved.")
(defun define-project-attribute (key attributes)
"Define extra attributes to be applied to projects.
See `eproject-extra-attributes' for details on the format of KEY
and ATTRIBUTES."
(check-type key (or function cons))
(check-type attributes list)
(add-to-list 'eproject-extra-attributes (list key attributes)))
(defmacro define-project-type (type supertypes selector &rest metadata)
"Define a new project type TYPE that inherits from SUPERTYPES.
SELECTOR is a form that is given a filename FILE and returns the
project root if it is of this type of project, or NIL otherwise.
Optional argument METADATA is a plist of metadata that will
become project attributes."
`(progn
(defvar ,(intern (format "%s-project-file-visit-hook" type)) nil
,(format "Hooks that will be run when a file in a %s project is opened." type))
(setq eproject-project-types
(nconc (assq-delete-all ',type eproject-project-types)
(list
(list ',type ',supertypes
(lambda (file) ,selector)
',metadata))))))
(defun eproject--build-parent-candidates (start-at)
"Given directory START-AT, return a list of parent directories, including START-AT."
(loop for x on (reverse (eshell-split-path start-at)) by #'cdr
;; i think eshell-split-path guarantees the
;; file-name-as-directory application, but i don't want to
;; debug it if it doesn't :)
collect (file-name-as-directory (apply #'concat (reverse x)))))
(defun eproject--scan-parents-for (start-at predicate)
"Call PREDICATE with each parent directory of START-AT, returning the path to the first directory where PREDICATE returns T."
(find-if predicate (eproject--build-parent-candidates
(file-name-as-directory start-at))))
(defun eproject--find-file-named (start-at filename)
"Starting in directory START-AT, recursively check parent directories for a file named FILENAME. Return the directory where the file is first found; return NIL otherwise."
(eproject--scan-parents-for start-at
(lambda (directory) ; note that directory always has the path separator on the end
(file-exists-p (concat directory filename)))))
;; TODO: sugar around lambda/lambda, which is ugly
(define-project-type generic () nil
:relevant-files (".*")
:irrelevant-files ("^[.]" "^[#]")
:file-name-map (lambda (root) (lambda (root file) file))
:local-variables (lambda (root) (lambda (root file) nil))
:config-file ".eproject")
(define-project-type generic-eproject (generic) (look-for ".eproject"))
(define-project-type generic-git (generic) (look-for ".git")
:irrelevant-files ("^[.]" "^[#]" ".git/"))
(define-project-type generic-hg (generic) (look-for ".hg")
:irrelevant-files ("^[.]" "^[#]" ".hg/"))
(define-project-type generic-bzr (generic) (look-for ".bzr")
:irrelevant-files ("^[.]" "^[#]" ".bzr/"))
(define-project-type generic-darcs (generic) (look-for "_darcs")
:irrelevant-files ("^[.]" "^[#]" "_darcs/"))
(defun eproject--type-info (type)
(or
(assoc type eproject-project-types)
(error "No type %s" type)))
(defun eproject--project-supertypes (type)
(nth 1 (eproject--type-info type)))
(defun eproject--project-selector (type)
(nth 2 (eproject--type-info type)))
(defun* eproject--look-for-impl (file expression &optional (type :filename))
"Implements the LOOK-FOR function that is flet-bound during
`eproject--run-project-selector'. EXPRESSION and TYPE specify
what to look for. Some examples:
(look-for \"Makefile.PL\") ; look up the directory tree for a file called Makefile.PL
(look-for \"*.PL\" :glob) ; look for a file matching *.PL
"
(case type
(:filename (eproject--find-file-named file expression))
(:glob (eproject--scan-parents-for (file-name-directory file)
(lambda (current-directory)
(let ((default-directory current-directory))
(and (not (equal file current-directory))
(> (length (file-expand-wildcards expression)) 0))))))
(otherwise (error "Don't know how to handle %s in LOOK-FOR!" type))))
(defun eproject--buffer-file-name ()
(or (buffer-file-name) (and (derived-mode-p 'dired-mode)
(expand-file-name (if (consp dired-directory)
(car dired-directory)
dired-directory)))))
(defun* eproject--run-project-selector (type &optional (file (eproject--buffer-file-name)))
"Run the selector associated with project type TYPE."
(when (not file)
(error "Buffer '%s' has no file name" (current-buffer)))
(flet ((look-for (expr &optional (expr-type :filename))
(funcall #'eproject--look-for-impl file expr expr-type)))
(funcall (eproject--project-selector type) file)))
(defun eproject--linearized-isa (type &optional include-self)
(delete-duplicates
(append
(if include-self (list type))
(eproject--project-supertypes type)
(loop for stype in (eproject--project-supertypes type)
append (eproject--linearized-isa stype)))))
(defun eproject--all-types ()
;; this should be most specific to least specific, as long as nothing
;; is forward-referenced.
(reverse (mapcar #'car eproject-project-types)))
;; metadata vs. attributes:
;; * metadata is per-project-type
;; * attributes are per-project-root (and includes the project-type metadata)
(defun eproject--compute-all-applicable-metadata (type)
(loop for next-type in (eproject--linearized-isa type t)
append (nth 3 (eproject--type-info next-type))))
(defun eproject-get-project-metadatum (type key)
(getf (eproject--compute-all-applicable-metadata type) key))
(defun eproject-add-project-metadatum (type key value)
(setf (getf (nth 3 (assoc type eproject-project-types)) key) value))
(defmacro* eproject--do-in-buffer ((buffer) &body forms)
`(with-current-buffer ,buffer
(when (not eproject-mode)
(error "Buffer is not an eproject buffer!"))
,@forms))
(defun* eproject-root (&optional (buffer (current-buffer)))
"Return the value of the eproject variable root.
BUFFER defaults to the current buffer"
(eproject--do-in-buffer (buffer) eproject-root))
(defun* eproject-attribute (key &optional (root (eproject-root)))
"Lookup the attribute KEY for the eproject ROOT
ROOT defaults to the current buffer's project-root."
(getf (cdr (assoc root eproject-attributes-alist)) key))
(defun eproject--known-project-roots ()
"Return a list of projects roots that have been visisted this session."
(loop for (key . value) in eproject-attributes-alist collect key))
(defmacro define-eproject-accessor (variable)
"Create a function named eproject-VARIABLE that return the value of VARIABLE in the context of the current project."
(let ((sym (intern (format "eproject-%s" variable))))
`(defun* ,sym
(&optional (buffer (current-buffer)))
,(format "Return the value of the eproject variable %s. BUFFER defaults to the current buffer." variable)
(eproject-attribute ,(intern (format ":%s" variable))))))
(define-eproject-accessor type)
(define-eproject-accessor name)
(defun eproject-reinitialize-project ()
"Forget all project settings for the current eproject, then reload them."
(interactive)
(let ((root (eproject-root)))
(setf eproject-attributes-alist
(delete-if (lambda (x) (equal (car x) root))
eproject-attributes-alist)))
(eproject-maybe-turn-on)
(if (ignore-errors (eproject-root))
(message "Project `%s' reinitialized successfully." (eproject-name))
(message "Error reinitializing project!")))
(defun eproject--maybe-reinitialize ()
"Run by `eproject-project-change-hook' to reinit the project after .eproject is modified."
(when (and (eq major-mode 'dot-eproject-mode)
(boundp 'eproject-root) eproject-root)
(eproject-reinitialize-project)))
(defun eproject--eval-user-data (project-name root)
"Interpret EPROJECT-EXTRA-ATTRIBUTES for PROJECT-NAME (in ROOT)."
(loop for (key attributes) in eproject-extra-attributes append
(cond ((functionp key)
(if (funcall key root) attributes nil))
((not (listp key))
(error "Bad eproject user data (%s %s), %s must be a list/function"
key attributes key))
((and (eq (cdr key) :project-name)
(equal (car key) project-name))
attributes)
((and (eq (cdr key) :root-regexp)
(string-match (car key) root))
attributes)
(t nil))))
(defun eproject--interpret-metadata (data root)
"Interpret DATA with respect to ROOT.
This mostly means evaluating functions and passing everything
else through unchanged."
(loop for i in data collect (if (functionp i) (funcall i root) i)))
(defun eproject--init-attributes (root type)
"Update the EPROJECT-ATTRIBUTES-ALIST for the project rooted at ROOT (of TYPE)."
(let ((project-data (assoc root eproject-attributes-alist)))
(when (null project-data)
(let* ((class-data (eproject--interpret-metadata
(eproject--compute-all-applicable-metadata type)
root))
;; read the .eproject (or whatever) file
(config-file
(concat root (getf class-data :config-file ".eproject")))
(config-file-contents
(with-temp-buffer
(ignore-errors (insert-file-contents config-file nil nil nil t))
(buffer-substring-no-properties (point-min) (point-max))))
(config-file-sexp
(read (format "(list %s)" config-file-contents)))
(data-is-unsafe (unsafep config-file-sexp))
(config-file-data
(cond (data-is-unsafe
(warn "Config file %s contains unsafe data (%s), ignoring!"
config-file data-is-unsafe)
nil)
(t (let ((data (eval config-file-sexp)))
(if data (nconc
(list :loaded-from-config-file config-file)
data)
nil)))))
;; combine class and config data; config overriding class
(class-and-config-data (cond
;; ensure that the config-file-data is really a plist
((evenp (length config-file-data))
(nconc config-file-data class-data))
(t class-data)))
;; calculate the project name, as it's used by "user
;; data"
;; backcompat note: not sure why i looked in
;; :project-name for the value to set the :name attribute
;; to. so now we look in both, preferring the new way.
(name (or (getf class-and-config-data :name)
(getf class-and-config-data :project-name)
(directory-file-name
(elt (reverse (eshell-split-path root)) 0))))
;; finally, merge in the "user data"
(user-data
(eproject--interpret-metadata
(eproject--eval-user-data name root) root))
;; now compute the final list of attributes
(data (nconc user-data class-and-config-data)))
(add-to-list 'eproject-attributes-alist
(cons root (nconc (list :type type :name name) data)))))))
(defvar eproject-mode-map (make-sparse-keymap)
"Keybindings while in eproject-mode")
(define-minor-mode eproject-mode
"A minor mode for buffers that are a member of an eproject project."
nil " Project" eproject-mode-map
(when (null eproject-root)
(error "Please do not use this directly. Call eproject-maybe-turn-on instead.")))
(defun eproject-maybe-turn-on ()
"Turn on eproject for the current buffer, if it is in a project."
(interactive)
(let (bestroot besttype (set-before (mapcar #'car eproject-attributes-alist)))
(loop for type in (eproject--all-types)
do (let ((root (eproject--run-project-selector type)))
(when (and root
(or (not bestroot)
;; longest filename == best match (XXX:
;; need to canonicalize?)
(> (length root) (length bestroot))))
(setq bestroot root)
(setq besttype type))))
(when bestroot
(setq eproject-root (file-name-as-directory bestroot))
;; read .eproject file (etc.) and initialize at least :name and
;; :type
(condition-case e
(eproject--init-attributes eproject-root besttype)
(error (display-warning 'warning
(format "There was a problem setting up the eproject attributes for this project: %s" e))))
;; with :name and :type set, it's now safe to turn on eproject
(eproject-mode 1)
;; initialize buffer-local variables that the project defines
;; (called after we turn on eproject-mode, so we can call
;; eproject-* functions cleanly)
(condition-case e
(eproject--setup-local-variables)
(error (display-warning 'warning
(format "Problem initializing project-specific local-variables in %s: %s"
(eproject--buffer-file-name) e))))
;; run the first-buffer hooks if this is the first time we've
;; seen this particular project root.
(when (not (member eproject-root set-before))
(run-hooks 'eproject-first-buffer-hook))
;; run project-type hooks, which may also call into eproject-*
;; functions
(mapc (lambda (x) (run-hooks (intern (format "%s-project-file-visit-hook" x))))
(eproject--project-supertypes besttype))
(run-hooks (intern (format "%s-project-file-visit-hook" besttype)))
;; return the project root; it's occasionally useful for the caller
bestroot)))
(defun eproject--setup-local-variables ()
"Setup local variables as specified by the project attribute :local-variables."
(let* ((var-maker (eproject-attribute :local-variables))
(vars (cond ((functionp var-maker)
(funcall var-maker
(eproject-root)
(file-relative-name (eproject--buffer-file-name)
(eproject-root))))
((listp var-maker) var-maker))))
(loop for (name val) on vars by #'cddr do
(set (make-local-variable name) val))))
(defun eproject--search-directory-tree (directory file-regexp ignore-regexp)
(loop for file in (directory-files (file-name-as-directory directory) t "^[^.]" t)
unless (string-match ignore-regexp file)
if (not (file-directory-p file))
when (and (not (string-match ignore-regexp
(file-name-nondirectory file)))
(string-match file-regexp file))
collect file into files end
else
collect file into directories
finally return
(nconc files
(loop for dir in directories
nconc (eproject--search-directory-tree dir file-regexp
ignore-regexp)))))
(defun eproject-assert-type (type)
"Assert that the current buffer is in a project of type TYPE."
(when (not (memq type (eproject--linearized-isa (eproject-type) t)))
(error (format "%s is not in a project of type %s!"
(current-buffer) type))))
(defun eproject--combine-regexps (regexp-list)
"Combine regexps like `regexp-opt', but without quoting anything.
Argument REGEXP-LIST is a list of regexps to combine."
(format "\\(?:%s\\)"
(reduce (lambda (a b) (concat a "\\|" b))
(mapcar (lambda (f) (format "\\(?:%s\\)" f)) regexp-list))))
;;; TODO: cache this?
(defun eproject--file-check-regexps (root)
"Return a pair (matcher . ignore) for the project in ROOT."
(let ((matcher (eproject--combine-regexps
(eproject-attribute :relevant-files root)))
(ignore (eproject--combine-regexps
(cons
(concat (regexp-opt completion-ignored-extensions t) "$")
(eproject-attribute :irrelevant-files root)))))
(cons matcher ignore)))
(defun* eproject-classify-file (file &optional (root (eproject-root)))
"Return T if FILE would belong to the project in ROOT.
No check is done to ensure that the root subsumes FILE or even
that FILE is an absolute path."
;; XXX: this logic is sort of copied from search-directory-tree.
;; maybe combine?
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(and (not (string-match ignore file))
(not (string-match ignore (file-name-nondirectory file)))
(string-match matcher file)
t)))
(defun* eproject-list-project-files (&optional (root (eproject-root)))
"Return a list of all project files in PROJECT-ROOT."
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(eproject--search-directory-tree root matcher ignore)))
(defun* eproject-list-project-files-relative (&optional (root (eproject-root)))
(mapcar (lambda (file)
(file-relative-name file root))
(eproject-list-project-files root)))
;;; dot-eproject mode
(define-derived-mode dot-eproject-mode emacs-lisp-mode "dot-eproject"
"Major mode for editing .eproject files."
(define-key dot-eproject-mode-map (kbd (concat eproject-keybind-prefix " C-c")) #'eproject-reinitialize-project))
;; introspect sets of projects
(defun eproject-projects ()
"Return a list of (name . root) pairs of all known eproject projects."
(let ((hash (make-hash-table :test 'equal)))
(loop for f in eproject-projects-hook do
(loop for (name . root) in (funcall f)
do (puthash name root hash)))
(loop for (root . rest)
in eproject-attributes-alist
do (puthash (or (getf rest :name) (getf rest :project-name))
root hash))
(loop for name being each hash-key in hash
collect (cons name (gethash name hash)))))
(defun eproject-project-names ()
"Return a list of project names known to eproject."
(mapcar #'car (eproject-projects)))
;; Finish up
(defun eproject--after-change-major-mode-hook ()
(when (and (buffer-file-name)
(not eproject-root))
(eproject-maybe-turn-on)))
(defun eproject--after-save-hook ()
;; TODO: perhaps check against relevant-files or irrelevant-files
;; regex? I'm avoiding this now because I'd rather not force the
;; speed hit -- if the user wants to do something slow after save,
;; fine... but I'd rather not make the decision for him.
(when (and (boundp 'eproject-root) eproject-root)
(run-hooks 'eproject-project-change-hook)))
(add-hook 'find-file-hook #'eproject-maybe-turn-on)
(add-hook 'dired-mode-hook #'eproject-maybe-turn-on)
(add-hook 'after-change-major-mode-hook #'eproject--after-change-major-mode-hook)
(add-hook 'after-save-hook #'eproject--after-save-hook)
(add-hook 'eproject-project-change-hook #'eproject--maybe-reinitialize)
(add-to-list 'auto-mode-alist '("\\.eproject\\'" . dot-eproject-mode))
(provide 'eproject)
;;; eproject.el ends here
| true | ;;; eproject.el --- assign files to projects, programatically
;;
;; Copyright (C) 2008, 2009 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 20 Nov 2008
;; Version: 1.5
;; Package-Requires: ((helm "1.6.4"))
;; Keywords: programming, projects
;;
;; This file is not a part of GNU Emacs.
;;
;; 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 of
;; the License, 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., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.
;;
;;; Commentary:
;;
;; Eproject is an extension that lets you group related files together
;; as projects. It aims to be as unobtrusive as possible -- no new
;; files are created (or required to exist) on disk, and buffers that
;; aren't a member of a project are not affected in any way.
;;
;; The main starting point for eproject is defining project types.
;; There is a macro for this, define-project-type, that accepts four
;; arguments, the type name (a symbol), a list of supertypes (for
;; inheriting properties), a form that is executed to determine
;; whether a file is a member of a project, and then a free-form
;; property list. An example will clear things up.
;;
;; Let's create a "perl" project type, for Perl projects that have a
;; Makefile.PL.
;;
;; (define-project-type perl (generic)
;; (look-for "Makefile.PL")
;; :relevant-files ("\\.pm$" "\\.t$"))
;;
;; Now when you open a file and somewhere above in the directory tree
;; there is a Makefile.PL, it will be a "perl project".
;;
;; There are a few things you get with this. A hook called
;; perl-project-file-visit-hook will be run, and the buffer will have
;; the "eproject-mode" minor-mode turned on. You can also read and
;; set metadata via the eproject-attribute and
;; eproject-add-project-metadatum calls.
;;
;; (This is mostly helpful to Lisp programmers rather than end-users;
;; if you want tools for visiting and managing projects (and ibuffer
;; integration), load `eproject-extras'. These extras are great
;; examples of the eproject API in action, so please take a look even
;; if you don't want those exact features.)
;;
;; Let's look at the mechanics of the define-project-type call. The
;; first argument is the name of the project type -- it can be any
;; symbol. The next argument is a list of other projects types that
;; this project will inherit from. That means that if you call
;; eproject-get-project-metadatum and the current project doesn't
;; define a value, we'll look at the supertypes until we get something
;; non-nil. Usually you will want to set this to (generic), which
;; will make your type work correctly even if you don't define any of
;; your own metadata.
;;
;; The next argument is a form that will be executed with the filename
;; that was just opened bound to FILE. It is expected to return the
;; project root, or nil if FILE is not in a project of this type. The
;; look-for function will look up the directory tree for a file that
;; is named the same as its argument (see the docstring for
;; `eproject--look-for-impl' for all the details). You can write any
;; Lisp here you like; we'll see some more examples later. (You only
;; get one form, so if you need to execute more than one, just wrap it
;; in a progn.)
;;
;; The final (&rest-style) argument is a property list of initial project
;; metadata. You can put anything you want here, as long as it is in the
;; form of a property list (keyword, value, keyword, value, ...).
;;
;; After this form runs, eproject will be able to recognize files in
;; the type of the project you defined. It also creates a hook named
;; <type>-project-file-visit-hook. You can do anything you want here,
;; including access (eproject-type) and (eproject-root).
;;
;; As an example, in my perl-project-file-visit-hook, I do this:
;;
;; (lambda ()
;; (ignore-errors
;; (stylish-repl-eval-perl
;; (format "use lib '%s'" (car (perl-project-includes)))))))
;;
;; This will add the library directory of this project to my current
;; stylish-repl session, so that I can use my project in the REPL
;; immediately. (I do something similar for Lisp + SLIME projects)
;;
;; That's basically all there is. eproject is designed to be minimal and
;; extensible, so I hope it meets your needs.
;;
;; Please e-mail me or find me on #emacs (jrockway) if you have
;; questions. If you'd like to send a patch (always appreciated),
;; please diff against the latest git version, available by running:
;;
;; $ git clone git://github.com/jrockway/eproject
;;
;; Share and enjoy.
;;; Public API:
;; eproject-root (&optional buffer)
;;
;; - returns the project root for the project that buffer is a member
;; of. defaults to the current buffer
;; eproject-attribute (key &optional root)
;;
;; - returns the value of key for the project that buffer is a member
;; of. root defaults to the current buffer's eproject-root
;; eproject-list-project-files
;; define-project-type
;; define-project-attribute
;; eproject-projects
;; Everything else is mostly used internally, and may change.
;;; Public commands:
;; eproject-maybe-turn-on
;;
;; - turn on eproject for the current buffer, if possible
;; (if it's turned on, the hooks will be run)
;; eproject-reinitialize-project
;;
;; - re-read config for the current project, then run
;; eproject-maybe-turn-on
;;
;; this is bound to C-c C-c when editing .eproject files, which is
;; very convenient for testing.
;; See eproject-extras.el for more interesting / useful commands.
;; This file is mostly "plumbing".
;;; Bugs:
;;
;; You can't forward reference supertypes -- this will mess things up
;; internally, but you won't get a warning. This can be easily fixed
;; by using a smarter algorithm for eproject--all-types.
;;
;; The "linearized isa" (i.e. "class precedence list") is computed
;; with a depth-first search. This is bad; we should really use the
;; C3 ordering.
;;; Website:
;;
;; The latest version is on github at
;; http://github.com/jrockway/eproject/tree/master
;;
;; The wiki has lots more documentation:
;; http://wiki.github.com/jrockway/eproject
;;
;;; The Changelog section documents major changes. Minor non-breaking
;;; updates are regularly committed to git.
;;; Changelog:
;;
;; 1.6 (Sat Aug 28 22:21:39 CDT 2010)
;;
;; * Remove eproject-project-names variable and add some proper
;; introspection for project sets.
;;
;; 1.5 (Thu May 28 21:38:08 MST 2009)
;;
;; * Split out the non-core stuff into eproject-extras.el.
;; (slime-contrib style)
;;
;; 1.4 (Thu May 28 02:21:40 MST 2009)
;;
;; * Add support for "instance" metadata, instead of "class" (project)
;; metadata
;;
;; 1.3 (Wed May 27 20:47:48 MST 2009)
;;
;; * Officially support w32
;;
;; 1.2 (Thu May 7 02:18:01 CDT 2009)
;;
;; * Add ibuffer support
;;
;; 1.1 (Sat Jan 31 20:03:56 CST 2009)
;;
;; * Make the completing-read function customizable
;;
;; 1.0 (Nov 28 2008)
;;
;; * Initial release
;;
;;; Code:
(require 'cl)
(require 'eshell) ;; For portable path handling
(defgroup eproject nil
"Eproject; provide support for grouping files and buffers into projects"
:prefix "eproject-"
:group 'convenience
:link '(emacs-commentary-link :tag "Commentary" "eproject.el")
:link '(emacs-library-link :tag "Optional extras" "eproject-extras.el")
:link '(url-link :tag "Github wiki" "http://wiki.github.com/jrockway/eproject"))
(defcustom eproject-keybind-prefix
"C-c"
"The keybind prefix for eproject"
:type 'string
:group 'eproject)
(defvar eproject-root nil
"A buffer-local variable set to the root of its eproject
project. NIL if it isn't in an eproject. Your code should
call the function `eproject-root` instead of accessing this
variable directly. It should also not set it; only
`eproject-maybe-turn-on' can do that.")
(make-variable-buffer-local 'eproject-root)
(defvar eproject-project-types nil
"An alist of project type name to (supertypes selector metadata-plist) pairs.")
(defvar eproject-extra-attributes nil
"A list of pairs used to assign attributes to projects.
Each entry can be in the form of `(FUNCTION (ATTRIBUTES))'
or `((KEY . TYPE) (ATTRIBUTES))'.
If FUNCTION is specified, it will be evaluated for each project
root. If it returns a non-nil value, ATTRIBUTES will be added to
the project attributes.
If `(KEY . TYPE)' is specified, then TYPE is either
`:root-regexp' or `:project-name' and KEY is interpreted
accordingly. If KEY matches a project root, its ATTRIBUTES are
applied.
ATTRIBUTES is a plist of attributes.")
(defvar eproject-attributes-alist nil
"An alist of project root -> plist of project metadata.")
(defvar eproject-first-buffer-hook nil
"Hook to run when the first buffer in a new project is opened.
Called after the project is initialized, so it's safe to call
eproject functions.")
(defvar eproject-projects-hook nil
"Hook that's run when a list of projects is requested. Hook may return a list of new (name . root) pairs to be added to eproject's internal list.")
(defvar eproject-project-change-hook nil
"Hook that's run when a project is changed; currently this means when a file in the project is saved.")
(defun define-project-attribute (key attributes)
"Define extra attributes to be applied to projects.
See `eproject-extra-attributes' for details on the format of KEY
and ATTRIBUTES."
(check-type key (or function cons))
(check-type attributes list)
(add-to-list 'eproject-extra-attributes (list key attributes)))
(defmacro define-project-type (type supertypes selector &rest metadata)
"Define a new project type TYPE that inherits from SUPERTYPES.
SELECTOR is a form that is given a filename FILE and returns the
project root if it is of this type of project, or NIL otherwise.
Optional argument METADATA is a plist of metadata that will
become project attributes."
`(progn
(defvar ,(intern (format "%s-project-file-visit-hook" type)) nil
,(format "Hooks that will be run when a file in a %s project is opened." type))
(setq eproject-project-types
(nconc (assq-delete-all ',type eproject-project-types)
(list
(list ',type ',supertypes
(lambda (file) ,selector)
',metadata))))))
(defun eproject--build-parent-candidates (start-at)
"Given directory START-AT, return a list of parent directories, including START-AT."
(loop for x on (reverse (eshell-split-path start-at)) by #'cdr
;; i think eshell-split-path guarantees the
;; file-name-as-directory application, but i don't want to
;; debug it if it doesn't :)
collect (file-name-as-directory (apply #'concat (reverse x)))))
(defun eproject--scan-parents-for (start-at predicate)
"Call PREDICATE with each parent directory of START-AT, returning the path to the first directory where PREDICATE returns T."
(find-if predicate (eproject--build-parent-candidates
(file-name-as-directory start-at))))
(defun eproject--find-file-named (start-at filename)
"Starting in directory START-AT, recursively check parent directories for a file named FILENAME. Return the directory where the file is first found; return NIL otherwise."
(eproject--scan-parents-for start-at
(lambda (directory) ; note that directory always has the path separator on the end
(file-exists-p (concat directory filename)))))
;; TODO: sugar around lambda/lambda, which is ugly
(define-project-type generic () nil
:relevant-files (".*")
:irrelevant-files ("^[.]" "^[#]")
:file-name-map (lambda (root) (lambda (root file) file))
:local-variables (lambda (root) (lambda (root file) nil))
:config-file ".eproject")
(define-project-type generic-eproject (generic) (look-for ".eproject"))
(define-project-type generic-git (generic) (look-for ".git")
:irrelevant-files ("^[.]" "^[#]" ".git/"))
(define-project-type generic-hg (generic) (look-for ".hg")
:irrelevant-files ("^[.]" "^[#]" ".hg/"))
(define-project-type generic-bzr (generic) (look-for ".bzr")
:irrelevant-files ("^[.]" "^[#]" ".bzr/"))
(define-project-type generic-darcs (generic) (look-for "_darcs")
:irrelevant-files ("^[.]" "^[#]" "_darcs/"))
(defun eproject--type-info (type)
(or
(assoc type eproject-project-types)
(error "No type %s" type)))
(defun eproject--project-supertypes (type)
(nth 1 (eproject--type-info type)))
(defun eproject--project-selector (type)
(nth 2 (eproject--type-info type)))
(defun* eproject--look-for-impl (file expression &optional (type :filename))
"Implements the LOOK-FOR function that is flet-bound during
`eproject--run-project-selector'. EXPRESSION and TYPE specify
what to look for. Some examples:
(look-for \"Makefile.PL\") ; look up the directory tree for a file called Makefile.PL
(look-for \"*.PL\" :glob) ; look for a file matching *.PL
"
(case type
(:filename (eproject--find-file-named file expression))
(:glob (eproject--scan-parents-for (file-name-directory file)
(lambda (current-directory)
(let ((default-directory current-directory))
(and (not (equal file current-directory))
(> (length (file-expand-wildcards expression)) 0))))))
(otherwise (error "Don't know how to handle %s in LOOK-FOR!" type))))
(defun eproject--buffer-file-name ()
(or (buffer-file-name) (and (derived-mode-p 'dired-mode)
(expand-file-name (if (consp dired-directory)
(car dired-directory)
dired-directory)))))
(defun* eproject--run-project-selector (type &optional (file (eproject--buffer-file-name)))
"Run the selector associated with project type TYPE."
(when (not file)
(error "Buffer '%s' has no file name" (current-buffer)))
(flet ((look-for (expr &optional (expr-type :filename))
(funcall #'eproject--look-for-impl file expr expr-type)))
(funcall (eproject--project-selector type) file)))
(defun eproject--linearized-isa (type &optional include-self)
(delete-duplicates
(append
(if include-self (list type))
(eproject--project-supertypes type)
(loop for stype in (eproject--project-supertypes type)
append (eproject--linearized-isa stype)))))
(defun eproject--all-types ()
;; this should be most specific to least specific, as long as nothing
;; is forward-referenced.
(reverse (mapcar #'car eproject-project-types)))
;; metadata vs. attributes:
;; * metadata is per-project-type
;; * attributes are per-project-root (and includes the project-type metadata)
(defun eproject--compute-all-applicable-metadata (type)
(loop for next-type in (eproject--linearized-isa type t)
append (nth 3 (eproject--type-info next-type))))
(defun eproject-get-project-metadatum (type key)
(getf (eproject--compute-all-applicable-metadata type) key))
(defun eproject-add-project-metadatum (type key value)
(setf (getf (nth 3 (assoc type eproject-project-types)) key) value))
(defmacro* eproject--do-in-buffer ((buffer) &body forms)
`(with-current-buffer ,buffer
(when (not eproject-mode)
(error "Buffer is not an eproject buffer!"))
,@forms))
(defun* eproject-root (&optional (buffer (current-buffer)))
"Return the value of the eproject variable root.
BUFFER defaults to the current buffer"
(eproject--do-in-buffer (buffer) eproject-root))
(defun* eproject-attribute (key &optional (root (eproject-root)))
"Lookup the attribute KEY for the eproject ROOT
ROOT defaults to the current buffer's project-root."
(getf (cdr (assoc root eproject-attributes-alist)) key))
(defun eproject--known-project-roots ()
"Return a list of projects roots that have been visisted this session."
(loop for (key . value) in eproject-attributes-alist collect key))
(defmacro define-eproject-accessor (variable)
"Create a function named eproject-VARIABLE that return the value of VARIABLE in the context of the current project."
(let ((sym (intern (format "eproject-%s" variable))))
`(defun* ,sym
(&optional (buffer (current-buffer)))
,(format "Return the value of the eproject variable %s. BUFFER defaults to the current buffer." variable)
(eproject-attribute ,(intern (format ":%s" variable))))))
(define-eproject-accessor type)
(define-eproject-accessor name)
(defun eproject-reinitialize-project ()
"Forget all project settings for the current eproject, then reload them."
(interactive)
(let ((root (eproject-root)))
(setf eproject-attributes-alist
(delete-if (lambda (x) (equal (car x) root))
eproject-attributes-alist)))
(eproject-maybe-turn-on)
(if (ignore-errors (eproject-root))
(message "Project `%s' reinitialized successfully." (eproject-name))
(message "Error reinitializing project!")))
(defun eproject--maybe-reinitialize ()
"Run by `eproject-project-change-hook' to reinit the project after .eproject is modified."
(when (and (eq major-mode 'dot-eproject-mode)
(boundp 'eproject-root) eproject-root)
(eproject-reinitialize-project)))
(defun eproject--eval-user-data (project-name root)
"Interpret EPROJECT-EXTRA-ATTRIBUTES for PROJECT-NAME (in ROOT)."
(loop for (key attributes) in eproject-extra-attributes append
(cond ((functionp key)
(if (funcall key root) attributes nil))
((not (listp key))
(error "Bad eproject user data (%s %s), %s must be a list/function"
key attributes key))
((and (eq (cdr key) :project-name)
(equal (car key) project-name))
attributes)
((and (eq (cdr key) :root-regexp)
(string-match (car key) root))
attributes)
(t nil))))
(defun eproject--interpret-metadata (data root)
"Interpret DATA with respect to ROOT.
This mostly means evaluating functions and passing everything
else through unchanged."
(loop for i in data collect (if (functionp i) (funcall i root) i)))
(defun eproject--init-attributes (root type)
"Update the EPROJECT-ATTRIBUTES-ALIST for the project rooted at ROOT (of TYPE)."
(let ((project-data (assoc root eproject-attributes-alist)))
(when (null project-data)
(let* ((class-data (eproject--interpret-metadata
(eproject--compute-all-applicable-metadata type)
root))
;; read the .eproject (or whatever) file
(config-file
(concat root (getf class-data :config-file ".eproject")))
(config-file-contents
(with-temp-buffer
(ignore-errors (insert-file-contents config-file nil nil nil t))
(buffer-substring-no-properties (point-min) (point-max))))
(config-file-sexp
(read (format "(list %s)" config-file-contents)))
(data-is-unsafe (unsafep config-file-sexp))
(config-file-data
(cond (data-is-unsafe
(warn "Config file %s contains unsafe data (%s), ignoring!"
config-file data-is-unsafe)
nil)
(t (let ((data (eval config-file-sexp)))
(if data (nconc
(list :loaded-from-config-file config-file)
data)
nil)))))
;; combine class and config data; config overriding class
(class-and-config-data (cond
;; ensure that the config-file-data is really a plist
((evenp (length config-file-data))
(nconc config-file-data class-data))
(t class-data)))
;; calculate the project name, as it's used by "user
;; data"
;; backcompat note: not sure why i looked in
;; :project-name for the value to set the :name attribute
;; to. so now we look in both, preferring the new way.
(name (or (getf class-and-config-data :name)
(getf class-and-config-data :project-name)
(directory-file-name
(elt (reverse (eshell-split-path root)) 0))))
;; finally, merge in the "user data"
(user-data
(eproject--interpret-metadata
(eproject--eval-user-data name root) root))
;; now compute the final list of attributes
(data (nconc user-data class-and-config-data)))
(add-to-list 'eproject-attributes-alist
(cons root (nconc (list :type type :name name) data)))))))
(defvar eproject-mode-map (make-sparse-keymap)
"Keybindings while in eproject-mode")
(define-minor-mode eproject-mode
"A minor mode for buffers that are a member of an eproject project."
nil " Project" eproject-mode-map
(when (null eproject-root)
(error "Please do not use this directly. Call eproject-maybe-turn-on instead.")))
(defun eproject-maybe-turn-on ()
"Turn on eproject for the current buffer, if it is in a project."
(interactive)
(let (bestroot besttype (set-before (mapcar #'car eproject-attributes-alist)))
(loop for type in (eproject--all-types)
do (let ((root (eproject--run-project-selector type)))
(when (and root
(or (not bestroot)
;; longest filename == best match (XXX:
;; need to canonicalize?)
(> (length root) (length bestroot))))
(setq bestroot root)
(setq besttype type))))
(when bestroot
(setq eproject-root (file-name-as-directory bestroot))
;; read .eproject file (etc.) and initialize at least :name and
;; :type
(condition-case e
(eproject--init-attributes eproject-root besttype)
(error (display-warning 'warning
(format "There was a problem setting up the eproject attributes for this project: %s" e))))
;; with :name and :type set, it's now safe to turn on eproject
(eproject-mode 1)
;; initialize buffer-local variables that the project defines
;; (called after we turn on eproject-mode, so we can call
;; eproject-* functions cleanly)
(condition-case e
(eproject--setup-local-variables)
(error (display-warning 'warning
(format "Problem initializing project-specific local-variables in %s: %s"
(eproject--buffer-file-name) e))))
;; run the first-buffer hooks if this is the first time we've
;; seen this particular project root.
(when (not (member eproject-root set-before))
(run-hooks 'eproject-first-buffer-hook))
;; run project-type hooks, which may also call into eproject-*
;; functions
(mapc (lambda (x) (run-hooks (intern (format "%s-project-file-visit-hook" x))))
(eproject--project-supertypes besttype))
(run-hooks (intern (format "%s-project-file-visit-hook" besttype)))
;; return the project root; it's occasionally useful for the caller
bestroot)))
(defun eproject--setup-local-variables ()
"Setup local variables as specified by the project attribute :local-variables."
(let* ((var-maker (eproject-attribute :local-variables))
(vars (cond ((functionp var-maker)
(funcall var-maker
(eproject-root)
(file-relative-name (eproject--buffer-file-name)
(eproject-root))))
((listp var-maker) var-maker))))
(loop for (name val) on vars by #'cddr do
(set (make-local-variable name) val))))
(defun eproject--search-directory-tree (directory file-regexp ignore-regexp)
(loop for file in (directory-files (file-name-as-directory directory) t "^[^.]" t)
unless (string-match ignore-regexp file)
if (not (file-directory-p file))
when (and (not (string-match ignore-regexp
(file-name-nondirectory file)))
(string-match file-regexp file))
collect file into files end
else
collect file into directories
finally return
(nconc files
(loop for dir in directories
nconc (eproject--search-directory-tree dir file-regexp
ignore-regexp)))))
(defun eproject-assert-type (type)
"Assert that the current buffer is in a project of type TYPE."
(when (not (memq type (eproject--linearized-isa (eproject-type) t)))
(error (format "%s is not in a project of type %s!"
(current-buffer) type))))
(defun eproject--combine-regexps (regexp-list)
"Combine regexps like `regexp-opt', but without quoting anything.
Argument REGEXP-LIST is a list of regexps to combine."
(format "\\(?:%s\\)"
(reduce (lambda (a b) (concat a "\\|" b))
(mapcar (lambda (f) (format "\\(?:%s\\)" f)) regexp-list))))
;;; TODO: cache this?
(defun eproject--file-check-regexps (root)
"Return a pair (matcher . ignore) for the project in ROOT."
(let ((matcher (eproject--combine-regexps
(eproject-attribute :relevant-files root)))
(ignore (eproject--combine-regexps
(cons
(concat (regexp-opt completion-ignored-extensions t) "$")
(eproject-attribute :irrelevant-files root)))))
(cons matcher ignore)))
(defun* eproject-classify-file (file &optional (root (eproject-root)))
"Return T if FILE would belong to the project in ROOT.
No check is done to ensure that the root subsumes FILE or even
that FILE is an absolute path."
;; XXX: this logic is sort of copied from search-directory-tree.
;; maybe combine?
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(and (not (string-match ignore file))
(not (string-match ignore (file-name-nondirectory file)))
(string-match matcher file)
t)))
(defun* eproject-list-project-files (&optional (root (eproject-root)))
"Return a list of all project files in PROJECT-ROOT."
(destructuring-bind (matcher . ignore) (eproject--file-check-regexps root)
(eproject--search-directory-tree root matcher ignore)))
(defun* eproject-list-project-files-relative (&optional (root (eproject-root)))
(mapcar (lambda (file)
(file-relative-name file root))
(eproject-list-project-files root)))
;;; dot-eproject mode
(define-derived-mode dot-eproject-mode emacs-lisp-mode "dot-eproject"
"Major mode for editing .eproject files."
(define-key dot-eproject-mode-map (kbd (concat eproject-keybind-prefix " C-c")) #'eproject-reinitialize-project))
;; introspect sets of projects
(defun eproject-projects ()
"Return a list of (name . root) pairs of all known eproject projects."
(let ((hash (make-hash-table :test 'equal)))
(loop for f in eproject-projects-hook do
(loop for (name . root) in (funcall f)
do (puthash name root hash)))
(loop for (root . rest)
in eproject-attributes-alist
do (puthash (or (getf rest :name) (getf rest :project-name))
root hash))
(loop for name being each hash-key in hash
collect (cons name (gethash name hash)))))
(defun eproject-project-names ()
"Return a list of project names known to eproject."
(mapcar #'car (eproject-projects)))
;; Finish up
(defun eproject--after-change-major-mode-hook ()
(when (and (buffer-file-name)
(not eproject-root))
(eproject-maybe-turn-on)))
(defun eproject--after-save-hook ()
;; TODO: perhaps check against relevant-files or irrelevant-files
;; regex? I'm avoiding this now because I'd rather not force the
;; speed hit -- if the user wants to do something slow after save,
;; fine... but I'd rather not make the decision for him.
(when (and (boundp 'eproject-root) eproject-root)
(run-hooks 'eproject-project-change-hook)))
(add-hook 'find-file-hook #'eproject-maybe-turn-on)
(add-hook 'dired-mode-hook #'eproject-maybe-turn-on)
(add-hook 'after-change-major-mode-hook #'eproject--after-change-major-mode-hook)
(add-hook 'after-save-hook #'eproject--after-save-hook)
(add-hook 'eproject-project-change-hook #'eproject--maybe-reinitialize)
(add-to-list 'auto-mode-alist '("\\.eproject\\'" . dot-eproject-mode))
(provide 'eproject)
;;; eproject.el ends here
|
[
{
"context": "programming language files.\n\n;; Copyright (C) 2015 Galen Liu\n;; Author: Galen Liu <galen.gang.liu at gmail.com",
"end": 132,
"score": 0.9998201131820679,
"start": 123,
"tag": "NAME",
"value": "Galen Liu"
},
{
"context": "files.\n\n;; Copyright (C) 2015 Galen Liu\n;; Author: Galen Liu <galen.gang.liu at gmail.com>\n\n;; This file is *N",
"end": 153,
"score": 0.9998379945755005,
"start": 144,
"tag": "NAME",
"value": "Galen Liu"
},
{
"context": "opyright (C) 2015 Galen Liu\n;; Author: Galen Liu <galen.gang.liu at gmail.com>\n\n;; This file is *NOT* part of GNU ",
"end": 169,
"score": 0.7660022377967834,
"start": 155,
"tag": "EMAIL",
"value": "galen.gang.liu"
},
{
"context": "\n (\"rst-mode\" \"rst\")\n ;; https://github.com/dominikh/go-mode.el.git\n (\"go-mode\" \"go\")\n (\"java-mo",
"end": 10568,
"score": 0.9996622204780579,
"start": 10560,
"tag": "USERNAME",
"value": "dominikh"
},
{
"context": "ile-gmake-mode\" \"make\")\n ;; https://github.com/mcandre/vimrc-mode.git\n (\"vimrc-mode\" \"vim\")\n (\"bat",
"end": 11203,
"score": 0.9993886947631836,
"start": 11196,
"tag": "USERNAME",
"value": "mcandre"
},
{
"context": "s.\n;; Exuberant Ctags 5.8, Copyright (C) 1996-2009 Darren Hiebert\n;; Compiled: Nov 9 2015, 15:37:41\n;; URL: ht",
"end": 34408,
"score": 0.9998757243156433,
"start": 34394,
"tag": "NAME",
"value": "Darren Hiebert"
},
{
"context": "ant Ctags 5.9~svn20110310, Copyright (C) 1996-2009 Darren Hiebert\n;; Addresses: <dhiebert@users.sourceforge.net>,",
"end": 34728,
"score": 0.9998784065246582,
"start": 34714,
"tag": "NAME",
"value": "Darren Hiebert"
},
{
"context": "ght (C) 1996-2009 Darren Hiebert\n;; Addresses: <dhiebert@users.sourceforge.net>, http://ctags.sourceforge.net\n;; Optional comp",
"end": 34776,
"score": 0.9999189376831055,
"start": 34746,
"tag": "EMAIL",
"value": "dhiebert@users.sourceforge.net"
}
] | taglist.el | liugang/taglist | 1 | ;;; taglist.el --- Taglist provides an overview of the structure of the programming language files.
;; Copyright (C) 2015 Galen Liu
;; Author: Galen Liu <galen.gang.liu at gmail.com>
;; This file is *NOT* part of GNU Emacs.
;; 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 of
;; the License, 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., 59 Temple Place, Suite 330, Boston,
;; MA 02111-1307 USA
;; Version: 1.0
;; Compatibility: Emacs 24
;;; Commentary:
;; The "Tag List" plugin is a source code browser plugin for Emacs and provides
;; an overview of the structure of the programming language files and allows you
;; to efficiently browse through source code files for different programming
;; languages.
;; It contains some useful functions features for developers:
;; 1) Tag navigation.
;;
;; When taglist-list-tags called, a new buffer is shown, containing list of
;; different type tags. You can select the tag moving to its line and press
;; ENTER to jump to the tag. You also can type a string in the buffer and tag
;; list will be reduced to those which contain the string as a substring.
;; Nice highlight is implemented.
;; 2) Header <-> Body file switch.
;;
;; You can easily switch between body (c, cpp, cc...) and its corresponding
;; header file (h, hpp...) using taglist-switch-h-cpp. The counterpart file
;; is first searched in opened buffers and if there is no match the file is
;; searched in the same directory. You can adjust body to header
;; correspondence customizing taglist-header-switches variable.
;; Taglist uses ctags as backend (https://ctags.io/ or http://ctags.sourceforge.net/)
;;; Usage:
;; 1) Install ctags(exuberant-ctags) package
;; 2) Add convenient keymaps for fast taglist calls in prog-mode
;;
;; (defun my-c-mode-common-hook ()
;; (define-key c-mode-base-map (kbd "M-o") 'taglist-switch-h-cpp)
;; (define-key c-mode-base-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
;;
;; (defun my-python-mode-hook ()
;; (define-key python-mode-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'python-mode-hook 'my-python-mode-hook)
;;
;; (define-key lisp-mode-shared-map (kbd "M-m") 'taglist-list-tags)
;;
;; 3) Open any programming file, press M-m. Try to type any tag name.
;;
;; 4) Open any .cpp file. Press M-o. If there is .h or .hpp file in the
;; same folder, it will be opened.
;;; Changelog:
;; 03 Nov 2015 -- v1.0 Initial version created.
;;; TODO:
;;; Code:
(require 'cl)
;; ================================== My STRING utils ========================
(defun taglist-string-without-last (string n)
"This function truncates from the STRING last N characters."
(substring string 0 (max 0(- (length string) n))))
(defun taglist-string-ends-with (string end)
"Check whether STRING ends with END substring."
(string= end (substring string (- (length end)))))
;; ================================== My STRING utils end ====================
;; ================================== CPP-H switch ===========================
;;;###autoload
(defvar taglist-header-switches '(("h" . ("cpp" "cc" "c"))
("hpp" . ("cpp" "cc"))
("cpp" . ("h" "hpp"))
("c" . ("h"))
("C" . ("H"))
("H" . ("C" "CPP" "CC"))
("cc" . ("h" "hpp")))
"This variable defines possible switches for `taglist-switch-h-cpp' function.
Its format is list of (from . (to1 to2 to3...)) elements. From and toN are
strings which are extentions of the files.")
;;;###autoload
(defun taglist-switch-h-cpp ()
"Switch header and body file according to `taglist-header-switches' var.
The current buffer's file name extention is searched in
`taglist-header-switches' variable to find out extention for file's counterpart,
for example *.hpp <--> *.cpp."
(interactive)
(let* ((ext (file-name-extension (buffer-file-name)))
(base-name (taglist-string-without-last (buffer-name) (length ext)))
(base-path (taglist-string-without-last (buffer-file-name) (length ext)))
(count-ext (cdr (find-if (lambda (i) (string= (car i) ext)) taglist-header-switches))))
(cond
(count-ext
(unless
(or
(loop for b in (mapcar (lambda (i) (concat base-name i)) count-ext)
when (bufferp (get-buffer b)) return (switch-to-buffer b))
(loop for c in (mapcar (lambda (count-ext) (concat base-path count-ext)) count-ext)
when (file-exists-p c) return (find-file c)))
(message "There is no corresponding pair (header or body) file.")))
(t
(message "It is not a header or body file! See taglist-header-switches variable.")))))
;; ================================== CPP-H switch end =========================
;; ================================== Tag navigator =========================
(defvar taglist-source-code-buffer nil
"Source code buffer")
(defvar taglist-all-tags nil
"Collection of tags used when searching for current selection.")
(defvar taglist-tmp-file nil
"save current buffer to a temp file. fix ctags can't open a gz
files, example: ido.el.gz")
(defvar taglist-actual-tags nil
"Collection of actual tags used when searching for current selection.")
(defvar taglist-search-string nil
"The current search string during a search.")
;; overlays, use hightlight tags
(defvar taglist-overlays nil
"List of active overlays.")
(defvar taglist-current-language nil
"current programming language.")
(defvar taglist-current-line nil
"current line")
(defvar taglist-current-major-mode nil
"current major mode")
(defface taglist-tag-type
'((((class color))
(:foreground "blue" :height 1.2))
(t (:weight bold)))
"Regexp matching the text identifying the file in `taglist-mode'."
:group 'taglist)
(defvar taglist-tag-type-face 'taglist-tag-type)
(defvar taglist-tag-type-re
(concat "^\\w.*$")
"Regexp matching the text identifying a tag type name.")
(defvar taglist-font-lock-keywords
;; We use `eval' so as to use the buffer-local value of taglist-tag-type-re if
;; applicable.
'((eval . `(,taglist-tag-type-re . taglist-tag-type-face))))
(defconst taglist-font-lock-defaults
'(taglist-font-lock-keywords t nil nil nil))
;; TODO: maintain the list by ctags --list-maps and
;; https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
;; format: (<file name pattern> <detected language>)
(defvar taglist-filename-to-language-alist
'(
("\\.i\\'" . "c")
("\\.lex\\'" . "c")
("\\.[ch]\\'" . "c")
("\\.x[bp]m\\'" . "c")
("\\.xs\\'" . "c")
("\\.h$" . "c++")
("\\.ii\\'" . "c++")
("\\.\\(CC?\\|HH?\\)\\'" . "c++")
("\\.[ch]\\(pp\\|xx\\|\\+\\+\\)\\'" . "c++")
("\\.\\(cc\\|hh\\)\\'" . "c++")
("\\.y\\(acc\\)?\\'" . "yacc")
("\\.vim\\(rc\\)?$" . "vim")
("\\.vim\\(rc\\|peratorrc\\)?$" . "vim")
("\\.exrc\\'" . "vim")
("[._]?g?vimrc\\'" . "vim")
("\\.vim\\'" . "vim")
("\\.go\\'" . "go")
("\\.l\\'" . "lisp")
("\\.li?sp\\'" . "lisp")
("\\.ml\\'" . "lisp")
("\\.asd\\'" . "lisp")
("\\.el\\'" . "lisp")
("Project\\.ede\\'" . "lisp")
("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . "lisp")
("\\`\\..*emacs\\'" . "lisp")
("[:/]_emacs\\'" . "lisp")
("\\.[tT]e[xX]\\'" . "tex")
("\\.ins\\'" . "tex")
("\\.sty\\'" . "tex")
("\\.cl[so]\\'" . "tex")
("\\.bbl\\'" . "tex")
("\\.ltx\\'" . "tex")
("\\.html?\\'" . "html")
("\\.djhtml\\'" . "html")
("\\.phtml\\'" . "html")
("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . "html")
("\\.as[cp]x\\'" . "asp")
("\\.asp\\'" . "asp")
("\\.php\\'" . "php")
("/crontab\\.X*[0-9]+\\'" . "sh")
("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . "sh")
("\\.bash\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . "sh")
("\\.m?spec\\'" . "sh")
("\\(?:\\.rb\\|ru\\|rake\\|thor\\|jbuilder\\|gemspec\\|podspec\\|/\\(?:Gem\\|Rake\\|Cap\\|Thor\\|Vagrant\\|Guard\\|Pod\\)file\\)\\'" . "ruby")
("\\.py\\'" . "python")
("\\.awk\\'" . "awk")
("\\.java\\'" . "java")
("\\.m\\'" . "objc")
("\\.\\(bat\\|cmd\\)\\'" . "dosbatch")
("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . "scheme")
("\\.scm\\.[0-9]*\\'" . "scheme")
("\\.oak\\'" . "scheme")
("\\.[fF]\\'" . "fortran")
("\\.for\\'" . "fortran")
("\\.f9[05]\\'" . "fortran")
("\\.f0[38]\\'" . "fortran")
("\\.p\\'" . "pascal")
("\\.pas\\'" . "pascal")
("\\.ad[abs]\\'" . "ada")
("\\.ad[bs].dg\\'" . "ada")
("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . "perl")
("\\.mk\\'" . "make")
("\\.make\\'" . "make")
("[Mm]akefile\\'" . "make")
("\\.[sS]\\'" . "asm")
("\\.asm\\'" . "asm")
("/\\.[a-z0-9-]*gdbinit" . "gdb-script")
("-gdb\\.gdb" . "gdb-script")
("\\.sql\\'" . "sql")
("\\.m[4c]\\'" . "m4")
("\\.i?tcl\\'" . "tcl")
("\\.exp\\'" . "tcl")
("\\.itk\\'" . "tcl")
("\\.svgz?\\'" . "xml")
("\\.x[ms]l\\'" . "xml")
("\\.dbk\\'" . "xml")
("\\.js\\'" . "javascript")
("\\.json\\'" . "javascript")
("\\.[ds]?vh?\\'" . "verilog")
("\\.vhdl?\\'" . "vhdl")
("\\.re?st\\'" . "reStructuredText")
)
)
;; major mode name map to language
;; (add-to-list 'taglist-major-to-language-alist '("<lang>-mode" "<lang>"))
;; format: (<major mode> <detected language>)
(defvar taglist-major-to-language-alist
`(
("emacs-lisp-mode" "lisp")
("lisp-mode" "lisp")
("c-mode" "c")
("c++-mode" "c++")
;; rust is support at https://github.com/universal-ctags
("rst-mode" "rst")
;; https://github.com/dominikh/go-mode.el.git
("go-mode" "go")
("java-mode" "java")
("python-mode" "python")
("ruby-mode" "ruby")
("js-mode" "javascript")
("objc-mode" "objectivec")
("asm-mode" "asm")
("sh-mode" "sh")
("shell-script-mode" "sh")
("sql-mode" "sql")
("tcl-mode" "tcl")
("fortran-mode" "fortran")
("f90-mode" "fortran")
("scheme-mode" "scheme")
("pascal-mode" "pascal")
("perl-mode" "perl")
("verilog-mode" "verilog")
("vhdl-mode" "vhdl")
("awk-mode" "awk")
("html-mode" "html")
("latex-mode" "tex")
("makefile-gmake-mode" "make")
;; https://github.com/mcandre/vimrc-mode.git
("vimrc-mode" "vim")
("bat-mode" "dosbatch")
("rst-mode" "reStructuredText")
))
;; TODO: maintain the list by ctags --list-kinds
;; format: (<detected language> <ctags language>;<short-kind:full-kind>....)
(defvar taglist-language-to-ctags-alist
`(
;; Ant language
("ant" "Ant;p:projects;t:targets")
;; assembly language
("asm" "Asm;d:define;l:label;m:macro;t:type")
;; aspperl language
("aspperl" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; aspvbs language
("aspvbs" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; awk language
("awk" "Awk;f:function")
;; basic language
("basic" "Basic;c:constant;l:label;g:enum;v:variable;t:type;f:function")
;; beta language
("beta" "BETA;f:fragment;s:slot;v:pattern")
;; c language
("c" "C;c:classes;d:macro definitions;g:enumeration names;\
n:namespaces;s:structure names;t:typedefs;\
u:union names;v:variable definitions;f:function definitions")
;; c++ language
("c++" "C++;n:namespace;v:variable;d:macro;t:typedef;\
c:class;g:enum;s:struct;u:union;f:function")
;; c# language
("cs" "C#;d:macro;t:typedef;n:namespace;c:class;E:event;\
g:enum;s:struct;i:interface;p:properties;m:method")
;; cobol language
("cobol" "Cobol;d:data;f:file;g:group;p:paragraph;\
P:program;s:section")
;; D programming language
("d" "C++;n:namespace;v:variable;t:typedef;c:class;\
g:enum;s:struct;u:union;f:function")
;; Dosbatch
("dosbatch" "DosBatch;l:labels;v:variables")
;; eiffel language
("eiffel" "Eiffel;c:class;f:feature")
;; erlang language
("erlang" "Erlang;d:macro;r:record;m:module;f:function")
;; expect (same as tcl) language
("expect" "Tcl;c:class;f:method;p:procedure")
;; flex
("flex" "Flex;v:global;c:classes;p:properties;m:methods;f:functions;x:mxtags")
;; fortran language
("Fortran" "fortran;p:program;b:block data;c:common;e:entry;\
i:interface;k:type;l:label;m:module;n:namelist;t:derived;v:variable;\
f:function;s:subroutine")
;; GO language
("go" "Go;p:packages;c:constants;t:types;v:variables;s:structs;i:interfaces;m:struct members;f:functions")
("objectivec" "ObjectiveC;i:class interface;I:class implementation;P:Protocol;m:Object's method;\
c:Class' method;v:Global variable;F:Object field;f:A function;p:A property;t:A type alias;\
s:A type structure;e:An enumeration;MA preprocessor macro")
;; HTML language
("html" "HTML;a:anchor;f:function")
;; java language
("java" "Java;p:package;c:class;i:interface;g:enum;f:field;m:method")
;; javascript language
("javascript" "JavaScript;c:class;m:method;v:global;f:function;p:properties;C:constants")
;; lisp language
("lisp" "Lisp;v:variable;f:function;c:custom")
;; lua language
("lua" "Lua;f:function")
;; makefiles
("make" "Make;m:macro;t:targets")
;; Matlab
("matlab" "MatLab;f:function")
;; Ocamal
("ocamal" "OCaml;M:module;v:global;t:type;c:class;\
f:function;m:method;C:constructor;e:exception")
;; pascal language
("pascal" "Pascal;f:function;p:procedure")
;; perl language
("perl" "Perl;f:formats;c:constant;l:label;p:package;s:subroutine")
;; Perl6
("perl6" "Perl6;c:classes;g:grammars;m:methods;o:modules;p:packages;r:roles;u:rules;b:submethods;s:subroutines:t:tokens")
;; php language
("php" "PHP;c:classes;d:constant definitions;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
;; python language
("python" "Python;i:imports;c:classes;m:class members;v:variables;f:functions;")
;; cython language
("pyrex" "Python;c:classe;m:memder;f:function")
;; rexx language
("rexx" "REXX;s:subroutine")
;; ruby language
("ruby" "Ruby;c:class;f:method;F:function;m:singleton method")
;; scheme language
("Scheme" "scheme;s:set;f:function")
;; shell language
("sh" "Sh;f:function")
;; C shell language
("csh" "Sh;f:function")
;; Z shell language
("zsh" "Sh;f:function")
;; slang language
("slang" "SLang;n:namespace;f:function")
;; sml language
("sml" "SML;e:exception;c:functor;s:signature;r:structure;\
t:type;v:value;c:functor;f:function")
;; sql language
("sql" "SQL;f:functions;P:packages;p:procedures;t:tables;T:triggers;\
v:variables;e:events;U:publications;R:services;D:domains;x:MLTableScripts;\
y:MLConnScripts;z:MLProperties;i:indexes;c:cursors;V:views;d:prototypes;\
l:local variables;F:record fields;L:block label;r:records;s:subtypes")
;; tcl language
("tcl" "Tcl;c:class;f:method;m:method;p:procedure")
;; Tex
("tex" "Tex;c:chapters;s:sections;u:subsections;b:subsubsections;\
p:parts;P:paragraphs;G:subparagraphs")
;; vera language
("vera" "Vera;c:class;d:macro;e:enumerator;f:function;g:enum;m:member;\
p:program;P:prototype;t:task;T:typedef;v:variable;x:externvar")
;; verilog language
("verilog" "Verilog;c:constants;e:events;m:modules;n:net data types;p:ports;r:register data types;t:tasks;b:blocks;f:functions")
;; VHDL
("vhdl" "VHDL;c:constant;t:type;T:subtype;r:record;e:entity;\
f:function;p:procedure;P:package")
;; vim language
("vim" "Vim;v:variable;a:autocmds;c:commands;m:map;n:vimball filename;f:function")
;; yacc language
("yacc" "YACC;l:label")
("zephir" "Zephir;c:classes;d:constant;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
("windres" "WindRes;d:dialogs;m:menus;i:icons;b:bitmaps;c:cursors;f:fonts;v:versions;a:accelerators")
("systemverilog" "SystemVerilog;c:constants;e:events;m:modules;n:net data types;p:ports;\
r:register data types;t:tasks;b:blocks;A:assertions;C:classes;V:covergroups;I:interfaces;M:modports;\
K:packages;P:programs;R:properties;T:type declarations;f:functions" )
("rust" "Rust;n:module;s:structural type;i:trait interface;c:implementation;g:Enum;t:Type Alias;\
v:Global variable;M:Macro Definition;m:A struct field;e:An enum variant;F:A method;f:Function")
("reStructuredText" "reStructuredText;c:chapters;s:sections;S:subsections;t:subsubsections")
("r" "R;l:libraries;s:sources;g:global variables;v:function variables;f:functions")
("json" "JSON;o:objects;a:arrays;n:numbers;s:strings;b:booleans;z:nulls")
;; ("gdb-script" "gdbinit;d:definition;t:toplevelVariable") ;; disabled
;; ("m4" "m4;d:definition;u:undefinition;") ;; disabled
))
(defun taglist-goto-line (N)
"goto specified line <N>"
(goto-char (point-min))
(forward-line (1- N)))
(defun taglist-detect-language-by-major-mode ()
"detect language by modeline"
(let ((language nil)
(i 0))
(while (and
(not language)
(< i (length taglist-major-to-language-alist)))
(if (string= taglist-current-major-mode (car (elt taglist-major-to-language-alist i)))
(setq language (nth 1 (elt taglist-major-to-language-alist i))))
(setq i (1+ i)))
;; (message "detect language by major mode = %s" language)
language))
;; TODO, for vim
(defun taglist-detect-language-by-modeline ()
"detect language by modeline"
(let ((language nil))
;; (setq language nil)
language))
;; TODO
(defun taglist-detect-language-by-shebang ()
"detect language by shebang"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language-by-filename ()
"detect language by filename"
(let ((detected-language nil)
(language nil)
(filename (buffer-file-name taglist-source-code-buffer)))
;; Next compare the filename against the entries in taglist-filename-to-language-alist.
(if filename
(let ((name filename)
(remote-id (file-remote-p filename)))
;; Remove backup-suffixes from file name.
(setq name (file-name-sans-versions name))
;; Remove remote file name identification.
(when (and (stringp remote-id)
(string-match (regexp-quote remote-id) name))
(setq name (substring name (match-end 0))))
(while name
;; Find first matching alist entry.
(setq language
(if (memq system-type '(windows-nt cygwin))
;; System is case-insensitive.
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; System is case-sensitive.
(or
;; First match case-sensitively.
(let ((case-fold-search nil))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; Fallback to case-insensitive match.
(and auto-mode-case-fold
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))))))
(if (and language
(consp language)
(cadr language))
(setq language (car language)
name (substring name 0 (match-beginning 0)))
(setq name nil))
(when language
(setq detected-language language))
)
)
)
detected-language))
;; TODO
(defun taglist-detect-language-by-heuristics ()
"detect language by heuristics"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language ()
"return programming language of the file"
(let ((language (taglist-detect-language-by-major-mode)))
;;(let ((language nil)) ;; for test
(if (not language)
(setq language (taglist-detect-language-by-modeline)))
(if (not language)
(setq language (taglist-detect-language-by-shebang)))
(if (not language)
(setq language (taglist-detect-language-by-filename)))
(if (not language)
(setq language (taglist-detect-language-by-heuristics)))
;; (message "last language = %s" language)
language))
(defun taglist-get-ctags-language-config (detected-language)
"get ctags language config"
(let ((language-config nil)
(i 0))
(while (and
(not language-config)
(< i (length taglist-language-to-ctags-alist)))
(if (string= detected-language (car (elt taglist-language-to-ctags-alist i)))
(progn
(setq language-config (nth 1 (elt taglist-language-to-ctags-alist i)))))
(setq i (1+ i)))
(if (not language-config)
(error "Unsupported language: %s" detected-language))
language-config))
(defun taglist-get-ctags-language-name (detected-language)
"get ctags-language by detected-language e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"C\""
(let ((ctags-language-config (taglist-get-ctags-language-config detected-language))
(ctags-language nil))
(setq ctags-language (car (split-string ctags-language-config ";" t)))
ctags-language))
(defsubst taglist-filter-unsupport-kinds (ctags-language expect-ctags-kinds)
"Return the supported kinds of current version `ctags'."
(let ((all-kinds nil)
(ctags-config nil)
(actual-ctags-kinds expect-ctags-kinds)
)
(setq all-kinds
(mapcar (lambda (line) (substring line 0 1) )
(split-string
(apply
#'taglist-ctags-process-string
"ctags" (append
(list (concat "--list-kinds=" ctags-language)))) "\n" t)))
(let ((found nil)
(element nil)
(i 0))
(dolist (kind expect-ctags-kinds)
(setq found nil)
(setq i 0)
(while (and (not found)
(< i (length all-kinds)))
(setq element (elt all-kinds i))
(if (string= (substring kind 0 1) element)
(setq found t))
(setq i (1+ i)))
(if (not found)
(progn
(setq actual-ctags-kinds (remove kind actual-ctags-kinds))))))
actual-ctags-kinds))
(defun taglist-get-ctags-language-full-kinds (detected-language)
"Get full ctags language kinds by detected-language. e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return a list (\"d:macro\" \"g:enum\" \"s:struct\" \"u:union\"
\"t:typedef\" \"v:variable\" \"f:function\")"
(let* ((ctags-language-config-string (taglist-get-ctags-language-config detected-language))
(ctags-language-config (split-string ctags-language-config-string ";" t))
(ctags-language-kinds nil))
(setq ctags-language-kinds (taglist-filter-unsupport-kinds
(car ctags-language-config)
(cdr ctags-language-config)))
ctags-language-kinds))
(defun taglist-get-ctags-language-short-kinds (detected-language)
"get kinds by detected-language.
e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"dgsutvf\""
(let ((kinds ""))
(dolist (element (taglist-get-ctags-language-full-kinds detected-language))
(setq kinds (concat kinds (substring element 0 1))))
kinds))
(defun taglist-get-tag-lines ()
"Return all tags of current buffer;"
(let* ((detected-language (taglist-detect-language))
(ctags-language (taglist-get-ctags-language-name detected-language))
(ctags-lang-kinds (taglist-get-ctags-language-short-kinds detected-language))
(file (buffer-file-name taglist-source-code-buffer)))
(setq taglist-current-language detected-language)
(if file
(split-string
(apply #'taglist-ctags-process-string
"ctags"
(append (list "-f" "-"
"--format=2"
"--excmd=number"
"--fields=nks"
"--sort=no"
(concat "--language-force=" ctags-language)
(concat "--" ctags-language "-kinds=" ctags-lang-kinds)
taglist-tmp-file
)))
"\n" t)
(insert (concat "Warnning: " (buffer-name taglist-source-code-buffer) " doesn't exist on your disk, you should save it first!\n"))
nil)))
;; e.g. tagline = main /path/to/src/ip46.c 38;" f line:38
(defun taglist-convert-to-elements (tagline)
"Convert tagline to a tag(tag-name tag-line tag-type) "
(let ((elements (split-string tagline "\t" t)))
(list (car elements) (string-to-number (nth 2 elements)) (nth 3 elements))))
(defun taglist-jump-to-tag ()
"Jump to a tag, corresponding the current line in tag buffer.
When called standing on a line of tag list, it closes the list
buffer and sets the point to a tag, corresponding the line."
(interactive)
(let ((tag-record (nth (1- (line-number-at-pos)) taglist-actual-tags)))
(if (and tag-record (= 0 (taglist-line tag-record)))
(setq tag-record (nth (line-number-at-pos) taglist-actual-tags)))
(if (and tag-record (taglist-line tag-record))
(progn
(kill-buffer (current-buffer))
(switch-to-buffer taglist-source-code-buffer t)
(taglist-goto-line (taglist-line tag-record))
(recenter))
(message "The line does not contain tag description!"))))
(defun taglist-matches-all (string substrings)
"Return non-nil if STRING contain each of SUBSTRINGS as a substring."
(reduce (lambda (prev part) (and prev (string-match part string))) substrings :initial-value t))
(defstruct taglist
(tag) ;; tag name, e.g. main
(line) ;; line number of tag, e.g. 11
(type) ;; type of the tag: e.g. f
)
(defun taglist-gen-display-struct (types taglines)
"Return a list of three strings, representing type, parent and name of tag F."
;; (message "types = %s, taglines = %s" types taglines)
(let ((tags-struct nil))
;; loop for each tag type
(dolist (tag-type types)
(let* ((element (split-string tag-type ":" t))
(type-abbr (car element))
(type-name (nth 1 element))
(type-occur nil)
)
;; (message "%s %s" type-abbr type-name)
;; loop for all taglines
(dolist (tagline taglines)
;; tagline (main 38 f)
;; when current tag type matched
(when (string= type-abbr (nth 2 tagline))
(if type-occur ;; when current tag is not first time appear.
;; (message "%s" tagline)
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; if current tag is first time appear, then display type name and current tag.
(setq tags-struct (append tags-struct (list (make-taglist :tag type-name :line 0 :type ""))))
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; (message "%s" type-name)
;; (message "%s" tagline)
(setq type-occur t))))))
;; (message "tags-struct = %s" tags-struct)
;; return tags-struct
tags-struct)
)
(defun taglist-search-string-updated ()
"Update tag list according to search string."
(message taglist-search-string)
;; let s:tlist_def_c_settings = 'c;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function'
;; (setq types (list "d:Macro" "g:Enum" "s:Struct" "u:Union" "t:Typedef" "v:Variable" "f:Function"))
(let ((types (taglist-get-ctags-language-full-kinds taglist-current-language))
(taglist-actual-tags-tmp
;; remove-if-not: Remove all items not satisfying search string.
(remove-if-not
(lambda (element)
(taglist-matches-all (car element) (split-string taglist-search-string)))
taglist-all-tags)))
;; ("DEBUG" 11 "d") ("main" 18 "f")
(setq taglist-actual-tags (taglist-gen-display-struct types taglist-actual-tags-tmp)))
;; (message "taglist-actual-tags = %S" taglist-actual-tags)
(erase-buffer)
(dolist (i taglist-overlays)
;; Delete the overlay from its buffer.
(delete-overlay i))
(setq taglist-overlays nil)
;; [cl-struct-taglist "main" 38 "f"]
(dolist (tag-record taglist-actual-tags)
(insert (concat (taglist-tag tag-record) "\n")))
(let ((offset 0)
(pos 0)
(line-pos nil)
(tag-record nil)
(output (buffer-string))
(search-strings (split-string taglist-search-string)))
(dolist (search-string search-strings)
(while (string-match search-string output offset)
(progn
(setq pos (match-beginning 0))
(setq offset (match-end 0))
;; match: start form 0, overlay: start from 1;
(setq tag-record (nth (1- (line-number-at-pos pos)) taglist-actual-tags))
(if (not (= 0 (taglist-line tag-record)))
(progn
(push (make-overlay (+ 1 pos) (+ 1 offset)) taglist-overlays)
(overlay-put (car taglist-overlays) 'face '(background-color . "yellow"))
(if (not line-pos)
(setq line-pos (line-number-at-pos pos)))
)))))
(if line-pos
(taglist-goto-line line-pos)
(taglist-goto-line (+ 1 (/ (count-lines (point-min) (point-max)) 2)))))
)
(defun taglist-key-pressed (key)
"Called when KEY is pressed."
(setq taglist-search-string (concat taglist-search-string (char-to-string key)))
(taglist-search-string-updated))
(defun taglist-backspace-pressed ()
"Called when Backspace is pressed."
(interactive)
(setq taglist-search-string (taglist-string-without-last taglist-search-string 1))
(taglist-search-string-updated))
(defun taglist-make-key-function (key)
"Return a function for KEY."
`(lambda () (interactive) (taglist-key-pressed ,key)))
(defun taglist-key-itself (map key)
"Maps in the MAP KEY to its function."
(define-key map (char-to-string key) (taglist-make-key-function key)))
(defun taglist-escape ()
"Kill tag list buffer."
(interactive)
(kill-buffer (current-buffer))
(delete-file taglist-tmp-file)
(switch-to-buffer taglist-source-code-buffer))
(defvar taglist-mode-map
(let ((map (make-sparse-keymap)))
(suppress-keymap map)
(do ((k (string-to-char "a") (+ 1 k))) ((> k (string-to-char "z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "A") (+ 1 k))) ((> k (string-to-char "Z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "0") (+ 1 k))) ((> k (string-to-char "9")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(dolist (k (string-to-list "=><&!"))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(taglist-key-itself map (string-to-char " "))
(taglist-key-itself map (string-to-char "_"))
(define-key map (kbd "<RET>") 'taglist-jump-to-tag)
(define-key map (kbd "<backspace>") 'taglist-backspace-pressed)
;; Cause M-v doesn't work!!!
;; (define-key map (kbd "<ESC>") 'taglist-escape)
(define-key map (kbd "C-q") 'taglist-escape)
(define-key map (kbd "M-q") 'taglist-escape)
(define-key map "\C-v" 'scroll-up)
(define-key map "\M-v" 'scroll-down)
map)
"Keymap for `taglist-mode'.")
(defcustom ctags-executable-directory nil
"If non-nil the directory to search global executables."
:type '(choice (const :tag "Unset" nil) directory)
:risky t
:group 'ctags)
(defun taglist-ctags-program-path (name)
(if ctags-executable-directory
;; (expand-file-name NAME &optional DEFAULT-DIRECTORY)
;; Convert filename NAME to absolute, and canonicalize it.
(expand-file-name name ctags-executable-directory)
name))
(defun taglist-ctags-process-string (program &rest args)
(with-temp-buffer
;; (process-file PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS)
;; Process files synchronously in a separate process.
(let ((exit (apply #'process-file
(taglist-ctags-program-path program) nil t nil args))
(output (progn
(goto-char (point-max))
(skip-chars-backward " \t\n")
(buffer-substring (point-min) (point)))))
(or (zerop exit)
(error "`%s' non-zero exit: %s" program output))
output)))
;; /usr/local/bin/ctags --version
;; Universal Ctags Development(ebe7328), Copyright (C) 2015 Universal Ctags Team
;; Universal Ctags is derived from Exuberant Ctags.
;; Exuberant Ctags 5.8, Copyright (C) 1996-2009 Darren Hiebert
;; Compiled: Nov 9 2015, 15:37:41
;; URL: https://ctags.io/
;; Optional compiled features: +wildcards, +regex, +debug, +option-directory, +coproc
;; ctags-exuberant --version
;; ctags-exuberant: Warning: Ignoring non-option in ./.ctags
;; Exuberant Ctags 5.9~svn20110310, Copyright (C) 1996-2009 Darren Hiebert
;; Addresses: <dhiebert@users.sourceforge.net>, http://ctags.sourceforge.net
;; Optional compiled features: +wildcards, +regex
;; ctags.emacs24 --version
;; ctags (GNU Emacs 24.5)
;; Copyright (C) 2015 Free Software Foundation, Inc.
;; This program is distributed under the terms in ETAGS.README
(defsubst taglist-ctags-variant ()
"Return the variant of `ctags'."
(let ((buffer-string nil)
(ctags-variant nil ))
(setq buffer-string (apply #'taglist-ctags-process-string
"ctags" (append (list "--version"))))
(if (string-match "Emacs" buffer-string 0)
(setq ctags-variant "emacs-ctags")
(if (string-match "Universal" buffer-string 0)
(setq ctags-variant "universal-ctags")
(if (string-match "Exuberant" buffer-string 0)
(setq ctags-variant "exuberant-ctags"))))
ctags-variant))
(defun taglist-highlight-current-tag ()
"Highlight current tag line"
;; taglist-all-tags =
;; (("INET_ADDRSTRLEN" 17 "d")
;; ("INET6_ADDRSTRLEN" 18 "d")
;; ("ZERO" 19 "d")
;; ("BUF_SIZE" 20 "d")
;; ("global_var" 22 "v")
;; ("IP4_2_6" 24 "f")
;; ("IP6_2_4" 31 "f")
;; ("main" 38 "f"))
;; get current line number; and find range of line nubmer in taglist-all-tags
;; Set current line corresponding to the current function/tag if any
(let ((prev-line 0)
(curr-line 0)
(tag-line 0)
(i 0))
(while (and
(= 0 tag-line)
(< i (length taglist-all-tags)))
(setq curr-line (nth 1 (elt taglist-all-tags i)))
(setq i (1+ i))
;; (message "taglist-current-line = %d, prev-line = %d curr-line = %d, tag-line = %d"
;; taglist-current-line
;; prev-line
;; curr-line
;; tag-line)
(if (= taglist-current-line curr-line)
;; best case
(setq tag-line curr-line)
(if (< taglist-current-line curr-line)
;; if current line in source code buffer less than the line number
;; of current encounter tag in taglist, then choose the line number
;; of previous tags.
(if (= 0 prev-line)
;; if line number of previous tag is zero, then choose the line
;; number of current tag
(setq tag-line curr-line)
(setq tag-line prev-line)
)
;; if current line in source code buffer is big than the line number
;; of current encounter tag in taglist, then continue loop.
))
;; (message "tag-line = %d" tag-line)
(setq prev-line curr-line))
(if (= 0 tag-line)
(setq tag-line prev-line))
;; (message "found tag-line = %d" tag-line)
(let ((line (position-if
(lambda (item) (= tag-line (taglist-line item)))
taglist-actual-tags)))
(when line
(taglist-goto-line (1+ line)))))
(hl-line-mode))
;;;###autoload
(defun taglist-list-tags ()
"Show tag list of current buffer in a newly created buffer.
This function is recommended to be bound to some convinient hotkey."
(interactive)
;; (message "taglist-ctags-variant = %s" (taglist-ctags-variant))
(if (string= (taglist-ctags-variant) "emacs-ctags")
(error "taglist doesn't support emacs ctags, please install universal-ctags or exuberant-ctags!")
)
(setq taglist-source-code-buffer (current-buffer))
(setq taglist-current-line (line-number-at-pos))
(setq taglist-current-major-mode major-mode)
(setq taglist-tmp-file (make-temp-file "taglist."))
(write-region (point-min) (point-max) taglist-tmp-file)
(switch-to-buffer (get-buffer-create (concat (buffer-name (current-buffer)) " tag list")) t)
(taglist-mode))
(defun taglist-mode-init ()
"Initialize tag list mode."
;; current tag search string
(make-local-variable 'taglist-search-string)
;; list of taglist-tag structures
(make-local-variable 'taglist-all-tags)
;; subset of taglist-all-tags that contain taglist-search string in the name string
(make-local-variable 'taglist-actual-tags)
;; overlays used to highligh search string matches in tag names
(make-local-variable 'taglist-overlays)
(make-local-variable 'taglist-current-language)
(set (make-local-variable 'font-lock-defaults) taglist-font-lock-defaults)
;; (message "current-line = %d" taglist-current-line)
(setq taglist-overlays nil)
(setq taglist-search-string "")
(setq taglist-all-tags
(let* ((tag-lines (taglist-get-tag-lines)))
(if tag-lines
(mapcar 'taglist-convert-to-elements tag-lines))))
(if (not taglist-all-tags)
(insert "No taglist, Press <C-q> or <M-q> to exist!!!\n")
(taglist-search-string-updated)
(taglist-highlight-current-tag)))
(define-derived-mode taglist-mode nil "Taglist"
"EmacsAssist tag selection mode.
\\{taglist-mode-map}
Turning on Text mode runs the normal hook `taglist-mode-hook'."
(taglist-mode-init))
;; ================================== Tag navigator end ======================
(provide 'taglist)
;;; taglist.el ends here
;; taglist.el:122:70:Warning: function `find-if' from cl package called at runtime
;; taglist.el:632:96:Warning: function `reduce' from cl package called at runtime
;; taglist.el:698:11:Warning: function `remove-if-not' from cl package called at runtime
;; taglist.el:902:18:Warning: function `position-if' from cl package called at runtime
;; [PATCH] emacs: Suppress warnings about using cl at runtime
;; https://notmuchmail.org/pipermail/notmuch/2012/010297.html
;; Local Variables:
;; byte-compile-warnings: (not cl-functions)
;; End:
| 3562 | ;;; taglist.el --- Taglist provides an overview of the structure of the programming language files.
;; Copyright (C) 2015 <NAME>
;; Author: <NAME> <<EMAIL> at gmail.com>
;; This file is *NOT* part of GNU Emacs.
;; 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 of
;; the License, 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., 59 Temple Place, Suite 330, Boston,
;; MA 02111-1307 USA
;; Version: 1.0
;; Compatibility: Emacs 24
;;; Commentary:
;; The "Tag List" plugin is a source code browser plugin for Emacs and provides
;; an overview of the structure of the programming language files and allows you
;; to efficiently browse through source code files for different programming
;; languages.
;; It contains some useful functions features for developers:
;; 1) Tag navigation.
;;
;; When taglist-list-tags called, a new buffer is shown, containing list of
;; different type tags. You can select the tag moving to its line and press
;; ENTER to jump to the tag. You also can type a string in the buffer and tag
;; list will be reduced to those which contain the string as a substring.
;; Nice highlight is implemented.
;; 2) Header <-> Body file switch.
;;
;; You can easily switch between body (c, cpp, cc...) and its corresponding
;; header file (h, hpp...) using taglist-switch-h-cpp. The counterpart file
;; is first searched in opened buffers and if there is no match the file is
;; searched in the same directory. You can adjust body to header
;; correspondence customizing taglist-header-switches variable.
;; Taglist uses ctags as backend (https://ctags.io/ or http://ctags.sourceforge.net/)
;;; Usage:
;; 1) Install ctags(exuberant-ctags) package
;; 2) Add convenient keymaps for fast taglist calls in prog-mode
;;
;; (defun my-c-mode-common-hook ()
;; (define-key c-mode-base-map (kbd "M-o") 'taglist-switch-h-cpp)
;; (define-key c-mode-base-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
;;
;; (defun my-python-mode-hook ()
;; (define-key python-mode-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'python-mode-hook 'my-python-mode-hook)
;;
;; (define-key lisp-mode-shared-map (kbd "M-m") 'taglist-list-tags)
;;
;; 3) Open any programming file, press M-m. Try to type any tag name.
;;
;; 4) Open any .cpp file. Press M-o. If there is .h or .hpp file in the
;; same folder, it will be opened.
;;; Changelog:
;; 03 Nov 2015 -- v1.0 Initial version created.
;;; TODO:
;;; Code:
(require 'cl)
;; ================================== My STRING utils ========================
(defun taglist-string-without-last (string n)
"This function truncates from the STRING last N characters."
(substring string 0 (max 0(- (length string) n))))
(defun taglist-string-ends-with (string end)
"Check whether STRING ends with END substring."
(string= end (substring string (- (length end)))))
;; ================================== My STRING utils end ====================
;; ================================== CPP-H switch ===========================
;;;###autoload
(defvar taglist-header-switches '(("h" . ("cpp" "cc" "c"))
("hpp" . ("cpp" "cc"))
("cpp" . ("h" "hpp"))
("c" . ("h"))
("C" . ("H"))
("H" . ("C" "CPP" "CC"))
("cc" . ("h" "hpp")))
"This variable defines possible switches for `taglist-switch-h-cpp' function.
Its format is list of (from . (to1 to2 to3...)) elements. From and toN are
strings which are extentions of the files.")
;;;###autoload
(defun taglist-switch-h-cpp ()
"Switch header and body file according to `taglist-header-switches' var.
The current buffer's file name extention is searched in
`taglist-header-switches' variable to find out extention for file's counterpart,
for example *.hpp <--> *.cpp."
(interactive)
(let* ((ext (file-name-extension (buffer-file-name)))
(base-name (taglist-string-without-last (buffer-name) (length ext)))
(base-path (taglist-string-without-last (buffer-file-name) (length ext)))
(count-ext (cdr (find-if (lambda (i) (string= (car i) ext)) taglist-header-switches))))
(cond
(count-ext
(unless
(or
(loop for b in (mapcar (lambda (i) (concat base-name i)) count-ext)
when (bufferp (get-buffer b)) return (switch-to-buffer b))
(loop for c in (mapcar (lambda (count-ext) (concat base-path count-ext)) count-ext)
when (file-exists-p c) return (find-file c)))
(message "There is no corresponding pair (header or body) file.")))
(t
(message "It is not a header or body file! See taglist-header-switches variable.")))))
;; ================================== CPP-H switch end =========================
;; ================================== Tag navigator =========================
(defvar taglist-source-code-buffer nil
"Source code buffer")
(defvar taglist-all-tags nil
"Collection of tags used when searching for current selection.")
(defvar taglist-tmp-file nil
"save current buffer to a temp file. fix ctags can't open a gz
files, example: ido.el.gz")
(defvar taglist-actual-tags nil
"Collection of actual tags used when searching for current selection.")
(defvar taglist-search-string nil
"The current search string during a search.")
;; overlays, use hightlight tags
(defvar taglist-overlays nil
"List of active overlays.")
(defvar taglist-current-language nil
"current programming language.")
(defvar taglist-current-line nil
"current line")
(defvar taglist-current-major-mode nil
"current major mode")
(defface taglist-tag-type
'((((class color))
(:foreground "blue" :height 1.2))
(t (:weight bold)))
"Regexp matching the text identifying the file in `taglist-mode'."
:group 'taglist)
(defvar taglist-tag-type-face 'taglist-tag-type)
(defvar taglist-tag-type-re
(concat "^\\w.*$")
"Regexp matching the text identifying a tag type name.")
(defvar taglist-font-lock-keywords
;; We use `eval' so as to use the buffer-local value of taglist-tag-type-re if
;; applicable.
'((eval . `(,taglist-tag-type-re . taglist-tag-type-face))))
(defconst taglist-font-lock-defaults
'(taglist-font-lock-keywords t nil nil nil))
;; TODO: maintain the list by ctags --list-maps and
;; https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
;; format: (<file name pattern> <detected language>)
(defvar taglist-filename-to-language-alist
'(
("\\.i\\'" . "c")
("\\.lex\\'" . "c")
("\\.[ch]\\'" . "c")
("\\.x[bp]m\\'" . "c")
("\\.xs\\'" . "c")
("\\.h$" . "c++")
("\\.ii\\'" . "c++")
("\\.\\(CC?\\|HH?\\)\\'" . "c++")
("\\.[ch]\\(pp\\|xx\\|\\+\\+\\)\\'" . "c++")
("\\.\\(cc\\|hh\\)\\'" . "c++")
("\\.y\\(acc\\)?\\'" . "yacc")
("\\.vim\\(rc\\)?$" . "vim")
("\\.vim\\(rc\\|peratorrc\\)?$" . "vim")
("\\.exrc\\'" . "vim")
("[._]?g?vimrc\\'" . "vim")
("\\.vim\\'" . "vim")
("\\.go\\'" . "go")
("\\.l\\'" . "lisp")
("\\.li?sp\\'" . "lisp")
("\\.ml\\'" . "lisp")
("\\.asd\\'" . "lisp")
("\\.el\\'" . "lisp")
("Project\\.ede\\'" . "lisp")
("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . "lisp")
("\\`\\..*emacs\\'" . "lisp")
("[:/]_emacs\\'" . "lisp")
("\\.[tT]e[xX]\\'" . "tex")
("\\.ins\\'" . "tex")
("\\.sty\\'" . "tex")
("\\.cl[so]\\'" . "tex")
("\\.bbl\\'" . "tex")
("\\.ltx\\'" . "tex")
("\\.html?\\'" . "html")
("\\.djhtml\\'" . "html")
("\\.phtml\\'" . "html")
("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . "html")
("\\.as[cp]x\\'" . "asp")
("\\.asp\\'" . "asp")
("\\.php\\'" . "php")
("/crontab\\.X*[0-9]+\\'" . "sh")
("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . "sh")
("\\.bash\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . "sh")
("\\.m?spec\\'" . "sh")
("\\(?:\\.rb\\|ru\\|rake\\|thor\\|jbuilder\\|gemspec\\|podspec\\|/\\(?:Gem\\|Rake\\|Cap\\|Thor\\|Vagrant\\|Guard\\|Pod\\)file\\)\\'" . "ruby")
("\\.py\\'" . "python")
("\\.awk\\'" . "awk")
("\\.java\\'" . "java")
("\\.m\\'" . "objc")
("\\.\\(bat\\|cmd\\)\\'" . "dosbatch")
("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . "scheme")
("\\.scm\\.[0-9]*\\'" . "scheme")
("\\.oak\\'" . "scheme")
("\\.[fF]\\'" . "fortran")
("\\.for\\'" . "fortran")
("\\.f9[05]\\'" . "fortran")
("\\.f0[38]\\'" . "fortran")
("\\.p\\'" . "pascal")
("\\.pas\\'" . "pascal")
("\\.ad[abs]\\'" . "ada")
("\\.ad[bs].dg\\'" . "ada")
("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . "perl")
("\\.mk\\'" . "make")
("\\.make\\'" . "make")
("[Mm]akefile\\'" . "make")
("\\.[sS]\\'" . "asm")
("\\.asm\\'" . "asm")
("/\\.[a-z0-9-]*gdbinit" . "gdb-script")
("-gdb\\.gdb" . "gdb-script")
("\\.sql\\'" . "sql")
("\\.m[4c]\\'" . "m4")
("\\.i?tcl\\'" . "tcl")
("\\.exp\\'" . "tcl")
("\\.itk\\'" . "tcl")
("\\.svgz?\\'" . "xml")
("\\.x[ms]l\\'" . "xml")
("\\.dbk\\'" . "xml")
("\\.js\\'" . "javascript")
("\\.json\\'" . "javascript")
("\\.[ds]?vh?\\'" . "verilog")
("\\.vhdl?\\'" . "vhdl")
("\\.re?st\\'" . "reStructuredText")
)
)
;; major mode name map to language
;; (add-to-list 'taglist-major-to-language-alist '("<lang>-mode" "<lang>"))
;; format: (<major mode> <detected language>)
(defvar taglist-major-to-language-alist
`(
("emacs-lisp-mode" "lisp")
("lisp-mode" "lisp")
("c-mode" "c")
("c++-mode" "c++")
;; rust is support at https://github.com/universal-ctags
("rst-mode" "rst")
;; https://github.com/dominikh/go-mode.el.git
("go-mode" "go")
("java-mode" "java")
("python-mode" "python")
("ruby-mode" "ruby")
("js-mode" "javascript")
("objc-mode" "objectivec")
("asm-mode" "asm")
("sh-mode" "sh")
("shell-script-mode" "sh")
("sql-mode" "sql")
("tcl-mode" "tcl")
("fortran-mode" "fortran")
("f90-mode" "fortran")
("scheme-mode" "scheme")
("pascal-mode" "pascal")
("perl-mode" "perl")
("verilog-mode" "verilog")
("vhdl-mode" "vhdl")
("awk-mode" "awk")
("html-mode" "html")
("latex-mode" "tex")
("makefile-gmake-mode" "make")
;; https://github.com/mcandre/vimrc-mode.git
("vimrc-mode" "vim")
("bat-mode" "dosbatch")
("rst-mode" "reStructuredText")
))
;; TODO: maintain the list by ctags --list-kinds
;; format: (<detected language> <ctags language>;<short-kind:full-kind>....)
(defvar taglist-language-to-ctags-alist
`(
;; Ant language
("ant" "Ant;p:projects;t:targets")
;; assembly language
("asm" "Asm;d:define;l:label;m:macro;t:type")
;; aspperl language
("aspperl" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; aspvbs language
("aspvbs" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; awk language
("awk" "Awk;f:function")
;; basic language
("basic" "Basic;c:constant;l:label;g:enum;v:variable;t:type;f:function")
;; beta language
("beta" "BETA;f:fragment;s:slot;v:pattern")
;; c language
("c" "C;c:classes;d:macro definitions;g:enumeration names;\
n:namespaces;s:structure names;t:typedefs;\
u:union names;v:variable definitions;f:function definitions")
;; c++ language
("c++" "C++;n:namespace;v:variable;d:macro;t:typedef;\
c:class;g:enum;s:struct;u:union;f:function")
;; c# language
("cs" "C#;d:macro;t:typedef;n:namespace;c:class;E:event;\
g:enum;s:struct;i:interface;p:properties;m:method")
;; cobol language
("cobol" "Cobol;d:data;f:file;g:group;p:paragraph;\
P:program;s:section")
;; D programming language
("d" "C++;n:namespace;v:variable;t:typedef;c:class;\
g:enum;s:struct;u:union;f:function")
;; Dosbatch
("dosbatch" "DosBatch;l:labels;v:variables")
;; eiffel language
("eiffel" "Eiffel;c:class;f:feature")
;; erlang language
("erlang" "Erlang;d:macro;r:record;m:module;f:function")
;; expect (same as tcl) language
("expect" "Tcl;c:class;f:method;p:procedure")
;; flex
("flex" "Flex;v:global;c:classes;p:properties;m:methods;f:functions;x:mxtags")
;; fortran language
("Fortran" "fortran;p:program;b:block data;c:common;e:entry;\
i:interface;k:type;l:label;m:module;n:namelist;t:derived;v:variable;\
f:function;s:subroutine")
;; GO language
("go" "Go;p:packages;c:constants;t:types;v:variables;s:structs;i:interfaces;m:struct members;f:functions")
("objectivec" "ObjectiveC;i:class interface;I:class implementation;P:Protocol;m:Object's method;\
c:Class' method;v:Global variable;F:Object field;f:A function;p:A property;t:A type alias;\
s:A type structure;e:An enumeration;MA preprocessor macro")
;; HTML language
("html" "HTML;a:anchor;f:function")
;; java language
("java" "Java;p:package;c:class;i:interface;g:enum;f:field;m:method")
;; javascript language
("javascript" "JavaScript;c:class;m:method;v:global;f:function;p:properties;C:constants")
;; lisp language
("lisp" "Lisp;v:variable;f:function;c:custom")
;; lua language
("lua" "Lua;f:function")
;; makefiles
("make" "Make;m:macro;t:targets")
;; Matlab
("matlab" "MatLab;f:function")
;; Ocamal
("ocamal" "OCaml;M:module;v:global;t:type;c:class;\
f:function;m:method;C:constructor;e:exception")
;; pascal language
("pascal" "Pascal;f:function;p:procedure")
;; perl language
("perl" "Perl;f:formats;c:constant;l:label;p:package;s:subroutine")
;; Perl6
("perl6" "Perl6;c:classes;g:grammars;m:methods;o:modules;p:packages;r:roles;u:rules;b:submethods;s:subroutines:t:tokens")
;; php language
("php" "PHP;c:classes;d:constant definitions;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
;; python language
("python" "Python;i:imports;c:classes;m:class members;v:variables;f:functions;")
;; cython language
("pyrex" "Python;c:classe;m:memder;f:function")
;; rexx language
("rexx" "REXX;s:subroutine")
;; ruby language
("ruby" "Ruby;c:class;f:method;F:function;m:singleton method")
;; scheme language
("Scheme" "scheme;s:set;f:function")
;; shell language
("sh" "Sh;f:function")
;; C shell language
("csh" "Sh;f:function")
;; Z shell language
("zsh" "Sh;f:function")
;; slang language
("slang" "SLang;n:namespace;f:function")
;; sml language
("sml" "SML;e:exception;c:functor;s:signature;r:structure;\
t:type;v:value;c:functor;f:function")
;; sql language
("sql" "SQL;f:functions;P:packages;p:procedures;t:tables;T:triggers;\
v:variables;e:events;U:publications;R:services;D:domains;x:MLTableScripts;\
y:MLConnScripts;z:MLProperties;i:indexes;c:cursors;V:views;d:prototypes;\
l:local variables;F:record fields;L:block label;r:records;s:subtypes")
;; tcl language
("tcl" "Tcl;c:class;f:method;m:method;p:procedure")
;; Tex
("tex" "Tex;c:chapters;s:sections;u:subsections;b:subsubsections;\
p:parts;P:paragraphs;G:subparagraphs")
;; vera language
("vera" "Vera;c:class;d:macro;e:enumerator;f:function;g:enum;m:member;\
p:program;P:prototype;t:task;T:typedef;v:variable;x:externvar")
;; verilog language
("verilog" "Verilog;c:constants;e:events;m:modules;n:net data types;p:ports;r:register data types;t:tasks;b:blocks;f:functions")
;; VHDL
("vhdl" "VHDL;c:constant;t:type;T:subtype;r:record;e:entity;\
f:function;p:procedure;P:package")
;; vim language
("vim" "Vim;v:variable;a:autocmds;c:commands;m:map;n:vimball filename;f:function")
;; yacc language
("yacc" "YACC;l:label")
("zephir" "Zephir;c:classes;d:constant;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
("windres" "WindRes;d:dialogs;m:menus;i:icons;b:bitmaps;c:cursors;f:fonts;v:versions;a:accelerators")
("systemverilog" "SystemVerilog;c:constants;e:events;m:modules;n:net data types;p:ports;\
r:register data types;t:tasks;b:blocks;A:assertions;C:classes;V:covergroups;I:interfaces;M:modports;\
K:packages;P:programs;R:properties;T:type declarations;f:functions" )
("rust" "Rust;n:module;s:structural type;i:trait interface;c:implementation;g:Enum;t:Type Alias;\
v:Global variable;M:Macro Definition;m:A struct field;e:An enum variant;F:A method;f:Function")
("reStructuredText" "reStructuredText;c:chapters;s:sections;S:subsections;t:subsubsections")
("r" "R;l:libraries;s:sources;g:global variables;v:function variables;f:functions")
("json" "JSON;o:objects;a:arrays;n:numbers;s:strings;b:booleans;z:nulls")
;; ("gdb-script" "gdbinit;d:definition;t:toplevelVariable") ;; disabled
;; ("m4" "m4;d:definition;u:undefinition;") ;; disabled
))
(defun taglist-goto-line (N)
"goto specified line <N>"
(goto-char (point-min))
(forward-line (1- N)))
(defun taglist-detect-language-by-major-mode ()
"detect language by modeline"
(let ((language nil)
(i 0))
(while (and
(not language)
(< i (length taglist-major-to-language-alist)))
(if (string= taglist-current-major-mode (car (elt taglist-major-to-language-alist i)))
(setq language (nth 1 (elt taglist-major-to-language-alist i))))
(setq i (1+ i)))
;; (message "detect language by major mode = %s" language)
language))
;; TODO, for vim
(defun taglist-detect-language-by-modeline ()
"detect language by modeline"
(let ((language nil))
;; (setq language nil)
language))
;; TODO
(defun taglist-detect-language-by-shebang ()
"detect language by shebang"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language-by-filename ()
"detect language by filename"
(let ((detected-language nil)
(language nil)
(filename (buffer-file-name taglist-source-code-buffer)))
;; Next compare the filename against the entries in taglist-filename-to-language-alist.
(if filename
(let ((name filename)
(remote-id (file-remote-p filename)))
;; Remove backup-suffixes from file name.
(setq name (file-name-sans-versions name))
;; Remove remote file name identification.
(when (and (stringp remote-id)
(string-match (regexp-quote remote-id) name))
(setq name (substring name (match-end 0))))
(while name
;; Find first matching alist entry.
(setq language
(if (memq system-type '(windows-nt cygwin))
;; System is case-insensitive.
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; System is case-sensitive.
(or
;; First match case-sensitively.
(let ((case-fold-search nil))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; Fallback to case-insensitive match.
(and auto-mode-case-fold
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))))))
(if (and language
(consp language)
(cadr language))
(setq language (car language)
name (substring name 0 (match-beginning 0)))
(setq name nil))
(when language
(setq detected-language language))
)
)
)
detected-language))
;; TODO
(defun taglist-detect-language-by-heuristics ()
"detect language by heuristics"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language ()
"return programming language of the file"
(let ((language (taglist-detect-language-by-major-mode)))
;;(let ((language nil)) ;; for test
(if (not language)
(setq language (taglist-detect-language-by-modeline)))
(if (not language)
(setq language (taglist-detect-language-by-shebang)))
(if (not language)
(setq language (taglist-detect-language-by-filename)))
(if (not language)
(setq language (taglist-detect-language-by-heuristics)))
;; (message "last language = %s" language)
language))
(defun taglist-get-ctags-language-config (detected-language)
"get ctags language config"
(let ((language-config nil)
(i 0))
(while (and
(not language-config)
(< i (length taglist-language-to-ctags-alist)))
(if (string= detected-language (car (elt taglist-language-to-ctags-alist i)))
(progn
(setq language-config (nth 1 (elt taglist-language-to-ctags-alist i)))))
(setq i (1+ i)))
(if (not language-config)
(error "Unsupported language: %s" detected-language))
language-config))
(defun taglist-get-ctags-language-name (detected-language)
"get ctags-language by detected-language e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"C\""
(let ((ctags-language-config (taglist-get-ctags-language-config detected-language))
(ctags-language nil))
(setq ctags-language (car (split-string ctags-language-config ";" t)))
ctags-language))
(defsubst taglist-filter-unsupport-kinds (ctags-language expect-ctags-kinds)
"Return the supported kinds of current version `ctags'."
(let ((all-kinds nil)
(ctags-config nil)
(actual-ctags-kinds expect-ctags-kinds)
)
(setq all-kinds
(mapcar (lambda (line) (substring line 0 1) )
(split-string
(apply
#'taglist-ctags-process-string
"ctags" (append
(list (concat "--list-kinds=" ctags-language)))) "\n" t)))
(let ((found nil)
(element nil)
(i 0))
(dolist (kind expect-ctags-kinds)
(setq found nil)
(setq i 0)
(while (and (not found)
(< i (length all-kinds)))
(setq element (elt all-kinds i))
(if (string= (substring kind 0 1) element)
(setq found t))
(setq i (1+ i)))
(if (not found)
(progn
(setq actual-ctags-kinds (remove kind actual-ctags-kinds))))))
actual-ctags-kinds))
(defun taglist-get-ctags-language-full-kinds (detected-language)
"Get full ctags language kinds by detected-language. e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return a list (\"d:macro\" \"g:enum\" \"s:struct\" \"u:union\"
\"t:typedef\" \"v:variable\" \"f:function\")"
(let* ((ctags-language-config-string (taglist-get-ctags-language-config detected-language))
(ctags-language-config (split-string ctags-language-config-string ";" t))
(ctags-language-kinds nil))
(setq ctags-language-kinds (taglist-filter-unsupport-kinds
(car ctags-language-config)
(cdr ctags-language-config)))
ctags-language-kinds))
(defun taglist-get-ctags-language-short-kinds (detected-language)
"get kinds by detected-language.
e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"dgsutvf\""
(let ((kinds ""))
(dolist (element (taglist-get-ctags-language-full-kinds detected-language))
(setq kinds (concat kinds (substring element 0 1))))
kinds))
(defun taglist-get-tag-lines ()
"Return all tags of current buffer;"
(let* ((detected-language (taglist-detect-language))
(ctags-language (taglist-get-ctags-language-name detected-language))
(ctags-lang-kinds (taglist-get-ctags-language-short-kinds detected-language))
(file (buffer-file-name taglist-source-code-buffer)))
(setq taglist-current-language detected-language)
(if file
(split-string
(apply #'taglist-ctags-process-string
"ctags"
(append (list "-f" "-"
"--format=2"
"--excmd=number"
"--fields=nks"
"--sort=no"
(concat "--language-force=" ctags-language)
(concat "--" ctags-language "-kinds=" ctags-lang-kinds)
taglist-tmp-file
)))
"\n" t)
(insert (concat "Warnning: " (buffer-name taglist-source-code-buffer) " doesn't exist on your disk, you should save it first!\n"))
nil)))
;; e.g. tagline = main /path/to/src/ip46.c 38;" f line:38
(defun taglist-convert-to-elements (tagline)
"Convert tagline to a tag(tag-name tag-line tag-type) "
(let ((elements (split-string tagline "\t" t)))
(list (car elements) (string-to-number (nth 2 elements)) (nth 3 elements))))
(defun taglist-jump-to-tag ()
"Jump to a tag, corresponding the current line in tag buffer.
When called standing on a line of tag list, it closes the list
buffer and sets the point to a tag, corresponding the line."
(interactive)
(let ((tag-record (nth (1- (line-number-at-pos)) taglist-actual-tags)))
(if (and tag-record (= 0 (taglist-line tag-record)))
(setq tag-record (nth (line-number-at-pos) taglist-actual-tags)))
(if (and tag-record (taglist-line tag-record))
(progn
(kill-buffer (current-buffer))
(switch-to-buffer taglist-source-code-buffer t)
(taglist-goto-line (taglist-line tag-record))
(recenter))
(message "The line does not contain tag description!"))))
(defun taglist-matches-all (string substrings)
"Return non-nil if STRING contain each of SUBSTRINGS as a substring."
(reduce (lambda (prev part) (and prev (string-match part string))) substrings :initial-value t))
(defstruct taglist
(tag) ;; tag name, e.g. main
(line) ;; line number of tag, e.g. 11
(type) ;; type of the tag: e.g. f
)
(defun taglist-gen-display-struct (types taglines)
"Return a list of three strings, representing type, parent and name of tag F."
;; (message "types = %s, taglines = %s" types taglines)
(let ((tags-struct nil))
;; loop for each tag type
(dolist (tag-type types)
(let* ((element (split-string tag-type ":" t))
(type-abbr (car element))
(type-name (nth 1 element))
(type-occur nil)
)
;; (message "%s %s" type-abbr type-name)
;; loop for all taglines
(dolist (tagline taglines)
;; tagline (main 38 f)
;; when current tag type matched
(when (string= type-abbr (nth 2 tagline))
(if type-occur ;; when current tag is not first time appear.
;; (message "%s" tagline)
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; if current tag is first time appear, then display type name and current tag.
(setq tags-struct (append tags-struct (list (make-taglist :tag type-name :line 0 :type ""))))
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; (message "%s" type-name)
;; (message "%s" tagline)
(setq type-occur t))))))
;; (message "tags-struct = %s" tags-struct)
;; return tags-struct
tags-struct)
)
(defun taglist-search-string-updated ()
"Update tag list according to search string."
(message taglist-search-string)
;; let s:tlist_def_c_settings = 'c;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function'
;; (setq types (list "d:Macro" "g:Enum" "s:Struct" "u:Union" "t:Typedef" "v:Variable" "f:Function"))
(let ((types (taglist-get-ctags-language-full-kinds taglist-current-language))
(taglist-actual-tags-tmp
;; remove-if-not: Remove all items not satisfying search string.
(remove-if-not
(lambda (element)
(taglist-matches-all (car element) (split-string taglist-search-string)))
taglist-all-tags)))
;; ("DEBUG" 11 "d") ("main" 18 "f")
(setq taglist-actual-tags (taglist-gen-display-struct types taglist-actual-tags-tmp)))
;; (message "taglist-actual-tags = %S" taglist-actual-tags)
(erase-buffer)
(dolist (i taglist-overlays)
;; Delete the overlay from its buffer.
(delete-overlay i))
(setq taglist-overlays nil)
;; [cl-struct-taglist "main" 38 "f"]
(dolist (tag-record taglist-actual-tags)
(insert (concat (taglist-tag tag-record) "\n")))
(let ((offset 0)
(pos 0)
(line-pos nil)
(tag-record nil)
(output (buffer-string))
(search-strings (split-string taglist-search-string)))
(dolist (search-string search-strings)
(while (string-match search-string output offset)
(progn
(setq pos (match-beginning 0))
(setq offset (match-end 0))
;; match: start form 0, overlay: start from 1;
(setq tag-record (nth (1- (line-number-at-pos pos)) taglist-actual-tags))
(if (not (= 0 (taglist-line tag-record)))
(progn
(push (make-overlay (+ 1 pos) (+ 1 offset)) taglist-overlays)
(overlay-put (car taglist-overlays) 'face '(background-color . "yellow"))
(if (not line-pos)
(setq line-pos (line-number-at-pos pos)))
)))))
(if line-pos
(taglist-goto-line line-pos)
(taglist-goto-line (+ 1 (/ (count-lines (point-min) (point-max)) 2)))))
)
(defun taglist-key-pressed (key)
"Called when KEY is pressed."
(setq taglist-search-string (concat taglist-search-string (char-to-string key)))
(taglist-search-string-updated))
(defun taglist-backspace-pressed ()
"Called when Backspace is pressed."
(interactive)
(setq taglist-search-string (taglist-string-without-last taglist-search-string 1))
(taglist-search-string-updated))
(defun taglist-make-key-function (key)
"Return a function for KEY."
`(lambda () (interactive) (taglist-key-pressed ,key)))
(defun taglist-key-itself (map key)
"Maps in the MAP KEY to its function."
(define-key map (char-to-string key) (taglist-make-key-function key)))
(defun taglist-escape ()
"Kill tag list buffer."
(interactive)
(kill-buffer (current-buffer))
(delete-file taglist-tmp-file)
(switch-to-buffer taglist-source-code-buffer))
(defvar taglist-mode-map
(let ((map (make-sparse-keymap)))
(suppress-keymap map)
(do ((k (string-to-char "a") (+ 1 k))) ((> k (string-to-char "z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "A") (+ 1 k))) ((> k (string-to-char "Z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "0") (+ 1 k))) ((> k (string-to-char "9")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(dolist (k (string-to-list "=><&!"))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(taglist-key-itself map (string-to-char " "))
(taglist-key-itself map (string-to-char "_"))
(define-key map (kbd "<RET>") 'taglist-jump-to-tag)
(define-key map (kbd "<backspace>") 'taglist-backspace-pressed)
;; Cause M-v doesn't work!!!
;; (define-key map (kbd "<ESC>") 'taglist-escape)
(define-key map (kbd "C-q") 'taglist-escape)
(define-key map (kbd "M-q") 'taglist-escape)
(define-key map "\C-v" 'scroll-up)
(define-key map "\M-v" 'scroll-down)
map)
"Keymap for `taglist-mode'.")
(defcustom ctags-executable-directory nil
"If non-nil the directory to search global executables."
:type '(choice (const :tag "Unset" nil) directory)
:risky t
:group 'ctags)
(defun taglist-ctags-program-path (name)
(if ctags-executable-directory
;; (expand-file-name NAME &optional DEFAULT-DIRECTORY)
;; Convert filename NAME to absolute, and canonicalize it.
(expand-file-name name ctags-executable-directory)
name))
(defun taglist-ctags-process-string (program &rest args)
(with-temp-buffer
;; (process-file PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS)
;; Process files synchronously in a separate process.
(let ((exit (apply #'process-file
(taglist-ctags-program-path program) nil t nil args))
(output (progn
(goto-char (point-max))
(skip-chars-backward " \t\n")
(buffer-substring (point-min) (point)))))
(or (zerop exit)
(error "`%s' non-zero exit: %s" program output))
output)))
;; /usr/local/bin/ctags --version
;; Universal Ctags Development(ebe7328), Copyright (C) 2015 Universal Ctags Team
;; Universal Ctags is derived from Exuberant Ctags.
;; Exuberant Ctags 5.8, Copyright (C) 1996-2009 <NAME>
;; Compiled: Nov 9 2015, 15:37:41
;; URL: https://ctags.io/
;; Optional compiled features: +wildcards, +regex, +debug, +option-directory, +coproc
;; ctags-exuberant --version
;; ctags-exuberant: Warning: Ignoring non-option in ./.ctags
;; Exuberant Ctags 5.9~svn20110310, Copyright (C) 1996-2009 <NAME>
;; Addresses: <<EMAIL>>, http://ctags.sourceforge.net
;; Optional compiled features: +wildcards, +regex
;; ctags.emacs24 --version
;; ctags (GNU Emacs 24.5)
;; Copyright (C) 2015 Free Software Foundation, Inc.
;; This program is distributed under the terms in ETAGS.README
(defsubst taglist-ctags-variant ()
"Return the variant of `ctags'."
(let ((buffer-string nil)
(ctags-variant nil ))
(setq buffer-string (apply #'taglist-ctags-process-string
"ctags" (append (list "--version"))))
(if (string-match "Emacs" buffer-string 0)
(setq ctags-variant "emacs-ctags")
(if (string-match "Universal" buffer-string 0)
(setq ctags-variant "universal-ctags")
(if (string-match "Exuberant" buffer-string 0)
(setq ctags-variant "exuberant-ctags"))))
ctags-variant))
(defun taglist-highlight-current-tag ()
"Highlight current tag line"
;; taglist-all-tags =
;; (("INET_ADDRSTRLEN" 17 "d")
;; ("INET6_ADDRSTRLEN" 18 "d")
;; ("ZERO" 19 "d")
;; ("BUF_SIZE" 20 "d")
;; ("global_var" 22 "v")
;; ("IP4_2_6" 24 "f")
;; ("IP6_2_4" 31 "f")
;; ("main" 38 "f"))
;; get current line number; and find range of line nubmer in taglist-all-tags
;; Set current line corresponding to the current function/tag if any
(let ((prev-line 0)
(curr-line 0)
(tag-line 0)
(i 0))
(while (and
(= 0 tag-line)
(< i (length taglist-all-tags)))
(setq curr-line (nth 1 (elt taglist-all-tags i)))
(setq i (1+ i))
;; (message "taglist-current-line = %d, prev-line = %d curr-line = %d, tag-line = %d"
;; taglist-current-line
;; prev-line
;; curr-line
;; tag-line)
(if (= taglist-current-line curr-line)
;; best case
(setq tag-line curr-line)
(if (< taglist-current-line curr-line)
;; if current line in source code buffer less than the line number
;; of current encounter tag in taglist, then choose the line number
;; of previous tags.
(if (= 0 prev-line)
;; if line number of previous tag is zero, then choose the line
;; number of current tag
(setq tag-line curr-line)
(setq tag-line prev-line)
)
;; if current line in source code buffer is big than the line number
;; of current encounter tag in taglist, then continue loop.
))
;; (message "tag-line = %d" tag-line)
(setq prev-line curr-line))
(if (= 0 tag-line)
(setq tag-line prev-line))
;; (message "found tag-line = %d" tag-line)
(let ((line (position-if
(lambda (item) (= tag-line (taglist-line item)))
taglist-actual-tags)))
(when line
(taglist-goto-line (1+ line)))))
(hl-line-mode))
;;;###autoload
(defun taglist-list-tags ()
"Show tag list of current buffer in a newly created buffer.
This function is recommended to be bound to some convinient hotkey."
(interactive)
;; (message "taglist-ctags-variant = %s" (taglist-ctags-variant))
(if (string= (taglist-ctags-variant) "emacs-ctags")
(error "taglist doesn't support emacs ctags, please install universal-ctags or exuberant-ctags!")
)
(setq taglist-source-code-buffer (current-buffer))
(setq taglist-current-line (line-number-at-pos))
(setq taglist-current-major-mode major-mode)
(setq taglist-tmp-file (make-temp-file "taglist."))
(write-region (point-min) (point-max) taglist-tmp-file)
(switch-to-buffer (get-buffer-create (concat (buffer-name (current-buffer)) " tag list")) t)
(taglist-mode))
(defun taglist-mode-init ()
"Initialize tag list mode."
;; current tag search string
(make-local-variable 'taglist-search-string)
;; list of taglist-tag structures
(make-local-variable 'taglist-all-tags)
;; subset of taglist-all-tags that contain taglist-search string in the name string
(make-local-variable 'taglist-actual-tags)
;; overlays used to highligh search string matches in tag names
(make-local-variable 'taglist-overlays)
(make-local-variable 'taglist-current-language)
(set (make-local-variable 'font-lock-defaults) taglist-font-lock-defaults)
;; (message "current-line = %d" taglist-current-line)
(setq taglist-overlays nil)
(setq taglist-search-string "")
(setq taglist-all-tags
(let* ((tag-lines (taglist-get-tag-lines)))
(if tag-lines
(mapcar 'taglist-convert-to-elements tag-lines))))
(if (not taglist-all-tags)
(insert "No taglist, Press <C-q> or <M-q> to exist!!!\n")
(taglist-search-string-updated)
(taglist-highlight-current-tag)))
(define-derived-mode taglist-mode nil "Taglist"
"EmacsAssist tag selection mode.
\\{taglist-mode-map}
Turning on Text mode runs the normal hook `taglist-mode-hook'."
(taglist-mode-init))
;; ================================== Tag navigator end ======================
(provide 'taglist)
;;; taglist.el ends here
;; taglist.el:122:70:Warning: function `find-if' from cl package called at runtime
;; taglist.el:632:96:Warning: function `reduce' from cl package called at runtime
;; taglist.el:698:11:Warning: function `remove-if-not' from cl package called at runtime
;; taglist.el:902:18:Warning: function `position-if' from cl package called at runtime
;; [PATCH] emacs: Suppress warnings about using cl at runtime
;; https://notmuchmail.org/pipermail/notmuch/2012/010297.html
;; Local Variables:
;; byte-compile-warnings: (not cl-functions)
;; End:
| true | ;;; taglist.el --- Taglist provides an overview of the structure of the programming language files.
;; Copyright (C) 2015 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI at gmail.com>
;; This file is *NOT* part of GNU Emacs.
;; 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 of
;; the License, 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., 59 Temple Place, Suite 330, Boston,
;; MA 02111-1307 USA
;; Version: 1.0
;; Compatibility: Emacs 24
;;; Commentary:
;; The "Tag List" plugin is a source code browser plugin for Emacs and provides
;; an overview of the structure of the programming language files and allows you
;; to efficiently browse through source code files for different programming
;; languages.
;; It contains some useful functions features for developers:
;; 1) Tag navigation.
;;
;; When taglist-list-tags called, a new buffer is shown, containing list of
;; different type tags. You can select the tag moving to its line and press
;; ENTER to jump to the tag. You also can type a string in the buffer and tag
;; list will be reduced to those which contain the string as a substring.
;; Nice highlight is implemented.
;; 2) Header <-> Body file switch.
;;
;; You can easily switch between body (c, cpp, cc...) and its corresponding
;; header file (h, hpp...) using taglist-switch-h-cpp. The counterpart file
;; is first searched in opened buffers and if there is no match the file is
;; searched in the same directory. You can adjust body to header
;; correspondence customizing taglist-header-switches variable.
;; Taglist uses ctags as backend (https://ctags.io/ or http://ctags.sourceforge.net/)
;;; Usage:
;; 1) Install ctags(exuberant-ctags) package
;; 2) Add convenient keymaps for fast taglist calls in prog-mode
;;
;; (defun my-c-mode-common-hook ()
;; (define-key c-mode-base-map (kbd "M-o") 'taglist-switch-h-cpp)
;; (define-key c-mode-base-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
;;
;; (defun my-python-mode-hook ()
;; (define-key python-mode-map (kbd "M-m") 'taglist-list-tags))
;; (add-hook 'python-mode-hook 'my-python-mode-hook)
;;
;; (define-key lisp-mode-shared-map (kbd "M-m") 'taglist-list-tags)
;;
;; 3) Open any programming file, press M-m. Try to type any tag name.
;;
;; 4) Open any .cpp file. Press M-o. If there is .h or .hpp file in the
;; same folder, it will be opened.
;;; Changelog:
;; 03 Nov 2015 -- v1.0 Initial version created.
;;; TODO:
;;; Code:
(require 'cl)
;; ================================== My STRING utils ========================
(defun taglist-string-without-last (string n)
"This function truncates from the STRING last N characters."
(substring string 0 (max 0(- (length string) n))))
(defun taglist-string-ends-with (string end)
"Check whether STRING ends with END substring."
(string= end (substring string (- (length end)))))
;; ================================== My STRING utils end ====================
;; ================================== CPP-H switch ===========================
;;;###autoload
(defvar taglist-header-switches '(("h" . ("cpp" "cc" "c"))
("hpp" . ("cpp" "cc"))
("cpp" . ("h" "hpp"))
("c" . ("h"))
("C" . ("H"))
("H" . ("C" "CPP" "CC"))
("cc" . ("h" "hpp")))
"This variable defines possible switches for `taglist-switch-h-cpp' function.
Its format is list of (from . (to1 to2 to3...)) elements. From and toN are
strings which are extentions of the files.")
;;;###autoload
(defun taglist-switch-h-cpp ()
"Switch header and body file according to `taglist-header-switches' var.
The current buffer's file name extention is searched in
`taglist-header-switches' variable to find out extention for file's counterpart,
for example *.hpp <--> *.cpp."
(interactive)
(let* ((ext (file-name-extension (buffer-file-name)))
(base-name (taglist-string-without-last (buffer-name) (length ext)))
(base-path (taglist-string-without-last (buffer-file-name) (length ext)))
(count-ext (cdr (find-if (lambda (i) (string= (car i) ext)) taglist-header-switches))))
(cond
(count-ext
(unless
(or
(loop for b in (mapcar (lambda (i) (concat base-name i)) count-ext)
when (bufferp (get-buffer b)) return (switch-to-buffer b))
(loop for c in (mapcar (lambda (count-ext) (concat base-path count-ext)) count-ext)
when (file-exists-p c) return (find-file c)))
(message "There is no corresponding pair (header or body) file.")))
(t
(message "It is not a header or body file! See taglist-header-switches variable.")))))
;; ================================== CPP-H switch end =========================
;; ================================== Tag navigator =========================
(defvar taglist-source-code-buffer nil
"Source code buffer")
(defvar taglist-all-tags nil
"Collection of tags used when searching for current selection.")
(defvar taglist-tmp-file nil
"save current buffer to a temp file. fix ctags can't open a gz
files, example: ido.el.gz")
(defvar taglist-actual-tags nil
"Collection of actual tags used when searching for current selection.")
(defvar taglist-search-string nil
"The current search string during a search.")
;; overlays, use hightlight tags
(defvar taglist-overlays nil
"List of active overlays.")
(defvar taglist-current-language nil
"current programming language.")
(defvar taglist-current-line nil
"current line")
(defvar taglist-current-major-mode nil
"current major mode")
(defface taglist-tag-type
'((((class color))
(:foreground "blue" :height 1.2))
(t (:weight bold)))
"Regexp matching the text identifying the file in `taglist-mode'."
:group 'taglist)
(defvar taglist-tag-type-face 'taglist-tag-type)
(defvar taglist-tag-type-re
(concat "^\\w.*$")
"Regexp matching the text identifying a tag type name.")
(defvar taglist-font-lock-keywords
;; We use `eval' so as to use the buffer-local value of taglist-tag-type-re if
;; applicable.
'((eval . `(,taglist-tag-type-re . taglist-tag-type-face))))
(defconst taglist-font-lock-defaults
'(taglist-font-lock-keywords t nil nil nil))
;; TODO: maintain the list by ctags --list-maps and
;; https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
;; format: (<file name pattern> <detected language>)
(defvar taglist-filename-to-language-alist
'(
("\\.i\\'" . "c")
("\\.lex\\'" . "c")
("\\.[ch]\\'" . "c")
("\\.x[bp]m\\'" . "c")
("\\.xs\\'" . "c")
("\\.h$" . "c++")
("\\.ii\\'" . "c++")
("\\.\\(CC?\\|HH?\\)\\'" . "c++")
("\\.[ch]\\(pp\\|xx\\|\\+\\+\\)\\'" . "c++")
("\\.\\(cc\\|hh\\)\\'" . "c++")
("\\.y\\(acc\\)?\\'" . "yacc")
("\\.vim\\(rc\\)?$" . "vim")
("\\.vim\\(rc\\|peratorrc\\)?$" . "vim")
("\\.exrc\\'" . "vim")
("[._]?g?vimrc\\'" . "vim")
("\\.vim\\'" . "vim")
("\\.go\\'" . "go")
("\\.l\\'" . "lisp")
("\\.li?sp\\'" . "lisp")
("\\.ml\\'" . "lisp")
("\\.asd\\'" . "lisp")
("\\.el\\'" . "lisp")
("Project\\.ede\\'" . "lisp")
("[]>:/\\]\\..*\\(emacs\\|gnus\\|viper\\)\\'" . "lisp")
("\\`\\..*emacs\\'" . "lisp")
("[:/]_emacs\\'" . "lisp")
("\\.[tT]e[xX]\\'" . "tex")
("\\.ins\\'" . "tex")
("\\.sty\\'" . "tex")
("\\.cl[so]\\'" . "tex")
("\\.bbl\\'" . "tex")
("\\.ltx\\'" . "tex")
("\\.html?\\'" . "html")
("\\.djhtml\\'" . "html")
("\\.phtml\\'" . "html")
("\\.[sx]?html?\\(\\.[a-zA-Z_]+\\)?\\'" . "html")
("\\.as[cp]x\\'" . "asp")
("\\.asp\\'" . "asp")
("\\.php\\'" . "php")
("/crontab\\.X*[0-9]+\\'" . "sh")
("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . "sh")
("\\.bash\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(bash_\\(profile\\|history\\|log\\(in\\|out\\)\\)\\|z?log\\(in\\|out\\)\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\(shrc\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . "sh")
("\\(/\\|\\`\\)\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . "sh")
("\\.m?spec\\'" . "sh")
("\\(?:\\.rb\\|ru\\|rake\\|thor\\|jbuilder\\|gemspec\\|podspec\\|/\\(?:Gem\\|Rake\\|Cap\\|Thor\\|Vagrant\\|Guard\\|Pod\\)file\\)\\'" . "ruby")
("\\.py\\'" . "python")
("\\.awk\\'" . "awk")
("\\.java\\'" . "java")
("\\.m\\'" . "objc")
("\\.\\(bat\\|cmd\\)\\'" . "dosbatch")
("\\.\\(scm\\|stk\\|ss\\|sch\\)\\'" . "scheme")
("\\.scm\\.[0-9]*\\'" . "scheme")
("\\.oak\\'" . "scheme")
("\\.[fF]\\'" . "fortran")
("\\.for\\'" . "fortran")
("\\.f9[05]\\'" . "fortran")
("\\.f0[38]\\'" . "fortran")
("\\.p\\'" . "pascal")
("\\.pas\\'" . "pascal")
("\\.ad[abs]\\'" . "ada")
("\\.ad[bs].dg\\'" . "ada")
("\\.\\([pP]\\([Llm]\\|erl\\|od\\)\\|al\\)\\'" . "perl")
("\\.mk\\'" . "make")
("\\.make\\'" . "make")
("[Mm]akefile\\'" . "make")
("\\.[sS]\\'" . "asm")
("\\.asm\\'" . "asm")
("/\\.[a-z0-9-]*gdbinit" . "gdb-script")
("-gdb\\.gdb" . "gdb-script")
("\\.sql\\'" . "sql")
("\\.m[4c]\\'" . "m4")
("\\.i?tcl\\'" . "tcl")
("\\.exp\\'" . "tcl")
("\\.itk\\'" . "tcl")
("\\.svgz?\\'" . "xml")
("\\.x[ms]l\\'" . "xml")
("\\.dbk\\'" . "xml")
("\\.js\\'" . "javascript")
("\\.json\\'" . "javascript")
("\\.[ds]?vh?\\'" . "verilog")
("\\.vhdl?\\'" . "vhdl")
("\\.re?st\\'" . "reStructuredText")
)
)
;; major mode name map to language
;; (add-to-list 'taglist-major-to-language-alist '("<lang>-mode" "<lang>"))
;; format: (<major mode> <detected language>)
(defvar taglist-major-to-language-alist
`(
("emacs-lisp-mode" "lisp")
("lisp-mode" "lisp")
("c-mode" "c")
("c++-mode" "c++")
;; rust is support at https://github.com/universal-ctags
("rst-mode" "rst")
;; https://github.com/dominikh/go-mode.el.git
("go-mode" "go")
("java-mode" "java")
("python-mode" "python")
("ruby-mode" "ruby")
("js-mode" "javascript")
("objc-mode" "objectivec")
("asm-mode" "asm")
("sh-mode" "sh")
("shell-script-mode" "sh")
("sql-mode" "sql")
("tcl-mode" "tcl")
("fortran-mode" "fortran")
("f90-mode" "fortran")
("scheme-mode" "scheme")
("pascal-mode" "pascal")
("perl-mode" "perl")
("verilog-mode" "verilog")
("vhdl-mode" "vhdl")
("awk-mode" "awk")
("html-mode" "html")
("latex-mode" "tex")
("makefile-gmake-mode" "make")
;; https://github.com/mcandre/vimrc-mode.git
("vimrc-mode" "vim")
("bat-mode" "dosbatch")
("rst-mode" "reStructuredText")
))
;; TODO: maintain the list by ctags --list-kinds
;; format: (<detected language> <ctags language>;<short-kind:full-kind>....)
(defvar taglist-language-to-ctags-alist
`(
;; Ant language
("ant" "Ant;p:projects;t:targets")
;; assembly language
("asm" "Asm;d:define;l:label;m:macro;t:type")
;; aspperl language
("aspperl" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; aspvbs language
("aspvbs" "Asp;c:constants;v:variable;f:function;s:subroutine")
;; awk language
("awk" "Awk;f:function")
;; basic language
("basic" "Basic;c:constant;l:label;g:enum;v:variable;t:type;f:function")
;; beta language
("beta" "BETA;f:fragment;s:slot;v:pattern")
;; c language
("c" "C;c:classes;d:macro definitions;g:enumeration names;\
n:namespaces;s:structure names;t:typedefs;\
u:union names;v:variable definitions;f:function definitions")
;; c++ language
("c++" "C++;n:namespace;v:variable;d:macro;t:typedef;\
c:class;g:enum;s:struct;u:union;f:function")
;; c# language
("cs" "C#;d:macro;t:typedef;n:namespace;c:class;E:event;\
g:enum;s:struct;i:interface;p:properties;m:method")
;; cobol language
("cobol" "Cobol;d:data;f:file;g:group;p:paragraph;\
P:program;s:section")
;; D programming language
("d" "C++;n:namespace;v:variable;t:typedef;c:class;\
g:enum;s:struct;u:union;f:function")
;; Dosbatch
("dosbatch" "DosBatch;l:labels;v:variables")
;; eiffel language
("eiffel" "Eiffel;c:class;f:feature")
;; erlang language
("erlang" "Erlang;d:macro;r:record;m:module;f:function")
;; expect (same as tcl) language
("expect" "Tcl;c:class;f:method;p:procedure")
;; flex
("flex" "Flex;v:global;c:classes;p:properties;m:methods;f:functions;x:mxtags")
;; fortran language
("Fortran" "fortran;p:program;b:block data;c:common;e:entry;\
i:interface;k:type;l:label;m:module;n:namelist;t:derived;v:variable;\
f:function;s:subroutine")
;; GO language
("go" "Go;p:packages;c:constants;t:types;v:variables;s:structs;i:interfaces;m:struct members;f:functions")
("objectivec" "ObjectiveC;i:class interface;I:class implementation;P:Protocol;m:Object's method;\
c:Class' method;v:Global variable;F:Object field;f:A function;p:A property;t:A type alias;\
s:A type structure;e:An enumeration;MA preprocessor macro")
;; HTML language
("html" "HTML;a:anchor;f:function")
;; java language
("java" "Java;p:package;c:class;i:interface;g:enum;f:field;m:method")
;; javascript language
("javascript" "JavaScript;c:class;m:method;v:global;f:function;p:properties;C:constants")
;; lisp language
("lisp" "Lisp;v:variable;f:function;c:custom")
;; lua language
("lua" "Lua;f:function")
;; makefiles
("make" "Make;m:macro;t:targets")
;; Matlab
("matlab" "MatLab;f:function")
;; Ocamal
("ocamal" "OCaml;M:module;v:global;t:type;c:class;\
f:function;m:method;C:constructor;e:exception")
;; pascal language
("pascal" "Pascal;f:function;p:procedure")
;; perl language
("perl" "Perl;f:formats;c:constant;l:label;p:package;s:subroutine")
;; Perl6
("perl6" "Perl6;c:classes;g:grammars;m:methods;o:modules;p:packages;r:roles;u:rules;b:submethods;s:subroutines:t:tokens")
;; php language
("php" "PHP;c:classes;d:constant definitions;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
;; python language
("python" "Python;i:imports;c:classes;m:class members;v:variables;f:functions;")
;; cython language
("pyrex" "Python;c:classe;m:memder;f:function")
;; rexx language
("rexx" "REXX;s:subroutine")
;; ruby language
("ruby" "Ruby;c:class;f:method;F:function;m:singleton method")
;; scheme language
("Scheme" "scheme;s:set;f:function")
;; shell language
("sh" "Sh;f:function")
;; C shell language
("csh" "Sh;f:function")
;; Z shell language
("zsh" "Sh;f:function")
;; slang language
("slang" "SLang;n:namespace;f:function")
;; sml language
("sml" "SML;e:exception;c:functor;s:signature;r:structure;\
t:type;v:value;c:functor;f:function")
;; sql language
("sql" "SQL;f:functions;P:packages;p:procedures;t:tables;T:triggers;\
v:variables;e:events;U:publications;R:services;D:domains;x:MLTableScripts;\
y:MLConnScripts;z:MLProperties;i:indexes;c:cursors;V:views;d:prototypes;\
l:local variables;F:record fields;L:block label;r:records;s:subtypes")
;; tcl language
("tcl" "Tcl;c:class;f:method;m:method;p:procedure")
;; Tex
("tex" "Tex;c:chapters;s:sections;u:subsections;b:subsubsections;\
p:parts;P:paragraphs;G:subparagraphs")
;; vera language
("vera" "Vera;c:class;d:macro;e:enumerator;f:function;g:enum;m:member;\
p:program;P:prototype;t:task;T:typedef;v:variable;x:externvar")
;; verilog language
("verilog" "Verilog;c:constants;e:events;m:modules;n:net data types;p:ports;r:register data types;t:tasks;b:blocks;f:functions")
;; VHDL
("vhdl" "VHDL;c:constant;t:type;T:subtype;r:record;e:entity;\
f:function;p:procedure;P:package")
;; vim language
("vim" "Vim;v:variable;a:autocmds;c:commands;m:map;n:vimball filename;f:function")
;; yacc language
("yacc" "YACC;l:label")
("zephir" "Zephir;c:classes;d:constant;i:interfaces;n:namespaces;t:traits;v:variables;f:functions")
("windres" "WindRes;d:dialogs;m:menus;i:icons;b:bitmaps;c:cursors;f:fonts;v:versions;a:accelerators")
("systemverilog" "SystemVerilog;c:constants;e:events;m:modules;n:net data types;p:ports;\
r:register data types;t:tasks;b:blocks;A:assertions;C:classes;V:covergroups;I:interfaces;M:modports;\
K:packages;P:programs;R:properties;T:type declarations;f:functions" )
("rust" "Rust;n:module;s:structural type;i:trait interface;c:implementation;g:Enum;t:Type Alias;\
v:Global variable;M:Macro Definition;m:A struct field;e:An enum variant;F:A method;f:Function")
("reStructuredText" "reStructuredText;c:chapters;s:sections;S:subsections;t:subsubsections")
("r" "R;l:libraries;s:sources;g:global variables;v:function variables;f:functions")
("json" "JSON;o:objects;a:arrays;n:numbers;s:strings;b:booleans;z:nulls")
;; ("gdb-script" "gdbinit;d:definition;t:toplevelVariable") ;; disabled
;; ("m4" "m4;d:definition;u:undefinition;") ;; disabled
))
(defun taglist-goto-line (N)
"goto specified line <N>"
(goto-char (point-min))
(forward-line (1- N)))
(defun taglist-detect-language-by-major-mode ()
"detect language by modeline"
(let ((language nil)
(i 0))
(while (and
(not language)
(< i (length taglist-major-to-language-alist)))
(if (string= taglist-current-major-mode (car (elt taglist-major-to-language-alist i)))
(setq language (nth 1 (elt taglist-major-to-language-alist i))))
(setq i (1+ i)))
;; (message "detect language by major mode = %s" language)
language))
;; TODO, for vim
(defun taglist-detect-language-by-modeline ()
"detect language by modeline"
(let ((language nil))
;; (setq language nil)
language))
;; TODO
(defun taglist-detect-language-by-shebang ()
"detect language by shebang"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language-by-filename ()
"detect language by filename"
(let ((detected-language nil)
(language nil)
(filename (buffer-file-name taglist-source-code-buffer)))
;; Next compare the filename against the entries in taglist-filename-to-language-alist.
(if filename
(let ((name filename)
(remote-id (file-remote-p filename)))
;; Remove backup-suffixes from file name.
(setq name (file-name-sans-versions name))
;; Remove remote file name identification.
(when (and (stringp remote-id)
(string-match (regexp-quote remote-id) name))
(setq name (substring name (match-end 0))))
(while name
;; Find first matching alist entry.
(setq language
(if (memq system-type '(windows-nt cygwin))
;; System is case-insensitive.
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; System is case-sensitive.
(or
;; First match case-sensitively.
(let ((case-fold-search nil))
(assoc-default name taglist-filename-to-language-alist
'string-match))
;; Fallback to case-insensitive match.
(and auto-mode-case-fold
(let ((case-fold-search t))
(assoc-default name taglist-filename-to-language-alist
'string-match))))))
(if (and language
(consp language)
(cadr language))
(setq language (car language)
name (substring name 0 (match-beginning 0)))
(setq name nil))
(when language
(setq detected-language language))
)
)
)
detected-language))
;; TODO
(defun taglist-detect-language-by-heuristics ()
"detect language by heuristics"
(let ((language nil))
;; (setq language nil)
language))
(defun taglist-detect-language ()
"return programming language of the file"
(let ((language (taglist-detect-language-by-major-mode)))
;;(let ((language nil)) ;; for test
(if (not language)
(setq language (taglist-detect-language-by-modeline)))
(if (not language)
(setq language (taglist-detect-language-by-shebang)))
(if (not language)
(setq language (taglist-detect-language-by-filename)))
(if (not language)
(setq language (taglist-detect-language-by-heuristics)))
;; (message "last language = %s" language)
language))
(defun taglist-get-ctags-language-config (detected-language)
"get ctags language config"
(let ((language-config nil)
(i 0))
(while (and
(not language-config)
(< i (length taglist-language-to-ctags-alist)))
(if (string= detected-language (car (elt taglist-language-to-ctags-alist i)))
(progn
(setq language-config (nth 1 (elt taglist-language-to-ctags-alist i)))))
(setq i (1+ i)))
(if (not language-config)
(error "Unsupported language: %s" detected-language))
language-config))
(defun taglist-get-ctags-language-name (detected-language)
"get ctags-language by detected-language e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"C\""
(let ((ctags-language-config (taglist-get-ctags-language-config detected-language))
(ctags-language nil))
(setq ctags-language (car (split-string ctags-language-config ";" t)))
ctags-language))
(defsubst taglist-filter-unsupport-kinds (ctags-language expect-ctags-kinds)
"Return the supported kinds of current version `ctags'."
(let ((all-kinds nil)
(ctags-config nil)
(actual-ctags-kinds expect-ctags-kinds)
)
(setq all-kinds
(mapcar (lambda (line) (substring line 0 1) )
(split-string
(apply
#'taglist-ctags-process-string
"ctags" (append
(list (concat "--list-kinds=" ctags-language)))) "\n" t)))
(let ((found nil)
(element nil)
(i 0))
(dolist (kind expect-ctags-kinds)
(setq found nil)
(setq i 0)
(while (and (not found)
(< i (length all-kinds)))
(setq element (elt all-kinds i))
(if (string= (substring kind 0 1) element)
(setq found t))
(setq i (1+ i)))
(if (not found)
(progn
(setq actual-ctags-kinds (remove kind actual-ctags-kinds))))))
actual-ctags-kinds))
(defun taglist-get-ctags-language-full-kinds (detected-language)
"Get full ctags language kinds by detected-language. e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return a list (\"d:macro\" \"g:enum\" \"s:struct\" \"u:union\"
\"t:typedef\" \"v:variable\" \"f:function\")"
(let* ((ctags-language-config-string (taglist-get-ctags-language-config detected-language))
(ctags-language-config (split-string ctags-language-config-string ";" t))
(ctags-language-kinds nil))
(setq ctags-language-kinds (taglist-filter-unsupport-kinds
(car ctags-language-config)
(cdr ctags-language-config)))
ctags-language-kinds))
(defun taglist-get-ctags-language-short-kinds (detected-language)
"get kinds by detected-language.
e.g.
\"C;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function\"
return \"dgsutvf\""
(let ((kinds ""))
(dolist (element (taglist-get-ctags-language-full-kinds detected-language))
(setq kinds (concat kinds (substring element 0 1))))
kinds))
(defun taglist-get-tag-lines ()
"Return all tags of current buffer;"
(let* ((detected-language (taglist-detect-language))
(ctags-language (taglist-get-ctags-language-name detected-language))
(ctags-lang-kinds (taglist-get-ctags-language-short-kinds detected-language))
(file (buffer-file-name taglist-source-code-buffer)))
(setq taglist-current-language detected-language)
(if file
(split-string
(apply #'taglist-ctags-process-string
"ctags"
(append (list "-f" "-"
"--format=2"
"--excmd=number"
"--fields=nks"
"--sort=no"
(concat "--language-force=" ctags-language)
(concat "--" ctags-language "-kinds=" ctags-lang-kinds)
taglist-tmp-file
)))
"\n" t)
(insert (concat "Warnning: " (buffer-name taglist-source-code-buffer) " doesn't exist on your disk, you should save it first!\n"))
nil)))
;; e.g. tagline = main /path/to/src/ip46.c 38;" f line:38
(defun taglist-convert-to-elements (tagline)
"Convert tagline to a tag(tag-name tag-line tag-type) "
(let ((elements (split-string tagline "\t" t)))
(list (car elements) (string-to-number (nth 2 elements)) (nth 3 elements))))
(defun taglist-jump-to-tag ()
"Jump to a tag, corresponding the current line in tag buffer.
When called standing on a line of tag list, it closes the list
buffer and sets the point to a tag, corresponding the line."
(interactive)
(let ((tag-record (nth (1- (line-number-at-pos)) taglist-actual-tags)))
(if (and tag-record (= 0 (taglist-line tag-record)))
(setq tag-record (nth (line-number-at-pos) taglist-actual-tags)))
(if (and tag-record (taglist-line tag-record))
(progn
(kill-buffer (current-buffer))
(switch-to-buffer taglist-source-code-buffer t)
(taglist-goto-line (taglist-line tag-record))
(recenter))
(message "The line does not contain tag description!"))))
(defun taglist-matches-all (string substrings)
"Return non-nil if STRING contain each of SUBSTRINGS as a substring."
(reduce (lambda (prev part) (and prev (string-match part string))) substrings :initial-value t))
(defstruct taglist
(tag) ;; tag name, e.g. main
(line) ;; line number of tag, e.g. 11
(type) ;; type of the tag: e.g. f
)
(defun taglist-gen-display-struct (types taglines)
"Return a list of three strings, representing type, parent and name of tag F."
;; (message "types = %s, taglines = %s" types taglines)
(let ((tags-struct nil))
;; loop for each tag type
(dolist (tag-type types)
(let* ((element (split-string tag-type ":" t))
(type-abbr (car element))
(type-name (nth 1 element))
(type-occur nil)
)
;; (message "%s %s" type-abbr type-name)
;; loop for all taglines
(dolist (tagline taglines)
;; tagline (main 38 f)
;; when current tag type matched
(when (string= type-abbr (nth 2 tagline))
(if type-occur ;; when current tag is not first time appear.
;; (message "%s" tagline)
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; if current tag is first time appear, then display type name and current tag.
(setq tags-struct (append tags-struct (list (make-taglist :tag type-name :line 0 :type ""))))
(setq tags-struct (append tags-struct (list (make-taglist :tag (concat " " (car tagline)) :line (nth 1 tagline) :type (nth 2 tagline)))))
;; (message "%s" type-name)
;; (message "%s" tagline)
(setq type-occur t))))))
;; (message "tags-struct = %s" tags-struct)
;; return tags-struct
tags-struct)
)
(defun taglist-search-string-updated ()
"Update tag list according to search string."
(message taglist-search-string)
;; let s:tlist_def_c_settings = 'c;d:macro;g:enum;s:struct;u:union;t:typedef;v:variable;f:function'
;; (setq types (list "d:Macro" "g:Enum" "s:Struct" "u:Union" "t:Typedef" "v:Variable" "f:Function"))
(let ((types (taglist-get-ctags-language-full-kinds taglist-current-language))
(taglist-actual-tags-tmp
;; remove-if-not: Remove all items not satisfying search string.
(remove-if-not
(lambda (element)
(taglist-matches-all (car element) (split-string taglist-search-string)))
taglist-all-tags)))
;; ("DEBUG" 11 "d") ("main" 18 "f")
(setq taglist-actual-tags (taglist-gen-display-struct types taglist-actual-tags-tmp)))
;; (message "taglist-actual-tags = %S" taglist-actual-tags)
(erase-buffer)
(dolist (i taglist-overlays)
;; Delete the overlay from its buffer.
(delete-overlay i))
(setq taglist-overlays nil)
;; [cl-struct-taglist "main" 38 "f"]
(dolist (tag-record taglist-actual-tags)
(insert (concat (taglist-tag tag-record) "\n")))
(let ((offset 0)
(pos 0)
(line-pos nil)
(tag-record nil)
(output (buffer-string))
(search-strings (split-string taglist-search-string)))
(dolist (search-string search-strings)
(while (string-match search-string output offset)
(progn
(setq pos (match-beginning 0))
(setq offset (match-end 0))
;; match: start form 0, overlay: start from 1;
(setq tag-record (nth (1- (line-number-at-pos pos)) taglist-actual-tags))
(if (not (= 0 (taglist-line tag-record)))
(progn
(push (make-overlay (+ 1 pos) (+ 1 offset)) taglist-overlays)
(overlay-put (car taglist-overlays) 'face '(background-color . "yellow"))
(if (not line-pos)
(setq line-pos (line-number-at-pos pos)))
)))))
(if line-pos
(taglist-goto-line line-pos)
(taglist-goto-line (+ 1 (/ (count-lines (point-min) (point-max)) 2)))))
)
(defun taglist-key-pressed (key)
"Called when KEY is pressed."
(setq taglist-search-string (concat taglist-search-string (char-to-string key)))
(taglist-search-string-updated))
(defun taglist-backspace-pressed ()
"Called when Backspace is pressed."
(interactive)
(setq taglist-search-string (taglist-string-without-last taglist-search-string 1))
(taglist-search-string-updated))
(defun taglist-make-key-function (key)
"Return a function for KEY."
`(lambda () (interactive) (taglist-key-pressed ,key)))
(defun taglist-key-itself (map key)
"Maps in the MAP KEY to its function."
(define-key map (char-to-string key) (taglist-make-key-function key)))
(defun taglist-escape ()
"Kill tag list buffer."
(interactive)
(kill-buffer (current-buffer))
(delete-file taglist-tmp-file)
(switch-to-buffer taglist-source-code-buffer))
(defvar taglist-mode-map
(let ((map (make-sparse-keymap)))
(suppress-keymap map)
(do ((k (string-to-char "a") (+ 1 k))) ((> k (string-to-char "z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "A") (+ 1 k))) ((> k (string-to-char "Z")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(do ((k (string-to-char "0") (+ 1 k))) ((> k (string-to-char "9")))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(dolist (k (string-to-list "=><&!"))
(define-key
map
(read-kbd-macro (char-to-string k))
(taglist-make-key-function k)))
(taglist-key-itself map (string-to-char " "))
(taglist-key-itself map (string-to-char "_"))
(define-key map (kbd "<RET>") 'taglist-jump-to-tag)
(define-key map (kbd "<backspace>") 'taglist-backspace-pressed)
;; Cause M-v doesn't work!!!
;; (define-key map (kbd "<ESC>") 'taglist-escape)
(define-key map (kbd "C-q") 'taglist-escape)
(define-key map (kbd "M-q") 'taglist-escape)
(define-key map "\C-v" 'scroll-up)
(define-key map "\M-v" 'scroll-down)
map)
"Keymap for `taglist-mode'.")
(defcustom ctags-executable-directory nil
"If non-nil the directory to search global executables."
:type '(choice (const :tag "Unset" nil) directory)
:risky t
:group 'ctags)
(defun taglist-ctags-program-path (name)
(if ctags-executable-directory
;; (expand-file-name NAME &optional DEFAULT-DIRECTORY)
;; Convert filename NAME to absolute, and canonicalize it.
(expand-file-name name ctags-executable-directory)
name))
(defun taglist-ctags-process-string (program &rest args)
(with-temp-buffer
;; (process-file PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS)
;; Process files synchronously in a separate process.
(let ((exit (apply #'process-file
(taglist-ctags-program-path program) nil t nil args))
(output (progn
(goto-char (point-max))
(skip-chars-backward " \t\n")
(buffer-substring (point-min) (point)))))
(or (zerop exit)
(error "`%s' non-zero exit: %s" program output))
output)))
;; /usr/local/bin/ctags --version
;; Universal Ctags Development(ebe7328), Copyright (C) 2015 Universal Ctags Team
;; Universal Ctags is derived from Exuberant Ctags.
;; Exuberant Ctags 5.8, Copyright (C) 1996-2009 PI:NAME:<NAME>END_PI
;; Compiled: Nov 9 2015, 15:37:41
;; URL: https://ctags.io/
;; Optional compiled features: +wildcards, +regex, +debug, +option-directory, +coproc
;; ctags-exuberant --version
;; ctags-exuberant: Warning: Ignoring non-option in ./.ctags
;; Exuberant Ctags 5.9~svn20110310, Copyright (C) 1996-2009 PI:NAME:<NAME>END_PI
;; Addresses: <PI:EMAIL:<EMAIL>END_PI>, http://ctags.sourceforge.net
;; Optional compiled features: +wildcards, +regex
;; ctags.emacs24 --version
;; ctags (GNU Emacs 24.5)
;; Copyright (C) 2015 Free Software Foundation, Inc.
;; This program is distributed under the terms in ETAGS.README
(defsubst taglist-ctags-variant ()
"Return the variant of `ctags'."
(let ((buffer-string nil)
(ctags-variant nil ))
(setq buffer-string (apply #'taglist-ctags-process-string
"ctags" (append (list "--version"))))
(if (string-match "Emacs" buffer-string 0)
(setq ctags-variant "emacs-ctags")
(if (string-match "Universal" buffer-string 0)
(setq ctags-variant "universal-ctags")
(if (string-match "Exuberant" buffer-string 0)
(setq ctags-variant "exuberant-ctags"))))
ctags-variant))
(defun taglist-highlight-current-tag ()
"Highlight current tag line"
;; taglist-all-tags =
;; (("INET_ADDRSTRLEN" 17 "d")
;; ("INET6_ADDRSTRLEN" 18 "d")
;; ("ZERO" 19 "d")
;; ("BUF_SIZE" 20 "d")
;; ("global_var" 22 "v")
;; ("IP4_2_6" 24 "f")
;; ("IP6_2_4" 31 "f")
;; ("main" 38 "f"))
;; get current line number; and find range of line nubmer in taglist-all-tags
;; Set current line corresponding to the current function/tag if any
(let ((prev-line 0)
(curr-line 0)
(tag-line 0)
(i 0))
(while (and
(= 0 tag-line)
(< i (length taglist-all-tags)))
(setq curr-line (nth 1 (elt taglist-all-tags i)))
(setq i (1+ i))
;; (message "taglist-current-line = %d, prev-line = %d curr-line = %d, tag-line = %d"
;; taglist-current-line
;; prev-line
;; curr-line
;; tag-line)
(if (= taglist-current-line curr-line)
;; best case
(setq tag-line curr-line)
(if (< taglist-current-line curr-line)
;; if current line in source code buffer less than the line number
;; of current encounter tag in taglist, then choose the line number
;; of previous tags.
(if (= 0 prev-line)
;; if line number of previous tag is zero, then choose the line
;; number of current tag
(setq tag-line curr-line)
(setq tag-line prev-line)
)
;; if current line in source code buffer is big than the line number
;; of current encounter tag in taglist, then continue loop.
))
;; (message "tag-line = %d" tag-line)
(setq prev-line curr-line))
(if (= 0 tag-line)
(setq tag-line prev-line))
;; (message "found tag-line = %d" tag-line)
(let ((line (position-if
(lambda (item) (= tag-line (taglist-line item)))
taglist-actual-tags)))
(when line
(taglist-goto-line (1+ line)))))
(hl-line-mode))
;;;###autoload
(defun taglist-list-tags ()
"Show tag list of current buffer in a newly created buffer.
This function is recommended to be bound to some convinient hotkey."
(interactive)
;; (message "taglist-ctags-variant = %s" (taglist-ctags-variant))
(if (string= (taglist-ctags-variant) "emacs-ctags")
(error "taglist doesn't support emacs ctags, please install universal-ctags or exuberant-ctags!")
)
(setq taglist-source-code-buffer (current-buffer))
(setq taglist-current-line (line-number-at-pos))
(setq taglist-current-major-mode major-mode)
(setq taglist-tmp-file (make-temp-file "taglist."))
(write-region (point-min) (point-max) taglist-tmp-file)
(switch-to-buffer (get-buffer-create (concat (buffer-name (current-buffer)) " tag list")) t)
(taglist-mode))
(defun taglist-mode-init ()
"Initialize tag list mode."
;; current tag search string
(make-local-variable 'taglist-search-string)
;; list of taglist-tag structures
(make-local-variable 'taglist-all-tags)
;; subset of taglist-all-tags that contain taglist-search string in the name string
(make-local-variable 'taglist-actual-tags)
;; overlays used to highligh search string matches in tag names
(make-local-variable 'taglist-overlays)
(make-local-variable 'taglist-current-language)
(set (make-local-variable 'font-lock-defaults) taglist-font-lock-defaults)
;; (message "current-line = %d" taglist-current-line)
(setq taglist-overlays nil)
(setq taglist-search-string "")
(setq taglist-all-tags
(let* ((tag-lines (taglist-get-tag-lines)))
(if tag-lines
(mapcar 'taglist-convert-to-elements tag-lines))))
(if (not taglist-all-tags)
(insert "No taglist, Press <C-q> or <M-q> to exist!!!\n")
(taglist-search-string-updated)
(taglist-highlight-current-tag)))
(define-derived-mode taglist-mode nil "Taglist"
"EmacsAssist tag selection mode.
\\{taglist-mode-map}
Turning on Text mode runs the normal hook `taglist-mode-hook'."
(taglist-mode-init))
;; ================================== Tag navigator end ======================
(provide 'taglist)
;;; taglist.el ends here
;; taglist.el:122:70:Warning: function `find-if' from cl package called at runtime
;; taglist.el:632:96:Warning: function `reduce' from cl package called at runtime
;; taglist.el:698:11:Warning: function `remove-if-not' from cl package called at runtime
;; taglist.el:902:18:Warning: function `position-if' from cl package called at runtime
;; [PATCH] emacs: Suppress warnings about using cl at runtime
;; https://notmuchmail.org/pipermail/notmuch/2012/010297.html
;; Local Variables:
;; byte-compile-warnings: (not cl-functions)
;; End:
|
[
{
"context": "turep! +latexmk)\n (package! auctex-latexmk :pin \"4d353522650d7685acbf1d38f7dbc504f734bd84\"))\n\n(when (featurep! +cdlatex)\n (package! cdlate",
"end": 622,
"score": 0.6855131387710571,
"start": 582,
"tag": "KEY",
"value": "4d353522650d7685acbf1d38f7dbc504f734bd84"
},
{
"context": "letion company)\n (package! company-auctex :pin \"9400a2ec7459dde8cbf1a5d50dfee4e300ed7e18\")\n (package! company-reftex :pin \"42eb98c6504e65",
"end": 891,
"score": 0.8299546837806702,
"start": 852,
"tag": "KEY",
"value": "400a2ec7459dde8cbf1a5d50dfee4e300ed7e18"
},
{
"context": "b81b65b9d5798e76\")\n (package! company-math :pin \"45778f5731c97a21a83e3b965cbde42018709afd\"))\n",
"end": 1041,
"score": 0.930993378162384,
"start": 1001,
"tag": "KEY",
"value": "45778f5731c97a21a83e3b965cbde42018709afd"
}
] | modules/lang/latex/packages.el | abougouffa/doom-emacs | 5 | ;; -*- no-byte-compile: t; -*-
;;; lang/latex/packages.el
(package! auctex
:recipe (:files ("*.el" "*.info" "dir"
"doc" "etc" "images" "latex" "style"))
:pin "830e40a0639aedc6c362a3a01e160aaa8246bb99")
(package! adaptive-wrap :pin "0d5b4a07de76d87dd64333a566a8a0a845f2b9f0")
(package! latex-preview-pane :pin "5297668a89996b50b2b62f99cba01cc544dbed2e")
(when (featurep! :editor evil +everywhere)
(package! evil-tex :pin "0fa85c3fc88d96621002b5a1b79efcc06776642f"))
;; Optional module features.
(when (featurep! +latexmk)
(package! auctex-latexmk :pin "4d353522650d7685acbf1d38f7dbc504f734bd84"))
(when (featurep! +cdlatex)
(package! cdlatex :pin "8e963c68531f75e459e8ebe7a34fd3ba9d3729a0"))
;; Features according to other user selected options.
(when (featurep! :completion company)
(package! company-auctex :pin "9400a2ec7459dde8cbf1a5d50dfee4e300ed7e18")
(package! company-reftex :pin "42eb98c6504e65989635d95ab81b65b9d5798e76")
(package! company-math :pin "45778f5731c97a21a83e3b965cbde42018709afd"))
| 7345 | ;; -*- no-byte-compile: t; -*-
;;; lang/latex/packages.el
(package! auctex
:recipe (:files ("*.el" "*.info" "dir"
"doc" "etc" "images" "latex" "style"))
:pin "830e40a0639aedc6c362a3a01e160aaa8246bb99")
(package! adaptive-wrap :pin "0d5b4a07de76d87dd64333a566a8a0a845f2b9f0")
(package! latex-preview-pane :pin "5297668a89996b50b2b62f99cba01cc544dbed2e")
(when (featurep! :editor evil +everywhere)
(package! evil-tex :pin "0fa85c3fc88d96621002b5a1b79efcc06776642f"))
;; Optional module features.
(when (featurep! +latexmk)
(package! auctex-latexmk :pin "<KEY>"))
(when (featurep! +cdlatex)
(package! cdlatex :pin "8e963c68531f75e459e8ebe7a34fd3ba9d3729a0"))
;; Features according to other user selected options.
(when (featurep! :completion company)
(package! company-auctex :pin "9<KEY>")
(package! company-reftex :pin "42eb98c6504e65989635d95ab81b65b9d5798e76")
(package! company-math :pin "<KEY>"))
| true | ;; -*- no-byte-compile: t; -*-
;;; lang/latex/packages.el
(package! auctex
:recipe (:files ("*.el" "*.info" "dir"
"doc" "etc" "images" "latex" "style"))
:pin "830e40a0639aedc6c362a3a01e160aaa8246bb99")
(package! adaptive-wrap :pin "0d5b4a07de76d87dd64333a566a8a0a845f2b9f0")
(package! latex-preview-pane :pin "5297668a89996b50b2b62f99cba01cc544dbed2e")
(when (featurep! :editor evil +everywhere)
(package! evil-tex :pin "0fa85c3fc88d96621002b5a1b79efcc06776642f"))
;; Optional module features.
(when (featurep! +latexmk)
(package! auctex-latexmk :pin "PI:KEY:<KEY>END_PI"))
(when (featurep! +cdlatex)
(package! cdlatex :pin "8e963c68531f75e459e8ebe7a34fd3ba9d3729a0"))
;; Features according to other user selected options.
(when (featurep! :completion company)
(package! company-auctex :pin "9PI:KEY:<KEY>END_PI")
(package! company-reftex :pin "42eb98c6504e65989635d95ab81b65b9d5798e76")
(package! company-math :pin "PI:KEY:<KEY>END_PI"))
|
[
{
"context": "ording to their depth.\n\n;; Copyright (C) 2010-2011 Jeremy L. Rayman.\n;; Author: Jeremy L. Rayman <jeremy.rayman@gmail",
"end": 147,
"score": 0.9998841285705566,
"start": 131,
"tag": "NAME",
"value": "Jeremy L. Rayman"
},
{
"context": "pyright (C) 2010-2011 Jeremy L. Rayman.\n;; Author: Jeremy L. Rayman <jeremy.rayman@gmail.com>\n;; Maintainer: Jeremy L",
"end": 176,
"score": 0.9998874664306641,
"start": 160,
"tag": "NAME",
"value": "Jeremy L. Rayman"
},
{
"context": "11 Jeremy L. Rayman.\n;; Author: Jeremy L. Rayman <jeremy.rayman@gmail.com>\n;; Maintainer: Jeremy L. Rayman <jeremy.rayman@g",
"end": 201,
"score": 0.9999344348907471,
"start": 178,
"tag": "EMAIL",
"value": "jeremy.rayman@gmail.com"
},
{
"context": "L. Rayman <jeremy.rayman@gmail.com>\n;; Maintainer: Jeremy L. Rayman <jeremy.rayman@gmail.com>\n;; Created: 2010-09-02\n",
"end": 234,
"score": 0.9998862147331238,
"start": 218,
"tag": "NAME",
"value": "Jeremy L. Rayman"
},
{
"context": "ayman@gmail.com>\n;; Maintainer: Jeremy L. Rayman <jeremy.rayman@gmail.com>\n;; Created: 2010-09-02\n;; Version: 1.2.1\n;; Keyw",
"end": 259,
"score": 0.9999358057975769,
"start": 236,
"tag": "EMAIL",
"value": "jeremy.rayman@gmail.com"
}
] | config/linux/.elisp/rainbow-delimiters.el | rapattack88/mcclanahoochie | 1 | ;;; rainbow-delimiters.el --- Color nested parentheses, brackets, and braces according to their depth.
;; Copyright (C) 2010-2011 Jeremy L. Rayman.
;; Author: Jeremy L. Rayman <jeremy.rayman@gmail.com>
;; Maintainer: Jeremy L. Rayman <jeremy.rayman@gmail.com>
;; Created: 2010-09-02
;; Version: 1.2.1
;; Keywords: faces, convenience, lisp, matching, tools
;; EmacsWiki: RainbowDelimiters
;; URL: http://www.emacswiki.org/emacs/rainbow-delimiters.el
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This is a "rainbow parentheses" mode which includes support for
;; parens "()", brackets "[]", and braces "{}". It conveys nesting
;; depth by using a different face for each level. It colors all
;; statements at a given level using the same color - if several
;; statements are all at the same nested depth, they will all be the
;; same color.
;;
;; Great care has been taken to make this mode FAST. You should see no
;; discernible change in scrolling or editing speed while using it,
;; even with delimiter-rich languages like Clojure, Lisp, and Scheme.
;;
;; The one exception is with extremely large nested data structures
;; having hundreds of delimiters; in that case there will be a brief
;; pause to colorize the structure the very first time it is displayed
;; on screen; from then on editing this structure will perform at full
;; speed.
;;
;; Default colors have been chosen with the philosophy that it's
;; better be less intrusive than to be more colorful. Color schemes
;; are always a matter of taste. If you do take the time to design a
;; new color scheme, please post it on the EmacsWiki page!
;; URL: http://www.emacswiki.org/emacs/RainbowDelimiters
;;; Installation:
;; 1. Place rainbow-delimiters.el on your emacs load-path.
;;
;; 2. Compile the file (necessary for speed):
;; M-x byte-compile-file <location of rainbow-delimiters.el>
;;
;; 3. Add the following to your dot-emacs/init file:
;; (require 'rainbow-delimiters)
;;
;; 4. Add hooks for modes where you want it enabled, for example:
;; (add-hook 'clojure-mode-hook 'rainbow-delimiters-mode)
;;
;; - To activate rainbow-delimiters mode temporarily in a buffer:
;; M-x rainbow-delimiters-mode
;;; Customization:
;; To customize various options, including the color scheme:
;; M-x customize-group rainbow-delimiters
;;
;; color-theme.el users:
;; If you use the color-theme package, you can specify custom colors
;; by adding the appropriate faces to your theme.
;; - Faces take the form of:
;; 'rainbow-delimiters-depth-#-face' with # being the depth.
;; Depth begins at 1, the outermost color.
;; Faces exist for depths 1-12.
;; - The unmatched delimiter face is:
;; 'rainbow-delimiters-unmatched-delimiter-face'
;;; Change Log:
;; 1.0 - Initial release.
;; 1.1 - Stop tracking each delimiter's depth independently.
;; This had lead to confusing results when viewing clojure
;; code. Instead, just color based on current nesting inside
;; all delimiters combined.
;; - Added 'all-delimiters' faces to apply a color scheme to
;; all delimiters at once. Other faces inherit from this group.
;; 1.1.1 - Change color scheme to a lighter, more subtle style.
;; 1.1.2: (2011-03-25)
;; - Add an unmatched-delimiter face and correct problem with
;; coloring of text following unmatched closing delims.
;; 1.2: (2011-03-28)
;; - Unify delimiter faces: all delimiter types now use the same depth
;; faces, of form 'rainbow-delimiters-depth-#-face'.
;; 1.2.1: (2011-03-29)
;; - Conform to ELPA conventions.
;;; TODO:
;; - Add support for nested tags (XML, HTML)
;;; Issues:
;; - Rainbow-delimiters mode does not appear to change the color of
;; delimiters when Org-mode is enabled.
;;; Code:
(eval-when-compile (require 'cl))
;;; Customize interface:
(defgroup rainbow-delimiters nil
"Color nested parentheses, brackets, and braces according to their depth."
:prefix "rainbow-delimiters-"
:link '(url-link :tag "Website for rainbow-delimiters (EmacsWiki)"
"http://www.emacswiki.org/emacs/RainbowDelimiters")
:group 'applications)
(defgroup rainbow-delimiters-faces nil
"Faces for each nested depth. Used to color delimiter pairs.
Depths 1-12 are defined. Depth 1 is the outermost delimiter pair."
:group 'rainbow-delimiters
:link '(custom-group-link "rainbow-delimiters")
:prefix 'rainbow-delimiters-faces-)
;;; Faces:
;; Unmatched delimiter face:
(defface rainbow-delimiters-unmatched-face
'((t (:foreground "#88090B")))
"Face to color unmatched closing delimiters with."
:group 'rainbow-delimiters
:group 'rainbow-delimiters-faces)
;; NOTE: The use of repetitious definitions for depth faces is temporary.
;; Once the emacs 24 color theme support comes in, this will be reevaluated.
;; Faces for colorizing delimiters at each level:
(defface rainbow-delimiters-depth-1-face
'((t (:foreground "grey55")))
"Rainbow-delimiters nested delimiter face, depth 1 - the outermost pair."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-2-face
'((t (:foreground "#93a8c6")))
"Rainbow-delimiters nested delimiter face, depth 2."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-3-face
'((t (:foreground "#b0b1a3")))
"Rainbow-delimiters nested delimiter face, depth 3."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-4-face
'((t (:foreground "#97b098")))
"Rainbow-delimiters nested delimiter face, depth 4."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-5-face
'((t (:foreground "#aebed8")))
"Rainbow-delimiters nested delimiter face, depth 5."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-6-face
'((t (:foreground "#b0b0b3")))
"Rainbow-delimiters nested delimiter face, depth 6."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-7-face
'((t (:foreground "#90a890")))
"Rainbow-delimiters nested delimiter face, depth 7."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-8-face
'((t (:foreground "#a2b6da")))
"Rainbow-delimiters nested delimiter face, depth 8."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-9-face
'((t (:foreground "#9cb6ad")))
"Rainbow-delimiters nested delimiter face, depth 9."
:group 'rainbow-delimiters-faces)
;; Emacs doesn't sort face names by number correctly above 1-9; trick it into
;; proper sorting by prepending a _ before the faces with depths over 10.
(defface rainbow-delimiters-depth-_10-face
'((t (:foreground "#83787e")))
"Rainbow-delimiters nested delimiter face, depth 10."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_11-face
'((t (:foreground "#e1ddca")))
"Rainbow-delimiters nested delimiter face, depth 11."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_12-face
'((t (:foreground "#e0c7c7")))
"Rainbow-delimiters nested delimiter face, depth 12."
:group 'rainbow-delimiters-faces)
;; Variable aliases for faces 10+:
;; We prepend an underline to numbers 10+ to force customize to sort correctly.
;; Here we define aliases without the underline for use everywhere else.
(put 'rainbow-delimiters-depth-10-face
'face-alias
'rainbow-delimiters-depth-_10-face)
(put 'rainbow-delimiters-depth-11-face
'face-alias
'rainbow-delimiters-depth-_11-face)
(put 'rainbow-delimiters-depth-12-face
'face-alias
'rainbow-delimiters-depth-_12-face)
;;; Face utility functions
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-depth-face (depth)
"Return face-name 'rainbow-delimiters-depth-DEPTH-face' as a string.
DEPTH is the number of nested levels deep for the delimiter being colorized.
Returns a face namestring the of form 'rainbow-delimiters-depth-DEPTH-face',
e.g. 'rainbow-delimiters-depth-1-face'."
(concat "rainbow-delimiters-depth-" (number-to-string depth) "-face"))
;;; Nesting level
;; syntax-table: used with parse-partial-sexp for determining current depth.
(defvar rainbow-delimiters-delim-syntax-table
(let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
(modify-syntax-entry ?\( "() " table)
(modify-syntax-entry ?\) ")( " table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
(modify-syntax-entry ?\{ "(}" table)
(modify-syntax-entry ?\} "){" table)
table)
"Syntax table for recognizing all supported delimiter types.")
(defun rainbow-delimiters-depth (point)
"Return # of nested levels of parens, brackets, braces POINT is inside of."
(save-excursion
(beginning-of-defun)
(let ((depth
(with-syntax-table rainbow-delimiters-delim-syntax-table
(car (parse-partial-sexp (point) point)))))
(if (>= depth 0)
depth
0)))) ; ignore negative depths created by unmatched closing parens.
;;; Text properties
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-propertize-delimiter (point depth)
"Colorize delimiter at POINT according to DEPTH.
POINT is the point of character to propertize.
DEPTH is the nested delimiter depth at POINT, which determines the face to use.
Sets text properties:
`font-lock-face' to the corresponding delimiter face.
`rear-nonsticky' to prevent color from bleeding into subsequent characters typed by the user."
(with-silent-modifications
(let ((delim-face (if (<= depth 0)
"rainbow-delimiters-unmatched-face"
(rainbow-delimiters-depth-face depth))))
;; (when (eq depth -1) (message "Unmatched delimiter at char %s." point))
(add-text-properties point (1+ point)
`(font-lock-face ,delim-face
rear-nonsticky t)))))
(defun rainbow-delimiters-unpropertize-delimiter (point)
"Remove text properties set by rainbow-delimiters mode from char at POINT."
(remove-text-properties point (1+ point)
'(font-lock-face nil
rear-nonsticky nil)))
(defun rainbow-delimiters-char-ineligible-p (point)
"Return t if char at POINT should be skipped, e.g. if inside a comment.
Returns t if char at point meets one of the following conditions:
- Inside a string.
- Inside a comment.
- Is an escaped char, e.g. ?\)"
(let ((parse-state (save-excursion
(beginning-of-defun)
;; (point) is at beg-of-defun; point is the char location
(parse-partial-sexp (point) point))))
(or
(nth 3 parse-state) ; inside string?
(nth 4 parse-state) ; inside comment?
(and (eq (char-before point) ?\\) ; escaped char, e.g. ?\) - not counted
(and (not (eq (char-before (1- point)) ?\\)) ; special-case: ignore ?\\
(eq (char-before (1- point)) ?\?))))))
;; standard char read syntax '?)' is not tested for because emacs manual states
;; that punctuation such as delimiters should _always_ use escaped '?\)' form.
;;; JIT-Lock functionality
;; Used to skip delimiter-by-delimiter `rainbow-delimiters-propertize-region'.
(defvar rainbow-delimiters-delim-regex "\\(\(\\|\)\\|\\[\\|\\]\\|\{\\|\}\\)"
"Regex matching all opening and closing delimiters we intend to colorize.")
;; main function called by jit-lock:
(defun rainbow-delimiters-propertize-region (start end)
"Colorize delimiters in region between START and END.
Used by jit-lock for dynamic highlighting."
(save-excursion
(goto-char start)
;; START can be anywhere in buffer; begin depth counts from values at START.
(let ((depth (rainbow-delimiters-depth start)))
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
(backward-char) ; re-search-forward places point after delim; go back.
(unless (rainbow-delimiters-char-ineligible-p (point))
(let ((delim (char-after (point))))
(cond ((eq ?\( delim) ; (
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\) delim) ; )
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched paren
(1- depth))))
((eq ?\[ delim) ; [
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\] delim) ; ]
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched bracket
(1- depth))))
((eq ?\{ delim) ; {
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\} delim) ; }
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched brace
(1- depth)))))))
;; move past delimiter so re-search-forward doesn't pick it up again
(forward-char)))))
(defun rainbow-delimiters-unpropertize-region (start end)
"Remove mode faces from delimiters in region between START and END."
(save-excursion
(goto-char start)
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
;; re-search-forward places point 1 further than the delim matched:
(rainbow-delimiters-unpropertize-delimiter (1- (point))))))
;;; Minor mode:
;;;###autoload
(define-minor-mode rainbow-delimiters-mode
"Color nested parentheses, brackets, and braces according to their depth."
nil "" nil ; No modeline lighter - it's already obvious when the mode is on.
(if (not rainbow-delimiters-mode)
(progn
(jit-lock-unregister 'rainbow-delimiters-propertize-region)
(rainbow-delimiters-unpropertize-region (point-min) (1- (point-max))))
(jit-lock-register 'rainbow-delimiters-propertize-region t)))
(provide 'rainbow-delimiters)
;;; rainbow-delimiters.el ends here.
| 48657 | ;;; rainbow-delimiters.el --- Color nested parentheses, brackets, and braces according to their depth.
;; Copyright (C) 2010-2011 <NAME>.
;; Author: <NAME> <<EMAIL>>
;; Maintainer: <NAME> <<EMAIL>>
;; Created: 2010-09-02
;; Version: 1.2.1
;; Keywords: faces, convenience, lisp, matching, tools
;; EmacsWiki: RainbowDelimiters
;; URL: http://www.emacswiki.org/emacs/rainbow-delimiters.el
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This is a "rainbow parentheses" mode which includes support for
;; parens "()", brackets "[]", and braces "{}". It conveys nesting
;; depth by using a different face for each level. It colors all
;; statements at a given level using the same color - if several
;; statements are all at the same nested depth, they will all be the
;; same color.
;;
;; Great care has been taken to make this mode FAST. You should see no
;; discernible change in scrolling or editing speed while using it,
;; even with delimiter-rich languages like Clojure, Lisp, and Scheme.
;;
;; The one exception is with extremely large nested data structures
;; having hundreds of delimiters; in that case there will be a brief
;; pause to colorize the structure the very first time it is displayed
;; on screen; from then on editing this structure will perform at full
;; speed.
;;
;; Default colors have been chosen with the philosophy that it's
;; better be less intrusive than to be more colorful. Color schemes
;; are always a matter of taste. If you do take the time to design a
;; new color scheme, please post it on the EmacsWiki page!
;; URL: http://www.emacswiki.org/emacs/RainbowDelimiters
;;; Installation:
;; 1. Place rainbow-delimiters.el on your emacs load-path.
;;
;; 2. Compile the file (necessary for speed):
;; M-x byte-compile-file <location of rainbow-delimiters.el>
;;
;; 3. Add the following to your dot-emacs/init file:
;; (require 'rainbow-delimiters)
;;
;; 4. Add hooks for modes where you want it enabled, for example:
;; (add-hook 'clojure-mode-hook 'rainbow-delimiters-mode)
;;
;; - To activate rainbow-delimiters mode temporarily in a buffer:
;; M-x rainbow-delimiters-mode
;;; Customization:
;; To customize various options, including the color scheme:
;; M-x customize-group rainbow-delimiters
;;
;; color-theme.el users:
;; If you use the color-theme package, you can specify custom colors
;; by adding the appropriate faces to your theme.
;; - Faces take the form of:
;; 'rainbow-delimiters-depth-#-face' with # being the depth.
;; Depth begins at 1, the outermost color.
;; Faces exist for depths 1-12.
;; - The unmatched delimiter face is:
;; 'rainbow-delimiters-unmatched-delimiter-face'
;;; Change Log:
;; 1.0 - Initial release.
;; 1.1 - Stop tracking each delimiter's depth independently.
;; This had lead to confusing results when viewing clojure
;; code. Instead, just color based on current nesting inside
;; all delimiters combined.
;; - Added 'all-delimiters' faces to apply a color scheme to
;; all delimiters at once. Other faces inherit from this group.
;; 1.1.1 - Change color scheme to a lighter, more subtle style.
;; 1.1.2: (2011-03-25)
;; - Add an unmatched-delimiter face and correct problem with
;; coloring of text following unmatched closing delims.
;; 1.2: (2011-03-28)
;; - Unify delimiter faces: all delimiter types now use the same depth
;; faces, of form 'rainbow-delimiters-depth-#-face'.
;; 1.2.1: (2011-03-29)
;; - Conform to ELPA conventions.
;;; TODO:
;; - Add support for nested tags (XML, HTML)
;;; Issues:
;; - Rainbow-delimiters mode does not appear to change the color of
;; delimiters when Org-mode is enabled.
;;; Code:
(eval-when-compile (require 'cl))
;;; Customize interface:
(defgroup rainbow-delimiters nil
"Color nested parentheses, brackets, and braces according to their depth."
:prefix "rainbow-delimiters-"
:link '(url-link :tag "Website for rainbow-delimiters (EmacsWiki)"
"http://www.emacswiki.org/emacs/RainbowDelimiters")
:group 'applications)
(defgroup rainbow-delimiters-faces nil
"Faces for each nested depth. Used to color delimiter pairs.
Depths 1-12 are defined. Depth 1 is the outermost delimiter pair."
:group 'rainbow-delimiters
:link '(custom-group-link "rainbow-delimiters")
:prefix 'rainbow-delimiters-faces-)
;;; Faces:
;; Unmatched delimiter face:
(defface rainbow-delimiters-unmatched-face
'((t (:foreground "#88090B")))
"Face to color unmatched closing delimiters with."
:group 'rainbow-delimiters
:group 'rainbow-delimiters-faces)
;; NOTE: The use of repetitious definitions for depth faces is temporary.
;; Once the emacs 24 color theme support comes in, this will be reevaluated.
;; Faces for colorizing delimiters at each level:
(defface rainbow-delimiters-depth-1-face
'((t (:foreground "grey55")))
"Rainbow-delimiters nested delimiter face, depth 1 - the outermost pair."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-2-face
'((t (:foreground "#93a8c6")))
"Rainbow-delimiters nested delimiter face, depth 2."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-3-face
'((t (:foreground "#b0b1a3")))
"Rainbow-delimiters nested delimiter face, depth 3."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-4-face
'((t (:foreground "#97b098")))
"Rainbow-delimiters nested delimiter face, depth 4."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-5-face
'((t (:foreground "#aebed8")))
"Rainbow-delimiters nested delimiter face, depth 5."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-6-face
'((t (:foreground "#b0b0b3")))
"Rainbow-delimiters nested delimiter face, depth 6."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-7-face
'((t (:foreground "#90a890")))
"Rainbow-delimiters nested delimiter face, depth 7."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-8-face
'((t (:foreground "#a2b6da")))
"Rainbow-delimiters nested delimiter face, depth 8."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-9-face
'((t (:foreground "#9cb6ad")))
"Rainbow-delimiters nested delimiter face, depth 9."
:group 'rainbow-delimiters-faces)
;; Emacs doesn't sort face names by number correctly above 1-9; trick it into
;; proper sorting by prepending a _ before the faces with depths over 10.
(defface rainbow-delimiters-depth-_10-face
'((t (:foreground "#83787e")))
"Rainbow-delimiters nested delimiter face, depth 10."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_11-face
'((t (:foreground "#e1ddca")))
"Rainbow-delimiters nested delimiter face, depth 11."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_12-face
'((t (:foreground "#e0c7c7")))
"Rainbow-delimiters nested delimiter face, depth 12."
:group 'rainbow-delimiters-faces)
;; Variable aliases for faces 10+:
;; We prepend an underline to numbers 10+ to force customize to sort correctly.
;; Here we define aliases without the underline for use everywhere else.
(put 'rainbow-delimiters-depth-10-face
'face-alias
'rainbow-delimiters-depth-_10-face)
(put 'rainbow-delimiters-depth-11-face
'face-alias
'rainbow-delimiters-depth-_11-face)
(put 'rainbow-delimiters-depth-12-face
'face-alias
'rainbow-delimiters-depth-_12-face)
;;; Face utility functions
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-depth-face (depth)
"Return face-name 'rainbow-delimiters-depth-DEPTH-face' as a string.
DEPTH is the number of nested levels deep for the delimiter being colorized.
Returns a face namestring the of form 'rainbow-delimiters-depth-DEPTH-face',
e.g. 'rainbow-delimiters-depth-1-face'."
(concat "rainbow-delimiters-depth-" (number-to-string depth) "-face"))
;;; Nesting level
;; syntax-table: used with parse-partial-sexp for determining current depth.
(defvar rainbow-delimiters-delim-syntax-table
(let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
(modify-syntax-entry ?\( "() " table)
(modify-syntax-entry ?\) ")( " table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
(modify-syntax-entry ?\{ "(}" table)
(modify-syntax-entry ?\} "){" table)
table)
"Syntax table for recognizing all supported delimiter types.")
(defun rainbow-delimiters-depth (point)
"Return # of nested levels of parens, brackets, braces POINT is inside of."
(save-excursion
(beginning-of-defun)
(let ((depth
(with-syntax-table rainbow-delimiters-delim-syntax-table
(car (parse-partial-sexp (point) point)))))
(if (>= depth 0)
depth
0)))) ; ignore negative depths created by unmatched closing parens.
;;; Text properties
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-propertize-delimiter (point depth)
"Colorize delimiter at POINT according to DEPTH.
POINT is the point of character to propertize.
DEPTH is the nested delimiter depth at POINT, which determines the face to use.
Sets text properties:
`font-lock-face' to the corresponding delimiter face.
`rear-nonsticky' to prevent color from bleeding into subsequent characters typed by the user."
(with-silent-modifications
(let ((delim-face (if (<= depth 0)
"rainbow-delimiters-unmatched-face"
(rainbow-delimiters-depth-face depth))))
;; (when (eq depth -1) (message "Unmatched delimiter at char %s." point))
(add-text-properties point (1+ point)
`(font-lock-face ,delim-face
rear-nonsticky t)))))
(defun rainbow-delimiters-unpropertize-delimiter (point)
"Remove text properties set by rainbow-delimiters mode from char at POINT."
(remove-text-properties point (1+ point)
'(font-lock-face nil
rear-nonsticky nil)))
(defun rainbow-delimiters-char-ineligible-p (point)
"Return t if char at POINT should be skipped, e.g. if inside a comment.
Returns t if char at point meets one of the following conditions:
- Inside a string.
- Inside a comment.
- Is an escaped char, e.g. ?\)"
(let ((parse-state (save-excursion
(beginning-of-defun)
;; (point) is at beg-of-defun; point is the char location
(parse-partial-sexp (point) point))))
(or
(nth 3 parse-state) ; inside string?
(nth 4 parse-state) ; inside comment?
(and (eq (char-before point) ?\\) ; escaped char, e.g. ?\) - not counted
(and (not (eq (char-before (1- point)) ?\\)) ; special-case: ignore ?\\
(eq (char-before (1- point)) ?\?))))))
;; standard char read syntax '?)' is not tested for because emacs manual states
;; that punctuation such as delimiters should _always_ use escaped '?\)' form.
;;; JIT-Lock functionality
;; Used to skip delimiter-by-delimiter `rainbow-delimiters-propertize-region'.
(defvar rainbow-delimiters-delim-regex "\\(\(\\|\)\\|\\[\\|\\]\\|\{\\|\}\\)"
"Regex matching all opening and closing delimiters we intend to colorize.")
;; main function called by jit-lock:
(defun rainbow-delimiters-propertize-region (start end)
"Colorize delimiters in region between START and END.
Used by jit-lock for dynamic highlighting."
(save-excursion
(goto-char start)
;; START can be anywhere in buffer; begin depth counts from values at START.
(let ((depth (rainbow-delimiters-depth start)))
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
(backward-char) ; re-search-forward places point after delim; go back.
(unless (rainbow-delimiters-char-ineligible-p (point))
(let ((delim (char-after (point))))
(cond ((eq ?\( delim) ; (
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\) delim) ; )
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched paren
(1- depth))))
((eq ?\[ delim) ; [
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\] delim) ; ]
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched bracket
(1- depth))))
((eq ?\{ delim) ; {
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\} delim) ; }
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched brace
(1- depth)))))))
;; move past delimiter so re-search-forward doesn't pick it up again
(forward-char)))))
(defun rainbow-delimiters-unpropertize-region (start end)
"Remove mode faces from delimiters in region between START and END."
(save-excursion
(goto-char start)
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
;; re-search-forward places point 1 further than the delim matched:
(rainbow-delimiters-unpropertize-delimiter (1- (point))))))
;;; Minor mode:
;;;###autoload
(define-minor-mode rainbow-delimiters-mode
"Color nested parentheses, brackets, and braces according to their depth."
nil "" nil ; No modeline lighter - it's already obvious when the mode is on.
(if (not rainbow-delimiters-mode)
(progn
(jit-lock-unregister 'rainbow-delimiters-propertize-region)
(rainbow-delimiters-unpropertize-region (point-min) (1- (point-max))))
(jit-lock-register 'rainbow-delimiters-propertize-region t)))
(provide 'rainbow-delimiters)
;;; rainbow-delimiters.el ends here.
| true | ;;; rainbow-delimiters.el --- Color nested parentheses, brackets, and braces according to their depth.
;; Copyright (C) 2010-2011 PI:NAME:<NAME>END_PI.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Maintainer: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 2010-09-02
;; Version: 1.2.1
;; Keywords: faces, convenience, lisp, matching, tools
;; EmacsWiki: RainbowDelimiters
;; URL: http://www.emacswiki.org/emacs/rainbow-delimiters.el
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This is a "rainbow parentheses" mode which includes support for
;; parens "()", brackets "[]", and braces "{}". It conveys nesting
;; depth by using a different face for each level. It colors all
;; statements at a given level using the same color - if several
;; statements are all at the same nested depth, they will all be the
;; same color.
;;
;; Great care has been taken to make this mode FAST. You should see no
;; discernible change in scrolling or editing speed while using it,
;; even with delimiter-rich languages like Clojure, Lisp, and Scheme.
;;
;; The one exception is with extremely large nested data structures
;; having hundreds of delimiters; in that case there will be a brief
;; pause to colorize the structure the very first time it is displayed
;; on screen; from then on editing this structure will perform at full
;; speed.
;;
;; Default colors have been chosen with the philosophy that it's
;; better be less intrusive than to be more colorful. Color schemes
;; are always a matter of taste. If you do take the time to design a
;; new color scheme, please post it on the EmacsWiki page!
;; URL: http://www.emacswiki.org/emacs/RainbowDelimiters
;;; Installation:
;; 1. Place rainbow-delimiters.el on your emacs load-path.
;;
;; 2. Compile the file (necessary for speed):
;; M-x byte-compile-file <location of rainbow-delimiters.el>
;;
;; 3. Add the following to your dot-emacs/init file:
;; (require 'rainbow-delimiters)
;;
;; 4. Add hooks for modes where you want it enabled, for example:
;; (add-hook 'clojure-mode-hook 'rainbow-delimiters-mode)
;;
;; - To activate rainbow-delimiters mode temporarily in a buffer:
;; M-x rainbow-delimiters-mode
;;; Customization:
;; To customize various options, including the color scheme:
;; M-x customize-group rainbow-delimiters
;;
;; color-theme.el users:
;; If you use the color-theme package, you can specify custom colors
;; by adding the appropriate faces to your theme.
;; - Faces take the form of:
;; 'rainbow-delimiters-depth-#-face' with # being the depth.
;; Depth begins at 1, the outermost color.
;; Faces exist for depths 1-12.
;; - The unmatched delimiter face is:
;; 'rainbow-delimiters-unmatched-delimiter-face'
;;; Change Log:
;; 1.0 - Initial release.
;; 1.1 - Stop tracking each delimiter's depth independently.
;; This had lead to confusing results when viewing clojure
;; code. Instead, just color based on current nesting inside
;; all delimiters combined.
;; - Added 'all-delimiters' faces to apply a color scheme to
;; all delimiters at once. Other faces inherit from this group.
;; 1.1.1 - Change color scheme to a lighter, more subtle style.
;; 1.1.2: (2011-03-25)
;; - Add an unmatched-delimiter face and correct problem with
;; coloring of text following unmatched closing delims.
;; 1.2: (2011-03-28)
;; - Unify delimiter faces: all delimiter types now use the same depth
;; faces, of form 'rainbow-delimiters-depth-#-face'.
;; 1.2.1: (2011-03-29)
;; - Conform to ELPA conventions.
;;; TODO:
;; - Add support for nested tags (XML, HTML)
;;; Issues:
;; - Rainbow-delimiters mode does not appear to change the color of
;; delimiters when Org-mode is enabled.
;;; Code:
(eval-when-compile (require 'cl))
;;; Customize interface:
(defgroup rainbow-delimiters nil
"Color nested parentheses, brackets, and braces according to their depth."
:prefix "rainbow-delimiters-"
:link '(url-link :tag "Website for rainbow-delimiters (EmacsWiki)"
"http://www.emacswiki.org/emacs/RainbowDelimiters")
:group 'applications)
(defgroup rainbow-delimiters-faces nil
"Faces for each nested depth. Used to color delimiter pairs.
Depths 1-12 are defined. Depth 1 is the outermost delimiter pair."
:group 'rainbow-delimiters
:link '(custom-group-link "rainbow-delimiters")
:prefix 'rainbow-delimiters-faces-)
;;; Faces:
;; Unmatched delimiter face:
(defface rainbow-delimiters-unmatched-face
'((t (:foreground "#88090B")))
"Face to color unmatched closing delimiters with."
:group 'rainbow-delimiters
:group 'rainbow-delimiters-faces)
;; NOTE: The use of repetitious definitions for depth faces is temporary.
;; Once the emacs 24 color theme support comes in, this will be reevaluated.
;; Faces for colorizing delimiters at each level:
(defface rainbow-delimiters-depth-1-face
'((t (:foreground "grey55")))
"Rainbow-delimiters nested delimiter face, depth 1 - the outermost pair."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-2-face
'((t (:foreground "#93a8c6")))
"Rainbow-delimiters nested delimiter face, depth 2."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-3-face
'((t (:foreground "#b0b1a3")))
"Rainbow-delimiters nested delimiter face, depth 3."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-4-face
'((t (:foreground "#97b098")))
"Rainbow-delimiters nested delimiter face, depth 4."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-5-face
'((t (:foreground "#aebed8")))
"Rainbow-delimiters nested delimiter face, depth 5."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-6-face
'((t (:foreground "#b0b0b3")))
"Rainbow-delimiters nested delimiter face, depth 6."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-7-face
'((t (:foreground "#90a890")))
"Rainbow-delimiters nested delimiter face, depth 7."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-8-face
'((t (:foreground "#a2b6da")))
"Rainbow-delimiters nested delimiter face, depth 8."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-9-face
'((t (:foreground "#9cb6ad")))
"Rainbow-delimiters nested delimiter face, depth 9."
:group 'rainbow-delimiters-faces)
;; Emacs doesn't sort face names by number correctly above 1-9; trick it into
;; proper sorting by prepending a _ before the faces with depths over 10.
(defface rainbow-delimiters-depth-_10-face
'((t (:foreground "#83787e")))
"Rainbow-delimiters nested delimiter face, depth 10."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_11-face
'((t (:foreground "#e1ddca")))
"Rainbow-delimiters nested delimiter face, depth 11."
:group 'rainbow-delimiters-faces)
(defface rainbow-delimiters-depth-_12-face
'((t (:foreground "#e0c7c7")))
"Rainbow-delimiters nested delimiter face, depth 12."
:group 'rainbow-delimiters-faces)
;; Variable aliases for faces 10+:
;; We prepend an underline to numbers 10+ to force customize to sort correctly.
;; Here we define aliases without the underline for use everywhere else.
(put 'rainbow-delimiters-depth-10-face
'face-alias
'rainbow-delimiters-depth-_10-face)
(put 'rainbow-delimiters-depth-11-face
'face-alias
'rainbow-delimiters-depth-_11-face)
(put 'rainbow-delimiters-depth-12-face
'face-alias
'rainbow-delimiters-depth-_12-face)
;;; Face utility functions
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-depth-face (depth)
"Return face-name 'rainbow-delimiters-depth-DEPTH-face' as a string.
DEPTH is the number of nested levels deep for the delimiter being colorized.
Returns a face namestring the of form 'rainbow-delimiters-depth-DEPTH-face',
e.g. 'rainbow-delimiters-depth-1-face'."
(concat "rainbow-delimiters-depth-" (number-to-string depth) "-face"))
;;; Nesting level
;; syntax-table: used with parse-partial-sexp for determining current depth.
(defvar rainbow-delimiters-delim-syntax-table
(let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
(modify-syntax-entry ?\( "() " table)
(modify-syntax-entry ?\) ")( " table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
(modify-syntax-entry ?\{ "(}" table)
(modify-syntax-entry ?\} "){" table)
table)
"Syntax table for recognizing all supported delimiter types.")
(defun rainbow-delimiters-depth (point)
"Return # of nested levels of parens, brackets, braces POINT is inside of."
(save-excursion
(beginning-of-defun)
(let ((depth
(with-syntax-table rainbow-delimiters-delim-syntax-table
(car (parse-partial-sexp (point) point)))))
(if (>= depth 0)
depth
0)))) ; ignore negative depths created by unmatched closing parens.
;;; Text properties
;; inlining this function for speed:
;; see: http://www.gnu.org/s/emacs/manual/html_node/elisp/Compilation-Tips.html
;; this will cause problems with debugging. To debug, change defsubst -> defun.
(defsubst rainbow-delimiters-propertize-delimiter (point depth)
"Colorize delimiter at POINT according to DEPTH.
POINT is the point of character to propertize.
DEPTH is the nested delimiter depth at POINT, which determines the face to use.
Sets text properties:
`font-lock-face' to the corresponding delimiter face.
`rear-nonsticky' to prevent color from bleeding into subsequent characters typed by the user."
(with-silent-modifications
(let ((delim-face (if (<= depth 0)
"rainbow-delimiters-unmatched-face"
(rainbow-delimiters-depth-face depth))))
;; (when (eq depth -1) (message "Unmatched delimiter at char %s." point))
(add-text-properties point (1+ point)
`(font-lock-face ,delim-face
rear-nonsticky t)))))
(defun rainbow-delimiters-unpropertize-delimiter (point)
"Remove text properties set by rainbow-delimiters mode from char at POINT."
(remove-text-properties point (1+ point)
'(font-lock-face nil
rear-nonsticky nil)))
(defun rainbow-delimiters-char-ineligible-p (point)
"Return t if char at POINT should be skipped, e.g. if inside a comment.
Returns t if char at point meets one of the following conditions:
- Inside a string.
- Inside a comment.
- Is an escaped char, e.g. ?\)"
(let ((parse-state (save-excursion
(beginning-of-defun)
;; (point) is at beg-of-defun; point is the char location
(parse-partial-sexp (point) point))))
(or
(nth 3 parse-state) ; inside string?
(nth 4 parse-state) ; inside comment?
(and (eq (char-before point) ?\\) ; escaped char, e.g. ?\) - not counted
(and (not (eq (char-before (1- point)) ?\\)) ; special-case: ignore ?\\
(eq (char-before (1- point)) ?\?))))))
;; standard char read syntax '?)' is not tested for because emacs manual states
;; that punctuation such as delimiters should _always_ use escaped '?\)' form.
;;; JIT-Lock functionality
;; Used to skip delimiter-by-delimiter `rainbow-delimiters-propertize-region'.
(defvar rainbow-delimiters-delim-regex "\\(\(\\|\)\\|\\[\\|\\]\\|\{\\|\}\\)"
"Regex matching all opening and closing delimiters we intend to colorize.")
;; main function called by jit-lock:
(defun rainbow-delimiters-propertize-region (start end)
"Colorize delimiters in region between START and END.
Used by jit-lock for dynamic highlighting."
(save-excursion
(goto-char start)
;; START can be anywhere in buffer; begin depth counts from values at START.
(let ((depth (rainbow-delimiters-depth start)))
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
(backward-char) ; re-search-forward places point after delim; go back.
(unless (rainbow-delimiters-char-ineligible-p (point))
(let ((delim (char-after (point))))
(cond ((eq ?\( delim) ; (
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\) delim) ; )
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched paren
(1- depth))))
((eq ?\[ delim) ; [
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\] delim) ; ]
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched bracket
(1- depth))))
((eq ?\{ delim) ; {
(setq depth (1+ depth))
(rainbow-delimiters-propertize-delimiter (point)
depth))
((eq ?\} delim) ; }
(rainbow-delimiters-propertize-delimiter (point)
depth)
(setq depth (or (and (<= depth 0) 0) ; unmatched brace
(1- depth)))))))
;; move past delimiter so re-search-forward doesn't pick it up again
(forward-char)))))
(defun rainbow-delimiters-unpropertize-region (start end)
"Remove mode faces from delimiters in region between START and END."
(save-excursion
(goto-char start)
(while (and (< (point) end)
(re-search-forward rainbow-delimiters-delim-regex end t))
;; re-search-forward places point 1 further than the delim matched:
(rainbow-delimiters-unpropertize-delimiter (1- (point))))))
;;; Minor mode:
;;;###autoload
(define-minor-mode rainbow-delimiters-mode
"Color nested parentheses, brackets, and braces according to their depth."
nil "" nil ; No modeline lighter - it's already obvious when the mode is on.
(if (not rainbow-delimiters-mode)
(progn
(jit-lock-unregister 'rainbow-delimiters-propertize-region)
(rainbow-delimiters-unpropertize-region (point-min) (1- (point-max))))
(jit-lock-register 'rainbow-delimiters-propertize-region t)))
(provide 'rainbow-delimiters)
;;; rainbow-delimiters.el ends here.
|
[
{
"context": "exical-binding: t -*-\n\n;; Copyright (C) 2015-2016 Mark Oteiza <mvoteiza@udel.edu>\n\n;; Author: Mark Oteiza <mvot",
"end": 138,
"score": 0.9998876452445984,
"start": 127,
"tag": "NAME",
"value": "Mark Oteiza"
},
{
"context": ": t -*-\n\n;; Copyright (C) 2015-2016 Mark Oteiza <mvoteiza@udel.edu>\n\n;; Author: Mark Oteiza <mvoteiza@udel.edu>\n\n;; ",
"end": 157,
"score": 0.9999343156814575,
"start": 140,
"tag": "EMAIL",
"value": "mvoteiza@udel.edu"
},
{
"context": "-2016 Mark Oteiza <mvoteiza@udel.edu>\n\n;; Author: Mark Oteiza <mvoteiza@udel.edu>\n\n;; This program is free soft",
"end": 182,
"score": 0.9998843669891357,
"start": 171,
"tag": "NAME",
"value": "Mark Oteiza"
},
{
"context": "eiza <mvoteiza@udel.edu>\n\n;; Author: Mark Oteiza <mvoteiza@udel.edu>\n\n;; This program is free software; you can redis",
"end": 201,
"score": 0.999935507774353,
"start": 184,
"tag": "EMAIL",
"value": "mvoteiza@udel.edu"
}
] | emacs.d/elpa/systemd-20151231.2334/systemd-company.el | robin-liu-1983/emacs-osx-robin.d | 1 | ;;; systemd-company.el --- company backend for systemd unit directives -*- lexical-binding: t -*-
;; Copyright (C) 2015-2016 Mark Oteiza <mvoteiza@udel.edu>
;; Author: Mark Oteiza <mvoteiza@udel.edu>
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(eval-when-compile (require 'cl-lib))
(declare-function company-mode "company")
(declare-function company-begin-backend "company")
(declare-function company-grab-symbol "company")
(defconst systemd-company-unit-sections
'("Unit" "Install" "Service")
"Configuration sections for systemd 225.")
(defconst systemd-company-unit-directives
;; TODO: keep a script of sorts for generating this list. systemd
;; source has a python script in tools/ for parsing the
;; documentation xml for the unit directives.
;;
;; forcer on freenode threw together a curl monstrosity for achieving
;; the same:
;; curl -s http://www.freedesktop.org/software/systemd/man/systemd.directives.html | tr -d '\n' | sed 's/>/>\n/g' | sed -ne '/Unit directives/,/Options on the kernel/p' | sed -ne 's/.*<dt id="\([^-][^"]*\)=">.*/\1/p'
;; Quote, wrap with fill-column at 72, insert into list and indent
'("Accept" "AccuracySec" "After" "Alias" "AllowIsolate" "Also"
"AppArmorProfile" "AssertACPower" "AssertArchitecture"
"AssertCapability" "AssertDirectoryNotEmpty" "AssertFileIsExecutable"
"AssertFileNotEmpty" "AssertFirstBoot" "AssertHost"
"AssertKernelCommandLine" "AssertNeedsUpdate" "AssertPathExists"
"AssertPathExistsGlob" "AssertPathIsDirectory" "AssertPathIsMountPoint"
"AssertPathIsReadWrite" "AssertPathIsSymbolicLink" "AssertSecurity"
"AssertVirtualization" "Backlog" "Before" "BindIPv6Only" "BindToDevice"
"BindsTo" "BlockIOAccounting" "BlockIODeviceWeight"
"BlockIOReadBandwidth" "BlockIOWeight" "BlockIOWriteBandwidth"
"Broadcast" "BusName" "BusPolicy" "CPUAccounting" "CPUAffinity"
"CPUQuota" "CPUSchedulingPolicy" "CPUSchedulingPriority"
"CPUSchedulingResetOnFork" "CPUShares" "Capabilities"
"CapabilityBoundingSet" "ConditionACPower" "ConditionArchitecture"
"ConditionCapability" "ConditionDirectoryNotEmpty"
"ConditionFileIsExecutable" "ConditionFileNotEmpty" "ConditionFirstBoot"
"ConditionHost" "ConditionKernelCommandLine" "ConditionNeedsUpdate"
"ConditionPathExists" "ConditionPathExistsGlob"
"ConditionPathIsDirectory" "ConditionPathIsMountPoint"
"ConditionPathIsReadWrite" "ConditionPathIsSymbolicLink"
"ConditionSecurity" "ConditionVirtualization" "Conflicts"
"DefaultDependencies" "DefaultInstance" "DeferAcceptSec" "Delegate"
"Description" "DeviceAllow" "DevicePolicy" "DirectoryMode"
"DirectoryNotEmpty" "Documentation" "Environment" "EnvironmentFile"
"ExecReload" "ExecStart" "ExecStartPost" "ExecStartPre" "ExecStop"
"ExecStopPost" "ExecStopPre" "FailureAction" "FileDescriptorName"
"FileDescriptorStoreMax" "FreeBind" "Group" "GuessMainPID"
"IOSchedulingClass" "IOSchedulingPriority" "IPTOS" "IPTTL"
"IgnoreOnIsolate" "IgnoreSIGPIPE" "InaccessibleDirectories"
"JobTimeoutAction" "JobTimeoutRebootArgument" "JobTimeoutSec"
"JoinsNamespaceOf" "KeepAlive" "KeepAliveIntervalSec" "KeepAliveProbes"
"KeepAliveTimeSec" "KillMode" "KillSignal" "LimitAS" "LimitCORE"
"LimitCPU" "LimitDATA" "LimitFSIZE" "LimitLOCKS" "LimitMEMLOCK"
"LimitMSGQUEUE" "LimitNICE" "LimitNOFILE" "LimitNPROC" "LimitRSS"
"LimitRTPRIO" "LimitRTTIME" "LimitSIGPENDING" "LimitSTACK"
"ListenDatagram" "ListenFIFO" "ListenMessageQueue" "ListenNetlink"
"ListenSequentialPacket" "ListenSpecial" "ListenStream"
"ListenUSBFunction" "MakeDirectory" "Mark" "MaxConnections"
"MemoryAccounting" "MemoryLimit" "MessageQueueMaxMessages"
"MessageQueueMessageSize" "MountFlags" "NetClass" "Nice" "NoDelay"
"NoNewPrivileges" "NonBlocking" "NotifyAccess" "OOMScoreAdjust"
"OnActiveSec" "OnBootSec" "OnCalendar" "OnFailure" "OnFailureJobMode"
"OnStartupSec" "OnUnitActiveSec" "OnUnitInactiveSec" "Options" "PAMName"
"PIDFile" "PartOf" "PassCredentials" "PassEnvironment" "PassSecurity"
"PathChanged" "PathExists" "PathExistsGlob" "PathModified"
"PermissionsStartOnly" "Persistent" "Personality" "PipeSize" "Priority"
"PrivateDevices" "PrivateNetwork" "PrivateTmp" "PropagatesReloadTo"
"ProtectHome" "ProtectSystem" "RandomSec" "ReadOnlyDirectories"
"ReadWriteDirectories" "RebootArgument" "ReceiveBuffer"
"RefuseManualStart" "RefuseManualStop" "ReloadPropagatedFrom"
"RemainAfterElapse" "RemainAfterExit" "RemoveOnStop" "RequiredBy"
"Requires" "RequiresMountsFor" "Requisite" "Restart"
"RestartForceExitStatus" "RestartPreventExitStatus" "RestartSec"
"RestrictAddressFamilies" "ReusePort" "RootDirectory"
"RootDirectoryStartOnly" "RuntimeDirectory" "RuntimeDirectoryMode"
"SELinuxContext" "SELinuxContextFromNet" "SecureBits" "SendBuffer"
"SendSIGHUP" "SendSIGKILL" "Service" "Slice" "SloppyOptions"
"SmackLabel" "SmackLabelIPIn" "SmackLabelIPOut" "SmackProcessLabel"
"SocketGroup" "SocketMode" "SocketProtocol" "SocketUser" "Sockets"
"SourcePath" "StandardError" "StandardInput" "StandardOutput"
"StartLimitAction" "StartLimitBurst" "StartLimitInterval"
"StartupBlockIOWeight" "StartupCPUShares" "StopWhenUnneeded"
"SuccessExitStatus" "SupplementaryGroups" "Symlinks" "SyslogFacility"
"SyslogIdentifier" "SyslogLevel" "SyslogLevelPrefix"
"SystemCallArchitectures" "SystemCallErrorNumber" "SystemCallFilter"
"TCPCongestion" "TTYPath" "TTYReset" "TTYVHangup" "TTYVTDisallocate"
"TasksAccounting" "TasksMax" "TimeoutIdleSec" "TimeoutSec"
"TimeoutStartSec" "TimeoutStopSec" "TimerSlackNSec" "Transparent" "Type"
"UMask" "USBFunctionDescriptors" "USBFunctionStrings" "Unit" "User"
"UtmpIdentifier" "UtmpMode" "WakeSystem" "WantedBy" "Wants"
"WatchdogSec" "What" "Where" "WorkingDirectory" "Writable")
"Configuration directives for systemd 228.")
(defconst systemd-company-network-sections
'("Match" "Link" "NetDev" "VLAN" "MACVLAN" "MACVTAP" "IPVLAN" "VXLAN"
"Tunnel" "Peer" "Tun" "Tap" "Bond" "Network" "Address" "Route" "DHCP"
"Bridge" "BridgeFDB")
"Network configuration sections for systemd 225.")
(defconst systemd-company-network-directives
;; /Network directives/,/Journal fields/p
'("ARPAllTargets" "ARPIPTargets" "ARPIntervalSec" "ARPProxy" "ARPValidate"
"AdSelect" "Address" "AllSlavesActive" "AllowPortToBeRoot"
"Architecture" "BindCarrier" "BitsPerSecond" "Bond" "Bridge"
"ClientIdentifier" "CopyDSCP" "Cost" "CriticalConnection" "DHCP"
"DHCPServer" "DNS" "DefaultLeaseTimeSec" "Description" "Destination" "DiscoverPathMTU"
"Domains" "DownDelaySec" "Driver" "Duplex" "EmitDNS" "EmitNTP"
"EmitTimezone" "EncapsulationLimit" "FDBAgeingSec" "FailOverMACPolicy"
"FallbackDNS" "FallbackNTP" "FastLeave" "ForwardDelaySec" "Gateway"
"GratuitousARP" "GroupPolicyExtension" "HairPin" "HelloTimeSec" "Host"
"Hostname" "IPForward" "IPMasquerade" "IPv4LLRoute"
"IPv6AcceptRouterAdvertisements" "IPv6DuplicateAddressDetection"
"IPv6FlowLabel" "IPv6HopLimit" "IPv6PrivacyExtensions" "IPv6Token" "Id"
"KernelCommandLine" "Kind" "L2MissNotification" "L3MissNotification"
"LACPTransmitRate" "LLDP" "LLMNR" "Label" "LearnPacketIntervalSec"
"LinkLocalAddressing" "Local" "MACAddress" "MACAddressPolicy" "MACVLAN"
"MIIMonitorSec" "MTUBytes" "MacLearning" "MaxAgeSec" "MaxLeaseTimeSec"
"MaximumFDBEntries" "Metric" "MinLinks" "Mode" "MultiQueue" "NTP" "Name"
"NamePolicy" "OneQueue" "OriginalName" "PacketInfo" "PacketsPerSlave"
"Path" "Peer" "PoolOffset" "PoolSize" "PreferredSource"
"PrimaryReselectPolicy" "Remote" "RequestBroadcast" "ResendIGMP"
"RouteMetric" "RouteShortCircuit" "Scope" "SendHostname" "Source" "TOS"
"TTL" "Timezone" "TransmitHashPolicy" "Tunnel" "UDP6ZeroCheckSumRx"
"UDP6ZeroChecksumTx" "UDPCheckSum" "UnicastFlood" "UpDelaySec" "UseBPDU"
"UseDNS" "UseDomains" "UseHostname" "UseMTU" "UseNTP" "UseRoutes"
"UseTimezone" "VLAN" "VLANId" "VNetHeader" "VXLAN"
"VendorClassIdentifier" "Virtualization" "WakeOnLan")
"Network configuration directives for systemd 228.")
(defun systemd-company--setup (enable)
(when (fboundp 'systemd-company--setup-company)
(systemd-company--setup-company enable)))
(defun systemd-company-section-p ()
"Return t if current line begins with \"[\", otherwise nil."
(save-excursion
(beginning-of-line)
(looking-at "\\[")))
(defun systemd-company-network-p ()
"Return non-nil if `buffer-name' has a network-type extension, otherwise nil."
(string-match "\\.\\(link\\|netdev\\|network\\)\\'" (buffer-name)))
(with-eval-after-load "company"
(defun systemd-company-backend (command &optional arg &rest ignored)
(interactive (list 'interactive))
(cl-case command
(interactive (company-begin-backend 'systemd-company-backend))
(prefix (and (eq major-mode 'systemd-mode)
(company-grab-symbol)))
(candidates
(cl-loop
for comp in (if (systemd-company-network-p)
(if (systemd-company-section-p)
systemd-company-network-sections
systemd-company-network-directives)
(if (systemd-company-section-p)
systemd-company-unit-sections
systemd-company-unit-directives))
if (string-prefix-p arg comp) collect comp))))
(defun systemd-company--setup-company (enable)
(when enable
(add-to-list (make-local-variable 'company-backends) 'systemd-company-backend))
(company-mode (if enable 1 -1))))
(provide 'systemd-company)
;;; systemd-company.el ends here
| 35121 | ;;; systemd-company.el --- company backend for systemd unit directives -*- lexical-binding: t -*-
;; Copyright (C) 2015-2016 <NAME> <<EMAIL>>
;; Author: <NAME> <<EMAIL>>
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(eval-when-compile (require 'cl-lib))
(declare-function company-mode "company")
(declare-function company-begin-backend "company")
(declare-function company-grab-symbol "company")
(defconst systemd-company-unit-sections
'("Unit" "Install" "Service")
"Configuration sections for systemd 225.")
(defconst systemd-company-unit-directives
;; TODO: keep a script of sorts for generating this list. systemd
;; source has a python script in tools/ for parsing the
;; documentation xml for the unit directives.
;;
;; forcer on freenode threw together a curl monstrosity for achieving
;; the same:
;; curl -s http://www.freedesktop.org/software/systemd/man/systemd.directives.html | tr -d '\n' | sed 's/>/>\n/g' | sed -ne '/Unit directives/,/Options on the kernel/p' | sed -ne 's/.*<dt id="\([^-][^"]*\)=">.*/\1/p'
;; Quote, wrap with fill-column at 72, insert into list and indent
'("Accept" "AccuracySec" "After" "Alias" "AllowIsolate" "Also"
"AppArmorProfile" "AssertACPower" "AssertArchitecture"
"AssertCapability" "AssertDirectoryNotEmpty" "AssertFileIsExecutable"
"AssertFileNotEmpty" "AssertFirstBoot" "AssertHost"
"AssertKernelCommandLine" "AssertNeedsUpdate" "AssertPathExists"
"AssertPathExistsGlob" "AssertPathIsDirectory" "AssertPathIsMountPoint"
"AssertPathIsReadWrite" "AssertPathIsSymbolicLink" "AssertSecurity"
"AssertVirtualization" "Backlog" "Before" "BindIPv6Only" "BindToDevice"
"BindsTo" "BlockIOAccounting" "BlockIODeviceWeight"
"BlockIOReadBandwidth" "BlockIOWeight" "BlockIOWriteBandwidth"
"Broadcast" "BusName" "BusPolicy" "CPUAccounting" "CPUAffinity"
"CPUQuota" "CPUSchedulingPolicy" "CPUSchedulingPriority"
"CPUSchedulingResetOnFork" "CPUShares" "Capabilities"
"CapabilityBoundingSet" "ConditionACPower" "ConditionArchitecture"
"ConditionCapability" "ConditionDirectoryNotEmpty"
"ConditionFileIsExecutable" "ConditionFileNotEmpty" "ConditionFirstBoot"
"ConditionHost" "ConditionKernelCommandLine" "ConditionNeedsUpdate"
"ConditionPathExists" "ConditionPathExistsGlob"
"ConditionPathIsDirectory" "ConditionPathIsMountPoint"
"ConditionPathIsReadWrite" "ConditionPathIsSymbolicLink"
"ConditionSecurity" "ConditionVirtualization" "Conflicts"
"DefaultDependencies" "DefaultInstance" "DeferAcceptSec" "Delegate"
"Description" "DeviceAllow" "DevicePolicy" "DirectoryMode"
"DirectoryNotEmpty" "Documentation" "Environment" "EnvironmentFile"
"ExecReload" "ExecStart" "ExecStartPost" "ExecStartPre" "ExecStop"
"ExecStopPost" "ExecStopPre" "FailureAction" "FileDescriptorName"
"FileDescriptorStoreMax" "FreeBind" "Group" "GuessMainPID"
"IOSchedulingClass" "IOSchedulingPriority" "IPTOS" "IPTTL"
"IgnoreOnIsolate" "IgnoreSIGPIPE" "InaccessibleDirectories"
"JobTimeoutAction" "JobTimeoutRebootArgument" "JobTimeoutSec"
"JoinsNamespaceOf" "KeepAlive" "KeepAliveIntervalSec" "KeepAliveProbes"
"KeepAliveTimeSec" "KillMode" "KillSignal" "LimitAS" "LimitCORE"
"LimitCPU" "LimitDATA" "LimitFSIZE" "LimitLOCKS" "LimitMEMLOCK"
"LimitMSGQUEUE" "LimitNICE" "LimitNOFILE" "LimitNPROC" "LimitRSS"
"LimitRTPRIO" "LimitRTTIME" "LimitSIGPENDING" "LimitSTACK"
"ListenDatagram" "ListenFIFO" "ListenMessageQueue" "ListenNetlink"
"ListenSequentialPacket" "ListenSpecial" "ListenStream"
"ListenUSBFunction" "MakeDirectory" "Mark" "MaxConnections"
"MemoryAccounting" "MemoryLimit" "MessageQueueMaxMessages"
"MessageQueueMessageSize" "MountFlags" "NetClass" "Nice" "NoDelay"
"NoNewPrivileges" "NonBlocking" "NotifyAccess" "OOMScoreAdjust"
"OnActiveSec" "OnBootSec" "OnCalendar" "OnFailure" "OnFailureJobMode"
"OnStartupSec" "OnUnitActiveSec" "OnUnitInactiveSec" "Options" "PAMName"
"PIDFile" "PartOf" "PassCredentials" "PassEnvironment" "PassSecurity"
"PathChanged" "PathExists" "PathExistsGlob" "PathModified"
"PermissionsStartOnly" "Persistent" "Personality" "PipeSize" "Priority"
"PrivateDevices" "PrivateNetwork" "PrivateTmp" "PropagatesReloadTo"
"ProtectHome" "ProtectSystem" "RandomSec" "ReadOnlyDirectories"
"ReadWriteDirectories" "RebootArgument" "ReceiveBuffer"
"RefuseManualStart" "RefuseManualStop" "ReloadPropagatedFrom"
"RemainAfterElapse" "RemainAfterExit" "RemoveOnStop" "RequiredBy"
"Requires" "RequiresMountsFor" "Requisite" "Restart"
"RestartForceExitStatus" "RestartPreventExitStatus" "RestartSec"
"RestrictAddressFamilies" "ReusePort" "RootDirectory"
"RootDirectoryStartOnly" "RuntimeDirectory" "RuntimeDirectoryMode"
"SELinuxContext" "SELinuxContextFromNet" "SecureBits" "SendBuffer"
"SendSIGHUP" "SendSIGKILL" "Service" "Slice" "SloppyOptions"
"SmackLabel" "SmackLabelIPIn" "SmackLabelIPOut" "SmackProcessLabel"
"SocketGroup" "SocketMode" "SocketProtocol" "SocketUser" "Sockets"
"SourcePath" "StandardError" "StandardInput" "StandardOutput"
"StartLimitAction" "StartLimitBurst" "StartLimitInterval"
"StartupBlockIOWeight" "StartupCPUShares" "StopWhenUnneeded"
"SuccessExitStatus" "SupplementaryGroups" "Symlinks" "SyslogFacility"
"SyslogIdentifier" "SyslogLevel" "SyslogLevelPrefix"
"SystemCallArchitectures" "SystemCallErrorNumber" "SystemCallFilter"
"TCPCongestion" "TTYPath" "TTYReset" "TTYVHangup" "TTYVTDisallocate"
"TasksAccounting" "TasksMax" "TimeoutIdleSec" "TimeoutSec"
"TimeoutStartSec" "TimeoutStopSec" "TimerSlackNSec" "Transparent" "Type"
"UMask" "USBFunctionDescriptors" "USBFunctionStrings" "Unit" "User"
"UtmpIdentifier" "UtmpMode" "WakeSystem" "WantedBy" "Wants"
"WatchdogSec" "What" "Where" "WorkingDirectory" "Writable")
"Configuration directives for systemd 228.")
(defconst systemd-company-network-sections
'("Match" "Link" "NetDev" "VLAN" "MACVLAN" "MACVTAP" "IPVLAN" "VXLAN"
"Tunnel" "Peer" "Tun" "Tap" "Bond" "Network" "Address" "Route" "DHCP"
"Bridge" "BridgeFDB")
"Network configuration sections for systemd 225.")
(defconst systemd-company-network-directives
;; /Network directives/,/Journal fields/p
'("ARPAllTargets" "ARPIPTargets" "ARPIntervalSec" "ARPProxy" "ARPValidate"
"AdSelect" "Address" "AllSlavesActive" "AllowPortToBeRoot"
"Architecture" "BindCarrier" "BitsPerSecond" "Bond" "Bridge"
"ClientIdentifier" "CopyDSCP" "Cost" "CriticalConnection" "DHCP"
"DHCPServer" "DNS" "DefaultLeaseTimeSec" "Description" "Destination" "DiscoverPathMTU"
"Domains" "DownDelaySec" "Driver" "Duplex" "EmitDNS" "EmitNTP"
"EmitTimezone" "EncapsulationLimit" "FDBAgeingSec" "FailOverMACPolicy"
"FallbackDNS" "FallbackNTP" "FastLeave" "ForwardDelaySec" "Gateway"
"GratuitousARP" "GroupPolicyExtension" "HairPin" "HelloTimeSec" "Host"
"Hostname" "IPForward" "IPMasquerade" "IPv4LLRoute"
"IPv6AcceptRouterAdvertisements" "IPv6DuplicateAddressDetection"
"IPv6FlowLabel" "IPv6HopLimit" "IPv6PrivacyExtensions" "IPv6Token" "Id"
"KernelCommandLine" "Kind" "L2MissNotification" "L3MissNotification"
"LACPTransmitRate" "LLDP" "LLMNR" "Label" "LearnPacketIntervalSec"
"LinkLocalAddressing" "Local" "MACAddress" "MACAddressPolicy" "MACVLAN"
"MIIMonitorSec" "MTUBytes" "MacLearning" "MaxAgeSec" "MaxLeaseTimeSec"
"MaximumFDBEntries" "Metric" "MinLinks" "Mode" "MultiQueue" "NTP" "Name"
"NamePolicy" "OneQueue" "OriginalName" "PacketInfo" "PacketsPerSlave"
"Path" "Peer" "PoolOffset" "PoolSize" "PreferredSource"
"PrimaryReselectPolicy" "Remote" "RequestBroadcast" "ResendIGMP"
"RouteMetric" "RouteShortCircuit" "Scope" "SendHostname" "Source" "TOS"
"TTL" "Timezone" "TransmitHashPolicy" "Tunnel" "UDP6ZeroCheckSumRx"
"UDP6ZeroChecksumTx" "UDPCheckSum" "UnicastFlood" "UpDelaySec" "UseBPDU"
"UseDNS" "UseDomains" "UseHostname" "UseMTU" "UseNTP" "UseRoutes"
"UseTimezone" "VLAN" "VLANId" "VNetHeader" "VXLAN"
"VendorClassIdentifier" "Virtualization" "WakeOnLan")
"Network configuration directives for systemd 228.")
(defun systemd-company--setup (enable)
(when (fboundp 'systemd-company--setup-company)
(systemd-company--setup-company enable)))
(defun systemd-company-section-p ()
"Return t if current line begins with \"[\", otherwise nil."
(save-excursion
(beginning-of-line)
(looking-at "\\[")))
(defun systemd-company-network-p ()
"Return non-nil if `buffer-name' has a network-type extension, otherwise nil."
(string-match "\\.\\(link\\|netdev\\|network\\)\\'" (buffer-name)))
(with-eval-after-load "company"
(defun systemd-company-backend (command &optional arg &rest ignored)
(interactive (list 'interactive))
(cl-case command
(interactive (company-begin-backend 'systemd-company-backend))
(prefix (and (eq major-mode 'systemd-mode)
(company-grab-symbol)))
(candidates
(cl-loop
for comp in (if (systemd-company-network-p)
(if (systemd-company-section-p)
systemd-company-network-sections
systemd-company-network-directives)
(if (systemd-company-section-p)
systemd-company-unit-sections
systemd-company-unit-directives))
if (string-prefix-p arg comp) collect comp))))
(defun systemd-company--setup-company (enable)
(when enable
(add-to-list (make-local-variable 'company-backends) 'systemd-company-backend))
(company-mode (if enable 1 -1))))
(provide 'systemd-company)
;;; systemd-company.el ends here
| true | ;;; systemd-company.el --- company backend for systemd unit directives -*- lexical-binding: t -*-
;; Copyright (C) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
(eval-when-compile (require 'cl-lib))
(declare-function company-mode "company")
(declare-function company-begin-backend "company")
(declare-function company-grab-symbol "company")
(defconst systemd-company-unit-sections
'("Unit" "Install" "Service")
"Configuration sections for systemd 225.")
(defconst systemd-company-unit-directives
;; TODO: keep a script of sorts for generating this list. systemd
;; source has a python script in tools/ for parsing the
;; documentation xml for the unit directives.
;;
;; forcer on freenode threw together a curl monstrosity for achieving
;; the same:
;; curl -s http://www.freedesktop.org/software/systemd/man/systemd.directives.html | tr -d '\n' | sed 's/>/>\n/g' | sed -ne '/Unit directives/,/Options on the kernel/p' | sed -ne 's/.*<dt id="\([^-][^"]*\)=">.*/\1/p'
;; Quote, wrap with fill-column at 72, insert into list and indent
'("Accept" "AccuracySec" "After" "Alias" "AllowIsolate" "Also"
"AppArmorProfile" "AssertACPower" "AssertArchitecture"
"AssertCapability" "AssertDirectoryNotEmpty" "AssertFileIsExecutable"
"AssertFileNotEmpty" "AssertFirstBoot" "AssertHost"
"AssertKernelCommandLine" "AssertNeedsUpdate" "AssertPathExists"
"AssertPathExistsGlob" "AssertPathIsDirectory" "AssertPathIsMountPoint"
"AssertPathIsReadWrite" "AssertPathIsSymbolicLink" "AssertSecurity"
"AssertVirtualization" "Backlog" "Before" "BindIPv6Only" "BindToDevice"
"BindsTo" "BlockIOAccounting" "BlockIODeviceWeight"
"BlockIOReadBandwidth" "BlockIOWeight" "BlockIOWriteBandwidth"
"Broadcast" "BusName" "BusPolicy" "CPUAccounting" "CPUAffinity"
"CPUQuota" "CPUSchedulingPolicy" "CPUSchedulingPriority"
"CPUSchedulingResetOnFork" "CPUShares" "Capabilities"
"CapabilityBoundingSet" "ConditionACPower" "ConditionArchitecture"
"ConditionCapability" "ConditionDirectoryNotEmpty"
"ConditionFileIsExecutable" "ConditionFileNotEmpty" "ConditionFirstBoot"
"ConditionHost" "ConditionKernelCommandLine" "ConditionNeedsUpdate"
"ConditionPathExists" "ConditionPathExistsGlob"
"ConditionPathIsDirectory" "ConditionPathIsMountPoint"
"ConditionPathIsReadWrite" "ConditionPathIsSymbolicLink"
"ConditionSecurity" "ConditionVirtualization" "Conflicts"
"DefaultDependencies" "DefaultInstance" "DeferAcceptSec" "Delegate"
"Description" "DeviceAllow" "DevicePolicy" "DirectoryMode"
"DirectoryNotEmpty" "Documentation" "Environment" "EnvironmentFile"
"ExecReload" "ExecStart" "ExecStartPost" "ExecStartPre" "ExecStop"
"ExecStopPost" "ExecStopPre" "FailureAction" "FileDescriptorName"
"FileDescriptorStoreMax" "FreeBind" "Group" "GuessMainPID"
"IOSchedulingClass" "IOSchedulingPriority" "IPTOS" "IPTTL"
"IgnoreOnIsolate" "IgnoreSIGPIPE" "InaccessibleDirectories"
"JobTimeoutAction" "JobTimeoutRebootArgument" "JobTimeoutSec"
"JoinsNamespaceOf" "KeepAlive" "KeepAliveIntervalSec" "KeepAliveProbes"
"KeepAliveTimeSec" "KillMode" "KillSignal" "LimitAS" "LimitCORE"
"LimitCPU" "LimitDATA" "LimitFSIZE" "LimitLOCKS" "LimitMEMLOCK"
"LimitMSGQUEUE" "LimitNICE" "LimitNOFILE" "LimitNPROC" "LimitRSS"
"LimitRTPRIO" "LimitRTTIME" "LimitSIGPENDING" "LimitSTACK"
"ListenDatagram" "ListenFIFO" "ListenMessageQueue" "ListenNetlink"
"ListenSequentialPacket" "ListenSpecial" "ListenStream"
"ListenUSBFunction" "MakeDirectory" "Mark" "MaxConnections"
"MemoryAccounting" "MemoryLimit" "MessageQueueMaxMessages"
"MessageQueueMessageSize" "MountFlags" "NetClass" "Nice" "NoDelay"
"NoNewPrivileges" "NonBlocking" "NotifyAccess" "OOMScoreAdjust"
"OnActiveSec" "OnBootSec" "OnCalendar" "OnFailure" "OnFailureJobMode"
"OnStartupSec" "OnUnitActiveSec" "OnUnitInactiveSec" "Options" "PAMName"
"PIDFile" "PartOf" "PassCredentials" "PassEnvironment" "PassSecurity"
"PathChanged" "PathExists" "PathExistsGlob" "PathModified"
"PermissionsStartOnly" "Persistent" "Personality" "PipeSize" "Priority"
"PrivateDevices" "PrivateNetwork" "PrivateTmp" "PropagatesReloadTo"
"ProtectHome" "ProtectSystem" "RandomSec" "ReadOnlyDirectories"
"ReadWriteDirectories" "RebootArgument" "ReceiveBuffer"
"RefuseManualStart" "RefuseManualStop" "ReloadPropagatedFrom"
"RemainAfterElapse" "RemainAfterExit" "RemoveOnStop" "RequiredBy"
"Requires" "RequiresMountsFor" "Requisite" "Restart"
"RestartForceExitStatus" "RestartPreventExitStatus" "RestartSec"
"RestrictAddressFamilies" "ReusePort" "RootDirectory"
"RootDirectoryStartOnly" "RuntimeDirectory" "RuntimeDirectoryMode"
"SELinuxContext" "SELinuxContextFromNet" "SecureBits" "SendBuffer"
"SendSIGHUP" "SendSIGKILL" "Service" "Slice" "SloppyOptions"
"SmackLabel" "SmackLabelIPIn" "SmackLabelIPOut" "SmackProcessLabel"
"SocketGroup" "SocketMode" "SocketProtocol" "SocketUser" "Sockets"
"SourcePath" "StandardError" "StandardInput" "StandardOutput"
"StartLimitAction" "StartLimitBurst" "StartLimitInterval"
"StartupBlockIOWeight" "StartupCPUShares" "StopWhenUnneeded"
"SuccessExitStatus" "SupplementaryGroups" "Symlinks" "SyslogFacility"
"SyslogIdentifier" "SyslogLevel" "SyslogLevelPrefix"
"SystemCallArchitectures" "SystemCallErrorNumber" "SystemCallFilter"
"TCPCongestion" "TTYPath" "TTYReset" "TTYVHangup" "TTYVTDisallocate"
"TasksAccounting" "TasksMax" "TimeoutIdleSec" "TimeoutSec"
"TimeoutStartSec" "TimeoutStopSec" "TimerSlackNSec" "Transparent" "Type"
"UMask" "USBFunctionDescriptors" "USBFunctionStrings" "Unit" "User"
"UtmpIdentifier" "UtmpMode" "WakeSystem" "WantedBy" "Wants"
"WatchdogSec" "What" "Where" "WorkingDirectory" "Writable")
"Configuration directives for systemd 228.")
(defconst systemd-company-network-sections
'("Match" "Link" "NetDev" "VLAN" "MACVLAN" "MACVTAP" "IPVLAN" "VXLAN"
"Tunnel" "Peer" "Tun" "Tap" "Bond" "Network" "Address" "Route" "DHCP"
"Bridge" "BridgeFDB")
"Network configuration sections for systemd 225.")
(defconst systemd-company-network-directives
;; /Network directives/,/Journal fields/p
'("ARPAllTargets" "ARPIPTargets" "ARPIntervalSec" "ARPProxy" "ARPValidate"
"AdSelect" "Address" "AllSlavesActive" "AllowPortToBeRoot"
"Architecture" "BindCarrier" "BitsPerSecond" "Bond" "Bridge"
"ClientIdentifier" "CopyDSCP" "Cost" "CriticalConnection" "DHCP"
"DHCPServer" "DNS" "DefaultLeaseTimeSec" "Description" "Destination" "DiscoverPathMTU"
"Domains" "DownDelaySec" "Driver" "Duplex" "EmitDNS" "EmitNTP"
"EmitTimezone" "EncapsulationLimit" "FDBAgeingSec" "FailOverMACPolicy"
"FallbackDNS" "FallbackNTP" "FastLeave" "ForwardDelaySec" "Gateway"
"GratuitousARP" "GroupPolicyExtension" "HairPin" "HelloTimeSec" "Host"
"Hostname" "IPForward" "IPMasquerade" "IPv4LLRoute"
"IPv6AcceptRouterAdvertisements" "IPv6DuplicateAddressDetection"
"IPv6FlowLabel" "IPv6HopLimit" "IPv6PrivacyExtensions" "IPv6Token" "Id"
"KernelCommandLine" "Kind" "L2MissNotification" "L3MissNotification"
"LACPTransmitRate" "LLDP" "LLMNR" "Label" "LearnPacketIntervalSec"
"LinkLocalAddressing" "Local" "MACAddress" "MACAddressPolicy" "MACVLAN"
"MIIMonitorSec" "MTUBytes" "MacLearning" "MaxAgeSec" "MaxLeaseTimeSec"
"MaximumFDBEntries" "Metric" "MinLinks" "Mode" "MultiQueue" "NTP" "Name"
"NamePolicy" "OneQueue" "OriginalName" "PacketInfo" "PacketsPerSlave"
"Path" "Peer" "PoolOffset" "PoolSize" "PreferredSource"
"PrimaryReselectPolicy" "Remote" "RequestBroadcast" "ResendIGMP"
"RouteMetric" "RouteShortCircuit" "Scope" "SendHostname" "Source" "TOS"
"TTL" "Timezone" "TransmitHashPolicy" "Tunnel" "UDP6ZeroCheckSumRx"
"UDP6ZeroChecksumTx" "UDPCheckSum" "UnicastFlood" "UpDelaySec" "UseBPDU"
"UseDNS" "UseDomains" "UseHostname" "UseMTU" "UseNTP" "UseRoutes"
"UseTimezone" "VLAN" "VLANId" "VNetHeader" "VXLAN"
"VendorClassIdentifier" "Virtualization" "WakeOnLan")
"Network configuration directives for systemd 228.")
(defun systemd-company--setup (enable)
(when (fboundp 'systemd-company--setup-company)
(systemd-company--setup-company enable)))
(defun systemd-company-section-p ()
"Return t if current line begins with \"[\", otherwise nil."
(save-excursion
(beginning-of-line)
(looking-at "\\[")))
(defun systemd-company-network-p ()
"Return non-nil if `buffer-name' has a network-type extension, otherwise nil."
(string-match "\\.\\(link\\|netdev\\|network\\)\\'" (buffer-name)))
(with-eval-after-load "company"
(defun systemd-company-backend (command &optional arg &rest ignored)
(interactive (list 'interactive))
(cl-case command
(interactive (company-begin-backend 'systemd-company-backend))
(prefix (and (eq major-mode 'systemd-mode)
(company-grab-symbol)))
(candidates
(cl-loop
for comp in (if (systemd-company-network-p)
(if (systemd-company-section-p)
systemd-company-network-sections
systemd-company-network-directives)
(if (systemd-company-section-p)
systemd-company-unit-sections
systemd-company-unit-directives))
if (string-prefix-p arg comp) collect comp))))
(defun systemd-company--setup-company (enable)
(when enable
(add-to-list (make-local-variable 'company-backends) 'systemd-company-backend))
(company-mode (if enable 1 -1))))
(provide 'systemd-company)
;;; systemd-company.el ends here
|
[
{
"context": "ting logstash configuration\n\n;; Copyright (C) 2014 Wilfred Hughes <me@wilfred.me.uk>\n;;\n;; Author: Wilfred Hughes <",
"end": 108,
"score": 0.9998874068260193,
"start": 94,
"tag": "NAME",
"value": "Wilfred Hughes"
},
{
"context": "figuration\n\n;; Copyright (C) 2014 Wilfred Hughes <me@wilfred.me.uk>\n;;\n;; Author: Wilfred Hughes <me@wilfred.me.uk>\n",
"end": 126,
"score": 0.9999346137046814,
"start": 110,
"tag": "EMAIL",
"value": "me@wilfred.me.uk"
},
{
"context": "14 Wilfred Hughes <me@wilfred.me.uk>\n;;\n;; Author: Wilfred Hughes <me@wilfred.me.uk>\n;; Created: 21 October 2014\n;;",
"end": 156,
"score": 0.9998884201049805,
"start": 142,
"tag": "NAME",
"value": "Wilfred Hughes"
},
{
"context": " <me@wilfred.me.uk>\n;;\n;; Author: Wilfred Hughes <me@wilfred.me.uk>\n;; Created: 21 October 2014\n;; Version: 0.2\n\n;;;",
"end": 174,
"score": 0.9999344348907471,
"start": 158,
"tag": "EMAIL",
"value": "me@wilfred.me.uk"
}
] | files/emacs.d/logstash-conf.el | ant31/ansible-emacs-conf | 0 | ;;; logstash-conf.el --- basic mode for editing logstash configuration
;; Copyright (C) 2014 Wilfred Hughes <me@wilfred.me.uk>
;;
;; Author: Wilfred Hughes <me@wilfred.me.uk>
;; Created: 21 October 2014
;; Version: 0.2
;;; Commentary:
;; `conf-mode' offers adequate highlighting for Logstash configuration
;; files, but does not indent them correctly. This file defines a
;; simple `logstash-conf-mode' that both highlights and indents.
;;; License:
;; This file is not part of GNU Emacs.
;; However, it is distributed under the same license.
;; 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 3, 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.
;;; Code:
(require 'conf-mode)
(eval-when-compile
(require 'cl-lib)) ;; cl-incf, cl-decf
(defgroup logstash nil
"Major mode for editing Logstash configuration files."
:group 'languages)
(defcustom logstash-indent 8
"Indentation offset for `logstash-conf-mode'"
:group 'logstash
:type 'integer)
(defun logstash--get-faces (pos)
"Get all the font faces at POS."
(remq nil
(list
(get-char-property pos 'read-face-name)
(get-char-property pos 'face)
(plist-get (text-properties-at pos) 'face))))
(defvar logstash--open-parens
'(?\{ ?\[))
(defvar logstash--close-parens
'(?\} ?\]))
;; TODO: release these as a reusable package.
(defun logstash--comment-p (pos)
"Return non-nil if POS is inside a comment."
(nth 4 (syntax-ppss pos)))
(defun logstash--string-p (pos)
"Return non-nil if POS is inside a string."
(memq 'font-lock-string-face (logstash--get-faces pos)))
(defun logstash--open-paren-p ()
"Return t if point is currently on an open paren."
(and (looking-at (rx-to-string `(or ,@logstash--open-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--close-paren-p ()
"Return t if point is currently on a close paren."
(and (looking-at (rx-to-string `(or ,@logstash--close-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--open-paren-count ()
"Return the number of open brackets before point."
(let ((open-paren-count 0)
(paren-pattern
(rx-to-string `(or ,@logstash--open-parens ,@logstash--close-parens))))
(save-excursion
(while (search-backward-regexp paren-pattern nil t)
(cond
((logstash--open-paren-p) (cl-incf open-paren-count))
((logstash--close-paren-p) (cl-decf open-paren-count)))))
open-paren-count))
(defun logstash-indent-line ()
(interactive)
(let ((initial-column (current-column))
initial-indentation
correct-indentation-level)
;; Get the current indentation
(back-to-indentation)
(setq initial-indentation (current-column))
;; Remove it.
(while (not (zerop (current-column)))
(delete-char -1))
;; Step over trailing close curlies before counting.
(save-excursion
(while (looking-at "}")
(forward-char 1))
(setq correct-indentation-level (logstash--open-paren-count)))
;; Replace with the correct indentation.
(dotimes (_ (* logstash-indent correct-indentation-level))
(insert " "))
;; Restore point at the same offset on this line.
(let ((point-offset (- initial-column initial-indentation)))
(forward-char point-offset))))
;;;###autoload
(defun logstash-conf-mode ()
(interactive)
;; It's a pain to use `define-derived-mode' with conf-mode, so just
;; call it directly instead.
(conf-unix-mode)
(setq indent-line-function 'logstash-indent-line)
(setq mode-name "Logstash"))
(provide 'logstash-conf)
;;; logstash-conf.el ends here
| 47176 | ;;; logstash-conf.el --- basic mode for editing logstash configuration
;; Copyright (C) 2014 <NAME> <<EMAIL>>
;;
;; Author: <NAME> <<EMAIL>>
;; Created: 21 October 2014
;; Version: 0.2
;;; Commentary:
;; `conf-mode' offers adequate highlighting for Logstash configuration
;; files, but does not indent them correctly. This file defines a
;; simple `logstash-conf-mode' that both highlights and indents.
;;; License:
;; This file is not part of GNU Emacs.
;; However, it is distributed under the same license.
;; 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 3, 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.
;;; Code:
(require 'conf-mode)
(eval-when-compile
(require 'cl-lib)) ;; cl-incf, cl-decf
(defgroup logstash nil
"Major mode for editing Logstash configuration files."
:group 'languages)
(defcustom logstash-indent 8
"Indentation offset for `logstash-conf-mode'"
:group 'logstash
:type 'integer)
(defun logstash--get-faces (pos)
"Get all the font faces at POS."
(remq nil
(list
(get-char-property pos 'read-face-name)
(get-char-property pos 'face)
(plist-get (text-properties-at pos) 'face))))
(defvar logstash--open-parens
'(?\{ ?\[))
(defvar logstash--close-parens
'(?\} ?\]))
;; TODO: release these as a reusable package.
(defun logstash--comment-p (pos)
"Return non-nil if POS is inside a comment."
(nth 4 (syntax-ppss pos)))
(defun logstash--string-p (pos)
"Return non-nil if POS is inside a string."
(memq 'font-lock-string-face (logstash--get-faces pos)))
(defun logstash--open-paren-p ()
"Return t if point is currently on an open paren."
(and (looking-at (rx-to-string `(or ,@logstash--open-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--close-paren-p ()
"Return t if point is currently on a close paren."
(and (looking-at (rx-to-string `(or ,@logstash--close-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--open-paren-count ()
"Return the number of open brackets before point."
(let ((open-paren-count 0)
(paren-pattern
(rx-to-string `(or ,@logstash--open-parens ,@logstash--close-parens))))
(save-excursion
(while (search-backward-regexp paren-pattern nil t)
(cond
((logstash--open-paren-p) (cl-incf open-paren-count))
((logstash--close-paren-p) (cl-decf open-paren-count)))))
open-paren-count))
(defun logstash-indent-line ()
(interactive)
(let ((initial-column (current-column))
initial-indentation
correct-indentation-level)
;; Get the current indentation
(back-to-indentation)
(setq initial-indentation (current-column))
;; Remove it.
(while (not (zerop (current-column)))
(delete-char -1))
;; Step over trailing close curlies before counting.
(save-excursion
(while (looking-at "}")
(forward-char 1))
(setq correct-indentation-level (logstash--open-paren-count)))
;; Replace with the correct indentation.
(dotimes (_ (* logstash-indent correct-indentation-level))
(insert " "))
;; Restore point at the same offset on this line.
(let ((point-offset (- initial-column initial-indentation)))
(forward-char point-offset))))
;;;###autoload
(defun logstash-conf-mode ()
(interactive)
;; It's a pain to use `define-derived-mode' with conf-mode, so just
;; call it directly instead.
(conf-unix-mode)
(setq indent-line-function 'logstash-indent-line)
(setq mode-name "Logstash"))
(provide 'logstash-conf)
;;; logstash-conf.el ends here
| true | ;;; logstash-conf.el --- basic mode for editing logstash configuration
;; Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 21 October 2014
;; Version: 0.2
;;; Commentary:
;; `conf-mode' offers adequate highlighting for Logstash configuration
;; files, but does not indent them correctly. This file defines a
;; simple `logstash-conf-mode' that both highlights and indents.
;;; License:
;; This file is not part of GNU Emacs.
;; However, it is distributed under the same license.
;; 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 3, 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.
;;; Code:
(require 'conf-mode)
(eval-when-compile
(require 'cl-lib)) ;; cl-incf, cl-decf
(defgroup logstash nil
"Major mode for editing Logstash configuration files."
:group 'languages)
(defcustom logstash-indent 8
"Indentation offset for `logstash-conf-mode'"
:group 'logstash
:type 'integer)
(defun logstash--get-faces (pos)
"Get all the font faces at POS."
(remq nil
(list
(get-char-property pos 'read-face-name)
(get-char-property pos 'face)
(plist-get (text-properties-at pos) 'face))))
(defvar logstash--open-parens
'(?\{ ?\[))
(defvar logstash--close-parens
'(?\} ?\]))
;; TODO: release these as a reusable package.
(defun logstash--comment-p (pos)
"Return non-nil if POS is inside a comment."
(nth 4 (syntax-ppss pos)))
(defun logstash--string-p (pos)
"Return non-nil if POS is inside a string."
(memq 'font-lock-string-face (logstash--get-faces pos)))
(defun logstash--open-paren-p ()
"Return t if point is currently on an open paren."
(and (looking-at (rx-to-string `(or ,@logstash--open-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--close-paren-p ()
"Return t if point is currently on a close paren."
(and (looking-at (rx-to-string `(or ,@logstash--close-parens)))
(not (logstash--comment-p (point)))
(not (logstash--string-p (point)))))
(defun logstash--open-paren-count ()
"Return the number of open brackets before point."
(let ((open-paren-count 0)
(paren-pattern
(rx-to-string `(or ,@logstash--open-parens ,@logstash--close-parens))))
(save-excursion
(while (search-backward-regexp paren-pattern nil t)
(cond
((logstash--open-paren-p) (cl-incf open-paren-count))
((logstash--close-paren-p) (cl-decf open-paren-count)))))
open-paren-count))
(defun logstash-indent-line ()
(interactive)
(let ((initial-column (current-column))
initial-indentation
correct-indentation-level)
;; Get the current indentation
(back-to-indentation)
(setq initial-indentation (current-column))
;; Remove it.
(while (not (zerop (current-column)))
(delete-char -1))
;; Step over trailing close curlies before counting.
(save-excursion
(while (looking-at "}")
(forward-char 1))
(setq correct-indentation-level (logstash--open-paren-count)))
;; Replace with the correct indentation.
(dotimes (_ (* logstash-indent correct-indentation-level))
(insert " "))
;; Restore point at the same offset on this line.
(let ((point-offset (- initial-column initial-indentation)))
(forward-char point-offset))))
;;;###autoload
(defun logstash-conf-mode ()
(interactive)
;; It's a pain to use `define-derived-mode' with conf-mode, so just
;; call it directly instead.
(conf-unix-mode)
(setq indent-line-function 'logstash-indent-line)
(setq mode-name "Logstash"))
(provide 'logstash-conf)
;;; logstash-conf.el ends here
|
[
{
"context": "07-2019 Free Software Foundation, Inc.\n\n;; Author: Eric M. Ludlam <zappo@gnu.org>\n\n;; This file is part of GNU Emac",
"end": 168,
"score": 0.9998753070831299,
"start": 154,
"tag": "NAME",
"value": "Eric M. Ludlam"
},
{
"context": "ware Foundation, Inc.\n\n;; Author: Eric M. Ludlam <zappo@gnu.org>\n\n;; This file is part of GNU Emacs.\n\n;; GNU Emac",
"end": 183,
"score": 0.9999285936355591,
"start": 170,
"tag": "EMAIL",
"value": "zappo@gnu.org"
}
] | 2-dev-env-docker/2-tool/files/app/emacs/lisp/cedet/semantic/analyze.el | jiftle/dev-docker | 0 | ;;; semantic/analyze.el --- Analyze semantic tags against local context
;; Copyright (C) 2000-2005, 2007-2019 Free Software Foundation, Inc.
;; Author: Eric M. Ludlam <zappo@gnu.org>
;; 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 3 of the License, 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. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Semantic, as a tool, provides a nice list of searchable tags.
;; That information can provide some very accurate answers if the current
;; context of a position is known.
;;
;; Semantic-ctxt provides ways of analyzing, and manipulating the
;; semantic context of a language in code.
;;
;; This library provides routines for finding intelligent answers to
;; tough problems, such as if an argument to a function has the correct
;; return type, or all possible tags that fit in a given local context.
;;
;;; Vocabulary:
;;
;; Here are some words used to describe different things in the analyzer:
;;
;; tag - A single entity
;; prefix - The beginning of a symbol, usually used to look up something
;; incomplete.
;; type - The name of a datatype in the language.
;; metatype - If a type is named in a declaration like:
;; struct moose somevariable;
;; that name "moose" can be turned into a concrete type.
;; tag sequence - In C code, a list of dereferences, such as:
;; this.that.theother();
;; parent - For a datatype in an OO language, another datatype
;; inherited from. This excludes interfaces.
;; scope - A list of tags that can be dereferenced that cannot
;; be found from the global namespace.
;; scopetypes - A list of tags which are datatype that contain
;; the scope. The scopetypes need to have the scope extracted
;; in a way that honors the type of inheritance.
;; nest/nested - When one tag is contained entirely in another.
;;
;; context - A semantic datatype representing a point in a buffer.
;;
;; constraint - If a context specifies a specific datatype is needed,
;; that is a constraint.
;; constants - Some datatypes define elements of themselves as a
;; constant. These need to be returned as there would be no
;; other possible completions.
(eval-when-compile (require 'cl))
(require 'semantic)
(require 'semantic/format)
(require 'semantic/ctxt)
(require 'semantic/scope)
(require 'semantic/sort)
(require 'semantic/analyze/fcn)
(eval-when-compile (require 'semantic/find))
(declare-function data-debug-new-buffer "data-debug")
(declare-function data-debug-insert-object-slots "eieio-datadebug")
;;; Code:
(defvar semantic-analyze-error-stack nil
"Collection of any errors thrown during analysis.")
(defun semantic-analyze-push-error (err)
"Push the error in ERR-DATA onto the error stack.
Argument ERR."
(push err semantic-analyze-error-stack))
;;; Analysis Classes
;;
;; These classes represent what a context is. Different types
;; of contexts provide differing amounts of information to help
;; provide completions.
;;
(defclass semantic-analyze-context ()
((bounds :initarg :bounds
:type list
:documentation "The bounds of this context.
Usually bound to the dimension of a single symbol or command.")
(prefix :initarg :prefix
:type list
:documentation "List of tags defining local text.
This can be nil, or a list where the last element can be a string
representing text that may be incomplete. Preceding elements
must be semantic tags representing variables or functions
called in a dereference sequence.")
(prefixclass :initarg :prefixclass
:type list
:documentation "Tag classes expected at this context.
These are classes for tags, such as 'function, or 'variable.")
(prefixtypes :initarg :prefixtypes
:type list
:documentation "List of tags defining types for :prefix.
This list is one shorter than :prefix. Each element is a semantic
tag representing a type matching the semantic tag in the same
position in PREFIX.")
(scope :initarg :scope
:type (or null semantic-scope-cache)
:documentation "List of tags available in scopetype.
See `semantic-analyze-scoped-tags' for details.")
(buffer :initarg :buffer
:type buffer
:documentation "The buffer this context is derived from.")
(errors :initarg :errors
:documentation "Any errors thrown and caught during analysis.")
)
"Base analysis data for any context.")
(defclass semantic-analyze-context-assignment (semantic-analyze-context)
((assignee :initarg :assignee
:type list
:documentation "A sequence of tags for an assignee.
This is a variable into which some value is being placed. The last
item in the list is the variable accepting the value. Earlier
tags represent the variables being dereferenced to get to the
assignee."))
"Analysis class for a value in an assignment.")
(defclass semantic-analyze-context-functionarg (semantic-analyze-context)
((function :initarg :function
:type list
:documentation "A sequence of tags for a function.
This is a function being called. The cursor will be in the position
of an argument.
The last tag in :function is the function being called. Earlier
tags represent the variables being dereferenced to get to the
function.")
(index :initarg :index
:type integer
:documentation "The index of the argument for this context.
If a function takes 4 arguments, this value should be bound to
the values 1 through 4.")
(argument :initarg :argument
:type list
:documentation "A sequence of tags for the :index argument.
The argument can accept a value of some type, and this contains the
tag for that definition. It should be a tag, but might
be just a string in some circumstances.")
)
"Analysis class for a value as a function argument.")
(defclass semantic-analyze-context-return (semantic-analyze-context)
() ; No extra data.
"Analysis class for return data.
Return data methods identify the required type by the return value
of the parent function.")
;;; METHODS
;;
;; Simple methods against the context classes.
;;
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context) &optional desired-type)
"Return a type constraint for completing :prefix in CONTEXT.
Optional argument DESIRED-TYPE may be a non-type tag to analyze."
(when (semantic-tag-p desired-type)
;; Convert the desired type if needed.
(if (not (eq (semantic-tag-class desired-type) 'type))
(setq desired-type (semantic-tag-type desired-type)))
;; Protect against plain strings
(cond ((stringp desired-type)
(setq desired-type (list desired-type 'type)))
((and (stringp (car desired-type))
(not (semantic-tag-p desired-type)))
(setq desired-type (list (car desired-type) 'type)))
((semantic-tag-p desired-type)
;; We have a tag of some sort. Yay!
nil)
(t (setq desired-type nil))
)
desired-type))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-functionarg))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (oref context argument))))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-assignment))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (reverse (oref context assignee)))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context))
"Return a tag from CONTEXT that would be most interesting to a user."
(let ((prefix (reverse (oref context :prefix))))
;; Go back through the prefix until we find a tag we can return.
(while (and prefix (not (semantic-tag-p (car prefix))))
(setq prefix (cdr prefix)))
;; Return the found tag, or nil.
(car prefix)))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-functionarg))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :function))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-assignment))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :assignee))))
;;; ANALYSIS
;;
;; Start out with routines that will calculate useful parts of
;; the general analyzer function. These could be used directly
;; by an application that doesn't need to calculate the full
;; context.
(define-overloadable-function semantic-analyze-find-tag-sequence
(sequence &optional scope typereturn throwsym &rest flags)
"Attempt to find all tags in SEQUENCE.
Optional argument LOCALVAR is the list of local variables to use when
finding the details on the first element of SEQUENCE in case
it is not found in the global set of tables.
Optional argument SCOPE are additional terminals to search which are currently
scoped. These are not local variables, but symbols available in a structure
which doesn't need to be dereferenced.
Optional argument TYPERETURN is a symbol in which the types of all found
will be stored. If nil, that data is thrown away.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.")
(defun semantic-analyze-find-tag-sequence-default
;; Note: overloadable fcn uses &rest, but it is a list already, so we don't need
;; to do that in the -default.
(sequence &optional scope typereturn throwsym flags)
"Attempt to find all tags in SEQUENCE.
SCOPE are extra tags which are in scope.
TYPERETURN is a symbol in which to place a list of tag classes that
are found in SEQUENCE.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.
This function knows of flags:
`mustbeclassvariable'"
(let ((s sequence) ; copy of the sequence
(tmp nil) ; tmp find variable
(tag nil) ; tag return list
(tagtype nil) ; tag types return list
(fname nil)
(miniscope (when scope (clone scope)))
(tagclass (if (memq 'mustbeclassvariable flags)
'variable nil))
)
;; First order check. Is this wholly contained in the typecache?
(setq tmp (semanticdb-typecache-find sequence))
(when tmp
(if (or (not tagclass) (semantic-tag-of-class-p tmp tagclass))
;; We are effectively done...
(setq s nil
tag (list tmp))
;; tagclass doesn't match, so fail this.
(setq tmp nil)))
(unless tmp
;; For tag class filtering, only apply the filter if the first entry
;; is also the only entry.
(let ((lftagclass (if (= (length s) 1) tagclass)))
;; For the first entry, it better be a variable, but it might
;; be in the local context too.
;; NOTE: Don't forget c++ namespace foo::bar.
(setq tmp (or
;; Is this tag within our scope. Scopes can sometimes
;; shadow other things, so it goes first.
(and scope (semantic-scope-find (car s) lftagclass scope))
;; Find the tag out there... somewhere, but not in scope
(semantic-analyze-find-tag (car s) lftagclass)
))
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp lftagclass)))
(if (not (semantic-tag-p tmp))
(if throwsym
(throw throwsym "Cannot find definition")
(error "Cannot find definition for \"%s\"" (car s))))
(setq s (cdr s))
(setq tag (cons tmp tag)) ; tag is nil here...
(setq fname (semantic-tag-file-name tmp))
))
;; For the middle entries
(while s
;; Using the tag found in TMP, let's find the tag
;; representing the full typeographic information of its
;; type, and use that to determine the search context for
;; (car s)
(let* ((tmptype
;; In some cases the found TMP is a type,
;; and we can use it directly.
(cond ((semantic-tag-of-class-p tmp 'type)
(or (semantic-analyze-type tmp miniscope)
tmp))
(t
(semantic-analyze-tag-type tmp miniscope))))
(typefile
(when tmptype
(semantic-tag-file-name tmptype)))
(slots nil))
;; Get the children
(setq slots (semantic-analyze-scoped-type-parts tmptype scope))
;; find (car s) in the list o slots
(setq tmp (semantic-find-tags-by-name (car s) slots))
;; If we have lots
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp)))
;; Make sure we have a tag.
(if (not (semantic-tag-p tmp))
(if (cdr s)
;; In the middle, we need to keep seeking our types out.
(error "Cannot find definition for \"%s\"" (car s))
;; Else, it's ok to end with a non-tag
(setq tmp (car s))))
(setq fname (or typefile fname))
(when (and fname (semantic-tag-p tmp)
(not (semantic-tag-in-buffer-p tmp)))
(semantic--tag-put-property tmp :filename fname))
(setq tag (cons tmp tag))
(setq tagtype (cons tmptype tagtype))
(when miniscope
(let ((rawscope
(apply 'append
(mapcar 'semantic-tag-type-members tagtype))))
(oset miniscope fullscope rawscope)))
)
(setq s (cdr s)))
(if typereturn (set typereturn (nreverse tagtype)))
;; Return the mess
(nreverse tag)))
(defun semantic-analyze-find-tag (name &optional tagclass scope)
"Return the first tag found with NAME or nil if not found.
Optional argument TAGCLASS specifies the class of tag to return,
such as 'function or 'variable.
Optional argument SCOPE specifies a scope object which has
additional tags which are in SCOPE and do not need prefixing to
find.
This is a wrapper on top of semanticdb, semanticdb typecache,
semantic-scope, and semantic search functions. Almost all
searches use the same arguments."
(let ((namelst (if (consp name) name ;; test if pre-split.
(semantic-analyze-split-name name))))
(cond
;; If the splitter gives us a list, use the sequence finder
;; to get the list. Since this routine is expected to return
;; only one tag, return the LAST tag found from the sequence
;; which is supposedly the nested reference.
;;
;; Of note, the SEQUENCE function below calls this function
;; (recursively now) so the names that we get from the above
;; fcn better not, in turn, be splittable.
((listp namelst)
;; If we had a split, then this is likely a c++ style namespace::name sequence,
;; so take a short-cut through the typecache.
(or (semanticdb-typecache-find namelst)
;; Ok, not there, try the usual...
(let ((seq (semantic-analyze-find-tag-sequence
namelst scope nil)))
(semantic-analyze-select-best-tag seq tagclass)
)))
;; If NAME is solo, then do our searches for it here.
((stringp namelst)
(let ((retlist (and scope (semantic-scope-find name tagclass scope))))
(if retlist
(semantic-analyze-select-best-tag
retlist tagclass)
(if (eq tagclass 'type)
(semanticdb-typecache-find name)
;; Search in the typecache. First entries in a sequence are
;; often there.
(setq retlist (semanticdb-typecache-find name))
(if (and retlist (or (not tagclass)
(semantic-tag-of-class-p retlist 'tagclass)))
retlist
(semantic-analyze-select-best-tag
(semanticdb-strip-find-results
(semanticdb-find-tags-by-name name)
'name)
tagclass)
)))))
)))
;;; SHORT ANALYSIS
;;
;; Create a mini-analysis of just the symbol under point.
;;
(define-overloadable-function semantic-analyze-current-symbol
(analyzehookfcn &optional position)
"Call ANALYZEHOOKFCN after analyzing the symbol under POSITION.
The ANALYZEHOOKFCN is called with the current symbol bounds, and the
analyzed prefix. It should take the arguments (START END PREFIX).
The ANALYZEHOOKFCN is only called if some sort of prefix with bounds was
found under POSITION.
The results of ANALYZEHOOKFCN is returned, or nil if there was nothing to
call it with.
For regular analysis, you should call `semantic-analyze-current-context'
to calculate the context information. The purpose for this function is
to provide a large number of non-cached analysis for filtering symbols."
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(save-match-data
(save-excursion
(:override)))
)
(defun semantic-analyze-current-symbol-default (analyzehookfcn position)
"Call ANALYZEHOOKFCN on the analyzed symbol at POSITION."
(let* ((semantic-analyze-error-stack nil)
(LLstart (current-time))
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
(scope (semantic-calculate-scope position))
(end nil)
)
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
;; If debug on error is on, allow debugging in this fcn.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable)))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(error (semantic-analyze-push-error err))))
(setq end (current-time))
;;(message "Analysis took %.2f sec" (semantic-elapsed-time LLstart end))
)
(when prefix
(prog1
(funcall analyzehookfcn (car bounds) (cdr bounds) prefix)
;;(setq end (current-time))
;;(message "hookfcn took %.5f sec" (semantic-elapsed-time LLstart end))
)
)))
;;; MAIN ANALYSIS
;;
;; Create a full-up context analysis.
;;
;;;###autoload
(define-overloadable-function semantic-analyze-current-context (&optional position)
"Analyze the current context at optional POSITION.
If called interactively, display interesting information about POSITION
in a separate buffer.
Returns an object based on symbol `semantic-analyze-context'.
This function can be overridden with the symbol `analyze-context'.
When overriding this function, your override will be called while
cursor is at POSITION. In addition, your function will not be called
if a cached copy of the return object is found."
(interactive "d")
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(if (not position) (setq position (point)))
(save-excursion
(goto-char position)
(let* ((answer (semantic-get-cache-data 'current-context)))
(with-syntax-table semantic-lex-syntax-table
(when (not answer)
(setq answer (:override))
(when (and answer (oref answer bounds))
(with-slots (bounds) answer
(semantic-cache-data-to-buffer (current-buffer)
(car bounds)
(cdr bounds)
answer
'current-context
'exit-cache-zone)))
;; Check for interactivity
(when (called-interactively-p 'any)
(if answer
(semantic-analyze-pop-to-context answer)
(message "No Context."))
))
answer))))
(defun semantic-analyze-current-context-default (position)
"Analyze the current context at POSITION.
Returns an object based on symbol `semantic-analyze-context'."
(let* ((semantic-analyze-error-stack nil)
(context-return nil)
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
;; @todo - vv too early to really know this answer! vv
(prefixclass (semantic-ctxt-current-class-list))
(prefixtypes nil)
(scope (semantic-calculate-scope position))
(function nil)
(fntag nil)
arg fntagend argtag
assign asstag newseq
)
;; Pattern for Analysis:
;;
;; Step 1: Calculate DataTypes in Scope:
;;
;; a) Calculate the scope (above)
;;
;; Step 2: Parse context
;;
;; a) Identify function being called, or variable assignment,
;; and find source tags for those references
;; b) Identify the prefix (text cursor is on) and find the source
;; tags for those references.
;;
;; Step 3: Assemble an object
;;
;; Step 2 a:
(setq function (semantic-ctxt-current-function))
(when function
;; Calculate the argument for the function if there is one.
(setq arg (semantic-ctxt-current-argument))
;; Find a tag related to the function name.
(condition-case err
(setq fntag
(semantic-analyze-find-tag-sequence function scope))
(error (semantic-analyze-push-error err)))
;; fntag can have the last entry as just a string, meaning we
;; could not find the core datatype. In this case, the searches
;; below will not work.
(when (stringp (car (last fntag)))
;; Take a wild guess!
(setcar (last fntag) (semantic-tag (car (last fntag)) 'function))
)
(when fntag
(let ((fcn (semantic-find-tags-by-class 'function fntag)))
(when (not fcn)
(let ((ty (semantic-find-tags-by-class 'type fntag)))
(when ty
;; We might have a constructor with the same name as
;; the found datatype.
(setq fcn (semantic-find-tags-by-name
(semantic-tag-name (car ty))
(semantic-tag-type-members (car ty))))
(if fcn
(let ((lp fcn))
(while lp
(when (semantic-tag-get-attribute (car lp)
:constructor)
(setq fcn (cons (car lp) fcn)))
(setq lp (cdr lp))))
;; Give up, go old school
(setq fcn fntag))
)))
(setq fntagend (car (reverse fcn))
argtag
(when (semantic-tag-p fntagend)
(nth (1- arg) (semantic-tag-function-arguments fntagend)))
fntag fcn))))
;; Step 2 b:
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable))
;; If there's an alias, dereference it and analyze
;; sequence again.
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes 'unfindable))))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(progn
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes))))
(error (semantic-analyze-push-error err))))
)
;; Step 3:
(cond
(fntag
;; If we found a tag for our function, we can go into
;; functional context analysis mode, meaning we have a type
;; for the argument.
(setq context-return
(semantic-analyze-context-functionarg
"functionargument"
:buffer (current-buffer)
:function fntag
:index arg
:argument (list argtag)
:scope scope
:prefix prefix
:prefixclass prefixclass
:bounds bounds
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; No function, try assignment
((and (setq assign (semantic-ctxt-current-assignment))
;; We have some sort of an assignment
(condition-case err
(setq asstag (semantic-analyze-find-tag-sequence
assign scope nil nil 'mustbeclassvariable))
(error (semantic-analyze-push-error err)
nil)))
(setq context-return
(semantic-analyze-context-assignment
"assignment"
:buffer (current-buffer)
:assignee asstag
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; TODO: Identify return value condition.
;;((setq return .... what to do?)
;; ...)
(bounds
;; Nothing in particular
(setq context-return
(semantic-analyze-context
"context"
:buffer (current-buffer)
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
(t (setq context-return nil))
)
;; Return our context.
context-return))
(defun semantic-analyze-dereference-alias (taglist)
"Dereference first tag in TAGLIST if it is an alias.
Returns a sequence of names which can then be fed again into
`semantic-analyze-find-tag-sequence'.
Returns nil if no alias was found."
(when (eq (semantic-tag-get-attribute (car taglist) :kind) 'alias)
(let ((tagname
(semantic-analyze-split-name
(semantic-tag-name
(car (semantic-tag-get-attribute (car taglist) :members))))))
(append (if (listp tagname)
tagname
(list tagname))
(cdr taglist)))))
(defun semantic-adebug-analyze (&optional ctxt)
"Perform `semantic-analyze-current-context'.
Display the results as a debug list.
Optional argument CTXT is the context to show."
(interactive)
(require 'data-debug)
(let ((start (current-time))
(ctxt (or ctxt (semantic-analyze-current-context)))
(end (current-time)))
(if (not ctxt)
(message "No Analyzer Results")
(message "Analysis took %.2f seconds."
(semantic-elapsed-time start end))
(semantic-analyze-pulse ctxt)
(if ctxt
(progn
(data-debug-new-buffer "*Analyzer ADEBUG*")
(data-debug-insert-object-slots ctxt "]"))
(message "No Context to analyze here.")))))
;;; DEBUG OUTPUT
;;
;; Friendly output of a context analysis.
;;
(declare-function pulse-momentary-highlight-region "pulse")
(cl-defmethod semantic-analyze-pulse ((context semantic-analyze-context))
"Pulse the region that CONTEXT affects."
(require 'pulse)
(with-current-buffer (oref context :buffer)
(let ((bounds (oref context :bounds)))
(when bounds
(pulse-momentary-highlight-region (car bounds) (cdr bounds))))))
(defcustom semantic-analyze-summary-function 'semantic-format-tag-prototype
"Function to use when creating items in Imenu.
Some useful functions are found in `semantic-format-tag-functions'."
:group 'semantic
:type semantic-format-tag-custom-list)
(defun semantic-analyze-princ-sequence (sequence &optional prefix buff)
"Send the tag SEQUENCE to standard out.
Use PREFIX as a label.
Use BUFF as a source of override methods."
;; If there is no sequence, at least show the field as being empty.
(unless sequence (princ prefix) (princ "<none>\n"))
;; Display the sequence column aligned.
(while sequence
(princ prefix)
(cond
((semantic-tag-p (car sequence))
(princ (funcall semantic-analyze-summary-function
(car sequence))))
((stringp (car sequence))
(princ "\"")
(princ (semantic--format-colorize-text (car sequence) 'variable))
(princ "\""))
(t
(princ (format "'%S" (car sequence)))))
(princ "\n")
(setq sequence (cdr sequence))
(setq prefix (make-string (length prefix) ? ))
))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context prefix) "Prefix: " )
(semantic-analyze-princ-sequence (oref context prefixclass) "Prefix Classes: ")
(semantic-analyze-princ-sequence (oref context prefixtypes) "Prefix Types: ")
(semantic-analyze-princ-sequence (oref context errors) "Encountered Errors: ")
(princ "--------\n")
;(semantic-analyze-princ-sequence (oref context scopetypes) "Scope Types: ")
;(semantic-analyze-princ-sequence (oref context scope) "Scope: ")
;(semantic-analyze-princ-sequence (oref context localvariables) "LocalVars: ")
(when (oref context scope)
(semantic-analyze-show (oref context scope)))
)
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-assignment))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context assignee) "Assignee: ")
(cl-call-next-method))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-functionarg))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context function) "Function: ")
(princ "Argument Index: ")
(princ (oref context index))
(princ "\n")
(semantic-analyze-princ-sequence (oref context argument) "Argument: ")
(cl-call-next-method))
(defun semantic-analyze-pop-to-context (context)
"Display CONTEXT in a temporary buffer.
CONTEXT's content is described in `semantic-analyze-current-context'."
(semantic-analyze-pulse context)
(with-output-to-temp-buffer "*Semantic Context Analysis*"
(princ "Context Type: ")
(princ (eieio-object-name context))
(princ "\n")
(princ "Bounds: ")
(princ (oref context bounds))
(princ "\n")
(semantic-analyze-show context)
)
(shrink-window-if-larger-than-buffer
(get-buffer-window "*Semantic Context Analysis*"))
)
(provide 'semantic/analyze)
;; Local variables:
;; generated-autoload-file: "loaddefs.el"
;; generated-autoload-load-name: "semantic/analyze"
;; End:
;;; semantic/analyze.el ends here
| 24698 | ;;; semantic/analyze.el --- Analyze semantic tags against local context
;; Copyright (C) 2000-2005, 2007-2019 Free Software Foundation, Inc.
;; Author: <NAME> <<EMAIL>>
;; 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 3 of the License, 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. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Semantic, as a tool, provides a nice list of searchable tags.
;; That information can provide some very accurate answers if the current
;; context of a position is known.
;;
;; Semantic-ctxt provides ways of analyzing, and manipulating the
;; semantic context of a language in code.
;;
;; This library provides routines for finding intelligent answers to
;; tough problems, such as if an argument to a function has the correct
;; return type, or all possible tags that fit in a given local context.
;;
;;; Vocabulary:
;;
;; Here are some words used to describe different things in the analyzer:
;;
;; tag - A single entity
;; prefix - The beginning of a symbol, usually used to look up something
;; incomplete.
;; type - The name of a datatype in the language.
;; metatype - If a type is named in a declaration like:
;; struct moose somevariable;
;; that name "moose" can be turned into a concrete type.
;; tag sequence - In C code, a list of dereferences, such as:
;; this.that.theother();
;; parent - For a datatype in an OO language, another datatype
;; inherited from. This excludes interfaces.
;; scope - A list of tags that can be dereferenced that cannot
;; be found from the global namespace.
;; scopetypes - A list of tags which are datatype that contain
;; the scope. The scopetypes need to have the scope extracted
;; in a way that honors the type of inheritance.
;; nest/nested - When one tag is contained entirely in another.
;;
;; context - A semantic datatype representing a point in a buffer.
;;
;; constraint - If a context specifies a specific datatype is needed,
;; that is a constraint.
;; constants - Some datatypes define elements of themselves as a
;; constant. These need to be returned as there would be no
;; other possible completions.
(eval-when-compile (require 'cl))
(require 'semantic)
(require 'semantic/format)
(require 'semantic/ctxt)
(require 'semantic/scope)
(require 'semantic/sort)
(require 'semantic/analyze/fcn)
(eval-when-compile (require 'semantic/find))
(declare-function data-debug-new-buffer "data-debug")
(declare-function data-debug-insert-object-slots "eieio-datadebug")
;;; Code:
(defvar semantic-analyze-error-stack nil
"Collection of any errors thrown during analysis.")
(defun semantic-analyze-push-error (err)
"Push the error in ERR-DATA onto the error stack.
Argument ERR."
(push err semantic-analyze-error-stack))
;;; Analysis Classes
;;
;; These classes represent what a context is. Different types
;; of contexts provide differing amounts of information to help
;; provide completions.
;;
(defclass semantic-analyze-context ()
((bounds :initarg :bounds
:type list
:documentation "The bounds of this context.
Usually bound to the dimension of a single symbol or command.")
(prefix :initarg :prefix
:type list
:documentation "List of tags defining local text.
This can be nil, or a list where the last element can be a string
representing text that may be incomplete. Preceding elements
must be semantic tags representing variables or functions
called in a dereference sequence.")
(prefixclass :initarg :prefixclass
:type list
:documentation "Tag classes expected at this context.
These are classes for tags, such as 'function, or 'variable.")
(prefixtypes :initarg :prefixtypes
:type list
:documentation "List of tags defining types for :prefix.
This list is one shorter than :prefix. Each element is a semantic
tag representing a type matching the semantic tag in the same
position in PREFIX.")
(scope :initarg :scope
:type (or null semantic-scope-cache)
:documentation "List of tags available in scopetype.
See `semantic-analyze-scoped-tags' for details.")
(buffer :initarg :buffer
:type buffer
:documentation "The buffer this context is derived from.")
(errors :initarg :errors
:documentation "Any errors thrown and caught during analysis.")
)
"Base analysis data for any context.")
(defclass semantic-analyze-context-assignment (semantic-analyze-context)
((assignee :initarg :assignee
:type list
:documentation "A sequence of tags for an assignee.
This is a variable into which some value is being placed. The last
item in the list is the variable accepting the value. Earlier
tags represent the variables being dereferenced to get to the
assignee."))
"Analysis class for a value in an assignment.")
(defclass semantic-analyze-context-functionarg (semantic-analyze-context)
((function :initarg :function
:type list
:documentation "A sequence of tags for a function.
This is a function being called. The cursor will be in the position
of an argument.
The last tag in :function is the function being called. Earlier
tags represent the variables being dereferenced to get to the
function.")
(index :initarg :index
:type integer
:documentation "The index of the argument for this context.
If a function takes 4 arguments, this value should be bound to
the values 1 through 4.")
(argument :initarg :argument
:type list
:documentation "A sequence of tags for the :index argument.
The argument can accept a value of some type, and this contains the
tag for that definition. It should be a tag, but might
be just a string in some circumstances.")
)
"Analysis class for a value as a function argument.")
(defclass semantic-analyze-context-return (semantic-analyze-context)
() ; No extra data.
"Analysis class for return data.
Return data methods identify the required type by the return value
of the parent function.")
;;; METHODS
;;
;; Simple methods against the context classes.
;;
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context) &optional desired-type)
"Return a type constraint for completing :prefix in CONTEXT.
Optional argument DESIRED-TYPE may be a non-type tag to analyze."
(when (semantic-tag-p desired-type)
;; Convert the desired type if needed.
(if (not (eq (semantic-tag-class desired-type) 'type))
(setq desired-type (semantic-tag-type desired-type)))
;; Protect against plain strings
(cond ((stringp desired-type)
(setq desired-type (list desired-type 'type)))
((and (stringp (car desired-type))
(not (semantic-tag-p desired-type)))
(setq desired-type (list (car desired-type) 'type)))
((semantic-tag-p desired-type)
;; We have a tag of some sort. Yay!
nil)
(t (setq desired-type nil))
)
desired-type))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-functionarg))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (oref context argument))))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-assignment))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (reverse (oref context assignee)))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context))
"Return a tag from CONTEXT that would be most interesting to a user."
(let ((prefix (reverse (oref context :prefix))))
;; Go back through the prefix until we find a tag we can return.
(while (and prefix (not (semantic-tag-p (car prefix))))
(setq prefix (cdr prefix)))
;; Return the found tag, or nil.
(car prefix)))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-functionarg))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :function))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-assignment))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :assignee))))
;;; ANALYSIS
;;
;; Start out with routines that will calculate useful parts of
;; the general analyzer function. These could be used directly
;; by an application that doesn't need to calculate the full
;; context.
(define-overloadable-function semantic-analyze-find-tag-sequence
(sequence &optional scope typereturn throwsym &rest flags)
"Attempt to find all tags in SEQUENCE.
Optional argument LOCALVAR is the list of local variables to use when
finding the details on the first element of SEQUENCE in case
it is not found in the global set of tables.
Optional argument SCOPE are additional terminals to search which are currently
scoped. These are not local variables, but symbols available in a structure
which doesn't need to be dereferenced.
Optional argument TYPERETURN is a symbol in which the types of all found
will be stored. If nil, that data is thrown away.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.")
(defun semantic-analyze-find-tag-sequence-default
;; Note: overloadable fcn uses &rest, but it is a list already, so we don't need
;; to do that in the -default.
(sequence &optional scope typereturn throwsym flags)
"Attempt to find all tags in SEQUENCE.
SCOPE are extra tags which are in scope.
TYPERETURN is a symbol in which to place a list of tag classes that
are found in SEQUENCE.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.
This function knows of flags:
`mustbeclassvariable'"
(let ((s sequence) ; copy of the sequence
(tmp nil) ; tmp find variable
(tag nil) ; tag return list
(tagtype nil) ; tag types return list
(fname nil)
(miniscope (when scope (clone scope)))
(tagclass (if (memq 'mustbeclassvariable flags)
'variable nil))
)
;; First order check. Is this wholly contained in the typecache?
(setq tmp (semanticdb-typecache-find sequence))
(when tmp
(if (or (not tagclass) (semantic-tag-of-class-p tmp tagclass))
;; We are effectively done...
(setq s nil
tag (list tmp))
;; tagclass doesn't match, so fail this.
(setq tmp nil)))
(unless tmp
;; For tag class filtering, only apply the filter if the first entry
;; is also the only entry.
(let ((lftagclass (if (= (length s) 1) tagclass)))
;; For the first entry, it better be a variable, but it might
;; be in the local context too.
;; NOTE: Don't forget c++ namespace foo::bar.
(setq tmp (or
;; Is this tag within our scope. Scopes can sometimes
;; shadow other things, so it goes first.
(and scope (semantic-scope-find (car s) lftagclass scope))
;; Find the tag out there... somewhere, but not in scope
(semantic-analyze-find-tag (car s) lftagclass)
))
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp lftagclass)))
(if (not (semantic-tag-p tmp))
(if throwsym
(throw throwsym "Cannot find definition")
(error "Cannot find definition for \"%s\"" (car s))))
(setq s (cdr s))
(setq tag (cons tmp tag)) ; tag is nil here...
(setq fname (semantic-tag-file-name tmp))
))
;; For the middle entries
(while s
;; Using the tag found in TMP, let's find the tag
;; representing the full typeographic information of its
;; type, and use that to determine the search context for
;; (car s)
(let* ((tmptype
;; In some cases the found TMP is a type,
;; and we can use it directly.
(cond ((semantic-tag-of-class-p tmp 'type)
(or (semantic-analyze-type tmp miniscope)
tmp))
(t
(semantic-analyze-tag-type tmp miniscope))))
(typefile
(when tmptype
(semantic-tag-file-name tmptype)))
(slots nil))
;; Get the children
(setq slots (semantic-analyze-scoped-type-parts tmptype scope))
;; find (car s) in the list o slots
(setq tmp (semantic-find-tags-by-name (car s) slots))
;; If we have lots
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp)))
;; Make sure we have a tag.
(if (not (semantic-tag-p tmp))
(if (cdr s)
;; In the middle, we need to keep seeking our types out.
(error "Cannot find definition for \"%s\"" (car s))
;; Else, it's ok to end with a non-tag
(setq tmp (car s))))
(setq fname (or typefile fname))
(when (and fname (semantic-tag-p tmp)
(not (semantic-tag-in-buffer-p tmp)))
(semantic--tag-put-property tmp :filename fname))
(setq tag (cons tmp tag))
(setq tagtype (cons tmptype tagtype))
(when miniscope
(let ((rawscope
(apply 'append
(mapcar 'semantic-tag-type-members tagtype))))
(oset miniscope fullscope rawscope)))
)
(setq s (cdr s)))
(if typereturn (set typereturn (nreverse tagtype)))
;; Return the mess
(nreverse tag)))
(defun semantic-analyze-find-tag (name &optional tagclass scope)
"Return the first tag found with NAME or nil if not found.
Optional argument TAGCLASS specifies the class of tag to return,
such as 'function or 'variable.
Optional argument SCOPE specifies a scope object which has
additional tags which are in SCOPE and do not need prefixing to
find.
This is a wrapper on top of semanticdb, semanticdb typecache,
semantic-scope, and semantic search functions. Almost all
searches use the same arguments."
(let ((namelst (if (consp name) name ;; test if pre-split.
(semantic-analyze-split-name name))))
(cond
;; If the splitter gives us a list, use the sequence finder
;; to get the list. Since this routine is expected to return
;; only one tag, return the LAST tag found from the sequence
;; which is supposedly the nested reference.
;;
;; Of note, the SEQUENCE function below calls this function
;; (recursively now) so the names that we get from the above
;; fcn better not, in turn, be splittable.
((listp namelst)
;; If we had a split, then this is likely a c++ style namespace::name sequence,
;; so take a short-cut through the typecache.
(or (semanticdb-typecache-find namelst)
;; Ok, not there, try the usual...
(let ((seq (semantic-analyze-find-tag-sequence
namelst scope nil)))
(semantic-analyze-select-best-tag seq tagclass)
)))
;; If NAME is solo, then do our searches for it here.
((stringp namelst)
(let ((retlist (and scope (semantic-scope-find name tagclass scope))))
(if retlist
(semantic-analyze-select-best-tag
retlist tagclass)
(if (eq tagclass 'type)
(semanticdb-typecache-find name)
;; Search in the typecache. First entries in a sequence are
;; often there.
(setq retlist (semanticdb-typecache-find name))
(if (and retlist (or (not tagclass)
(semantic-tag-of-class-p retlist 'tagclass)))
retlist
(semantic-analyze-select-best-tag
(semanticdb-strip-find-results
(semanticdb-find-tags-by-name name)
'name)
tagclass)
)))))
)))
;;; SHORT ANALYSIS
;;
;; Create a mini-analysis of just the symbol under point.
;;
(define-overloadable-function semantic-analyze-current-symbol
(analyzehookfcn &optional position)
"Call ANALYZEHOOKFCN after analyzing the symbol under POSITION.
The ANALYZEHOOKFCN is called with the current symbol bounds, and the
analyzed prefix. It should take the arguments (START END PREFIX).
The ANALYZEHOOKFCN is only called if some sort of prefix with bounds was
found under POSITION.
The results of ANALYZEHOOKFCN is returned, or nil if there was nothing to
call it with.
For regular analysis, you should call `semantic-analyze-current-context'
to calculate the context information. The purpose for this function is
to provide a large number of non-cached analysis for filtering symbols."
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(save-match-data
(save-excursion
(:override)))
)
(defun semantic-analyze-current-symbol-default (analyzehookfcn position)
"Call ANALYZEHOOKFCN on the analyzed symbol at POSITION."
(let* ((semantic-analyze-error-stack nil)
(LLstart (current-time))
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
(scope (semantic-calculate-scope position))
(end nil)
)
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
;; If debug on error is on, allow debugging in this fcn.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable)))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(error (semantic-analyze-push-error err))))
(setq end (current-time))
;;(message "Analysis took %.2f sec" (semantic-elapsed-time LLstart end))
)
(when prefix
(prog1
(funcall analyzehookfcn (car bounds) (cdr bounds) prefix)
;;(setq end (current-time))
;;(message "hookfcn took %.5f sec" (semantic-elapsed-time LLstart end))
)
)))
;;; MAIN ANALYSIS
;;
;; Create a full-up context analysis.
;;
;;;###autoload
(define-overloadable-function semantic-analyze-current-context (&optional position)
"Analyze the current context at optional POSITION.
If called interactively, display interesting information about POSITION
in a separate buffer.
Returns an object based on symbol `semantic-analyze-context'.
This function can be overridden with the symbol `analyze-context'.
When overriding this function, your override will be called while
cursor is at POSITION. In addition, your function will not be called
if a cached copy of the return object is found."
(interactive "d")
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(if (not position) (setq position (point)))
(save-excursion
(goto-char position)
(let* ((answer (semantic-get-cache-data 'current-context)))
(with-syntax-table semantic-lex-syntax-table
(when (not answer)
(setq answer (:override))
(when (and answer (oref answer bounds))
(with-slots (bounds) answer
(semantic-cache-data-to-buffer (current-buffer)
(car bounds)
(cdr bounds)
answer
'current-context
'exit-cache-zone)))
;; Check for interactivity
(when (called-interactively-p 'any)
(if answer
(semantic-analyze-pop-to-context answer)
(message "No Context."))
))
answer))))
(defun semantic-analyze-current-context-default (position)
"Analyze the current context at POSITION.
Returns an object based on symbol `semantic-analyze-context'."
(let* ((semantic-analyze-error-stack nil)
(context-return nil)
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
;; @todo - vv too early to really know this answer! vv
(prefixclass (semantic-ctxt-current-class-list))
(prefixtypes nil)
(scope (semantic-calculate-scope position))
(function nil)
(fntag nil)
arg fntagend argtag
assign asstag newseq
)
;; Pattern for Analysis:
;;
;; Step 1: Calculate DataTypes in Scope:
;;
;; a) Calculate the scope (above)
;;
;; Step 2: Parse context
;;
;; a) Identify function being called, or variable assignment,
;; and find source tags for those references
;; b) Identify the prefix (text cursor is on) and find the source
;; tags for those references.
;;
;; Step 3: Assemble an object
;;
;; Step 2 a:
(setq function (semantic-ctxt-current-function))
(when function
;; Calculate the argument for the function if there is one.
(setq arg (semantic-ctxt-current-argument))
;; Find a tag related to the function name.
(condition-case err
(setq fntag
(semantic-analyze-find-tag-sequence function scope))
(error (semantic-analyze-push-error err)))
;; fntag can have the last entry as just a string, meaning we
;; could not find the core datatype. In this case, the searches
;; below will not work.
(when (stringp (car (last fntag)))
;; Take a wild guess!
(setcar (last fntag) (semantic-tag (car (last fntag)) 'function))
)
(when fntag
(let ((fcn (semantic-find-tags-by-class 'function fntag)))
(when (not fcn)
(let ((ty (semantic-find-tags-by-class 'type fntag)))
(when ty
;; We might have a constructor with the same name as
;; the found datatype.
(setq fcn (semantic-find-tags-by-name
(semantic-tag-name (car ty))
(semantic-tag-type-members (car ty))))
(if fcn
(let ((lp fcn))
(while lp
(when (semantic-tag-get-attribute (car lp)
:constructor)
(setq fcn (cons (car lp) fcn)))
(setq lp (cdr lp))))
;; Give up, go old school
(setq fcn fntag))
)))
(setq fntagend (car (reverse fcn))
argtag
(when (semantic-tag-p fntagend)
(nth (1- arg) (semantic-tag-function-arguments fntagend)))
fntag fcn))))
;; Step 2 b:
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable))
;; If there's an alias, dereference it and analyze
;; sequence again.
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes 'unfindable))))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(progn
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes))))
(error (semantic-analyze-push-error err))))
)
;; Step 3:
(cond
(fntag
;; If we found a tag for our function, we can go into
;; functional context analysis mode, meaning we have a type
;; for the argument.
(setq context-return
(semantic-analyze-context-functionarg
"functionargument"
:buffer (current-buffer)
:function fntag
:index arg
:argument (list argtag)
:scope scope
:prefix prefix
:prefixclass prefixclass
:bounds bounds
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; No function, try assignment
((and (setq assign (semantic-ctxt-current-assignment))
;; We have some sort of an assignment
(condition-case err
(setq asstag (semantic-analyze-find-tag-sequence
assign scope nil nil 'mustbeclassvariable))
(error (semantic-analyze-push-error err)
nil)))
(setq context-return
(semantic-analyze-context-assignment
"assignment"
:buffer (current-buffer)
:assignee asstag
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; TODO: Identify return value condition.
;;((setq return .... what to do?)
;; ...)
(bounds
;; Nothing in particular
(setq context-return
(semantic-analyze-context
"context"
:buffer (current-buffer)
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
(t (setq context-return nil))
)
;; Return our context.
context-return))
(defun semantic-analyze-dereference-alias (taglist)
"Dereference first tag in TAGLIST if it is an alias.
Returns a sequence of names which can then be fed again into
`semantic-analyze-find-tag-sequence'.
Returns nil if no alias was found."
(when (eq (semantic-tag-get-attribute (car taglist) :kind) 'alias)
(let ((tagname
(semantic-analyze-split-name
(semantic-tag-name
(car (semantic-tag-get-attribute (car taglist) :members))))))
(append (if (listp tagname)
tagname
(list tagname))
(cdr taglist)))))
(defun semantic-adebug-analyze (&optional ctxt)
"Perform `semantic-analyze-current-context'.
Display the results as a debug list.
Optional argument CTXT is the context to show."
(interactive)
(require 'data-debug)
(let ((start (current-time))
(ctxt (or ctxt (semantic-analyze-current-context)))
(end (current-time)))
(if (not ctxt)
(message "No Analyzer Results")
(message "Analysis took %.2f seconds."
(semantic-elapsed-time start end))
(semantic-analyze-pulse ctxt)
(if ctxt
(progn
(data-debug-new-buffer "*Analyzer ADEBUG*")
(data-debug-insert-object-slots ctxt "]"))
(message "No Context to analyze here.")))))
;;; DEBUG OUTPUT
;;
;; Friendly output of a context analysis.
;;
(declare-function pulse-momentary-highlight-region "pulse")
(cl-defmethod semantic-analyze-pulse ((context semantic-analyze-context))
"Pulse the region that CONTEXT affects."
(require 'pulse)
(with-current-buffer (oref context :buffer)
(let ((bounds (oref context :bounds)))
(when bounds
(pulse-momentary-highlight-region (car bounds) (cdr bounds))))))
(defcustom semantic-analyze-summary-function 'semantic-format-tag-prototype
"Function to use when creating items in Imenu.
Some useful functions are found in `semantic-format-tag-functions'."
:group 'semantic
:type semantic-format-tag-custom-list)
(defun semantic-analyze-princ-sequence (sequence &optional prefix buff)
"Send the tag SEQUENCE to standard out.
Use PREFIX as a label.
Use BUFF as a source of override methods."
;; If there is no sequence, at least show the field as being empty.
(unless sequence (princ prefix) (princ "<none>\n"))
;; Display the sequence column aligned.
(while sequence
(princ prefix)
(cond
((semantic-tag-p (car sequence))
(princ (funcall semantic-analyze-summary-function
(car sequence))))
((stringp (car sequence))
(princ "\"")
(princ (semantic--format-colorize-text (car sequence) 'variable))
(princ "\""))
(t
(princ (format "'%S" (car sequence)))))
(princ "\n")
(setq sequence (cdr sequence))
(setq prefix (make-string (length prefix) ? ))
))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context prefix) "Prefix: " )
(semantic-analyze-princ-sequence (oref context prefixclass) "Prefix Classes: ")
(semantic-analyze-princ-sequence (oref context prefixtypes) "Prefix Types: ")
(semantic-analyze-princ-sequence (oref context errors) "Encountered Errors: ")
(princ "--------\n")
;(semantic-analyze-princ-sequence (oref context scopetypes) "Scope Types: ")
;(semantic-analyze-princ-sequence (oref context scope) "Scope: ")
;(semantic-analyze-princ-sequence (oref context localvariables) "LocalVars: ")
(when (oref context scope)
(semantic-analyze-show (oref context scope)))
)
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-assignment))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context assignee) "Assignee: ")
(cl-call-next-method))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-functionarg))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context function) "Function: ")
(princ "Argument Index: ")
(princ (oref context index))
(princ "\n")
(semantic-analyze-princ-sequence (oref context argument) "Argument: ")
(cl-call-next-method))
(defun semantic-analyze-pop-to-context (context)
"Display CONTEXT in a temporary buffer.
CONTEXT's content is described in `semantic-analyze-current-context'."
(semantic-analyze-pulse context)
(with-output-to-temp-buffer "*Semantic Context Analysis*"
(princ "Context Type: ")
(princ (eieio-object-name context))
(princ "\n")
(princ "Bounds: ")
(princ (oref context bounds))
(princ "\n")
(semantic-analyze-show context)
)
(shrink-window-if-larger-than-buffer
(get-buffer-window "*Semantic Context Analysis*"))
)
(provide 'semantic/analyze)
;; Local variables:
;; generated-autoload-file: "loaddefs.el"
;; generated-autoload-load-name: "semantic/analyze"
;; End:
;;; semantic/analyze.el ends here
| true | ;;; semantic/analyze.el --- Analyze semantic tags against local context
;; Copyright (C) 2000-2005, 2007-2019 Free Software Foundation, Inc.
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; 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 3 of the License, 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. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Semantic, as a tool, provides a nice list of searchable tags.
;; That information can provide some very accurate answers if the current
;; context of a position is known.
;;
;; Semantic-ctxt provides ways of analyzing, and manipulating the
;; semantic context of a language in code.
;;
;; This library provides routines for finding intelligent answers to
;; tough problems, such as if an argument to a function has the correct
;; return type, or all possible tags that fit in a given local context.
;;
;;; Vocabulary:
;;
;; Here are some words used to describe different things in the analyzer:
;;
;; tag - A single entity
;; prefix - The beginning of a symbol, usually used to look up something
;; incomplete.
;; type - The name of a datatype in the language.
;; metatype - If a type is named in a declaration like:
;; struct moose somevariable;
;; that name "moose" can be turned into a concrete type.
;; tag sequence - In C code, a list of dereferences, such as:
;; this.that.theother();
;; parent - For a datatype in an OO language, another datatype
;; inherited from. This excludes interfaces.
;; scope - A list of tags that can be dereferenced that cannot
;; be found from the global namespace.
;; scopetypes - A list of tags which are datatype that contain
;; the scope. The scopetypes need to have the scope extracted
;; in a way that honors the type of inheritance.
;; nest/nested - When one tag is contained entirely in another.
;;
;; context - A semantic datatype representing a point in a buffer.
;;
;; constraint - If a context specifies a specific datatype is needed,
;; that is a constraint.
;; constants - Some datatypes define elements of themselves as a
;; constant. These need to be returned as there would be no
;; other possible completions.
(eval-when-compile (require 'cl))
(require 'semantic)
(require 'semantic/format)
(require 'semantic/ctxt)
(require 'semantic/scope)
(require 'semantic/sort)
(require 'semantic/analyze/fcn)
(eval-when-compile (require 'semantic/find))
(declare-function data-debug-new-buffer "data-debug")
(declare-function data-debug-insert-object-slots "eieio-datadebug")
;;; Code:
(defvar semantic-analyze-error-stack nil
"Collection of any errors thrown during analysis.")
(defun semantic-analyze-push-error (err)
"Push the error in ERR-DATA onto the error stack.
Argument ERR."
(push err semantic-analyze-error-stack))
;;; Analysis Classes
;;
;; These classes represent what a context is. Different types
;; of contexts provide differing amounts of information to help
;; provide completions.
;;
(defclass semantic-analyze-context ()
((bounds :initarg :bounds
:type list
:documentation "The bounds of this context.
Usually bound to the dimension of a single symbol or command.")
(prefix :initarg :prefix
:type list
:documentation "List of tags defining local text.
This can be nil, or a list where the last element can be a string
representing text that may be incomplete. Preceding elements
must be semantic tags representing variables or functions
called in a dereference sequence.")
(prefixclass :initarg :prefixclass
:type list
:documentation "Tag classes expected at this context.
These are classes for tags, such as 'function, or 'variable.")
(prefixtypes :initarg :prefixtypes
:type list
:documentation "List of tags defining types for :prefix.
This list is one shorter than :prefix. Each element is a semantic
tag representing a type matching the semantic tag in the same
position in PREFIX.")
(scope :initarg :scope
:type (or null semantic-scope-cache)
:documentation "List of tags available in scopetype.
See `semantic-analyze-scoped-tags' for details.")
(buffer :initarg :buffer
:type buffer
:documentation "The buffer this context is derived from.")
(errors :initarg :errors
:documentation "Any errors thrown and caught during analysis.")
)
"Base analysis data for any context.")
(defclass semantic-analyze-context-assignment (semantic-analyze-context)
((assignee :initarg :assignee
:type list
:documentation "A sequence of tags for an assignee.
This is a variable into which some value is being placed. The last
item in the list is the variable accepting the value. Earlier
tags represent the variables being dereferenced to get to the
assignee."))
"Analysis class for a value in an assignment.")
(defclass semantic-analyze-context-functionarg (semantic-analyze-context)
((function :initarg :function
:type list
:documentation "A sequence of tags for a function.
This is a function being called. The cursor will be in the position
of an argument.
The last tag in :function is the function being called. Earlier
tags represent the variables being dereferenced to get to the
function.")
(index :initarg :index
:type integer
:documentation "The index of the argument for this context.
If a function takes 4 arguments, this value should be bound to
the values 1 through 4.")
(argument :initarg :argument
:type list
:documentation "A sequence of tags for the :index argument.
The argument can accept a value of some type, and this contains the
tag for that definition. It should be a tag, but might
be just a string in some circumstances.")
)
"Analysis class for a value as a function argument.")
(defclass semantic-analyze-context-return (semantic-analyze-context)
() ; No extra data.
"Analysis class for return data.
Return data methods identify the required type by the return value
of the parent function.")
;;; METHODS
;;
;; Simple methods against the context classes.
;;
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context) &optional desired-type)
"Return a type constraint for completing :prefix in CONTEXT.
Optional argument DESIRED-TYPE may be a non-type tag to analyze."
(when (semantic-tag-p desired-type)
;; Convert the desired type if needed.
(if (not (eq (semantic-tag-class desired-type) 'type))
(setq desired-type (semantic-tag-type desired-type)))
;; Protect against plain strings
(cond ((stringp desired-type)
(setq desired-type (list desired-type 'type)))
((and (stringp (car desired-type))
(not (semantic-tag-p desired-type)))
(setq desired-type (list (car desired-type) 'type)))
((semantic-tag-p desired-type)
;; We have a tag of some sort. Yay!
nil)
(t (setq desired-type nil))
)
desired-type))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-functionarg))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (oref context argument))))
(cl-defmethod semantic-analyze-type-constraint
((context semantic-analyze-context-assignment))
"Return a type constraint for completing :prefix in CONTEXT."
(cl-call-next-method context (car (reverse (oref context assignee)))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context))
"Return a tag from CONTEXT that would be most interesting to a user."
(let ((prefix (reverse (oref context :prefix))))
;; Go back through the prefix until we find a tag we can return.
(while (and prefix (not (semantic-tag-p (car prefix))))
(setq prefix (cdr prefix)))
;; Return the found tag, or nil.
(car prefix)))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-functionarg))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :function))))
(cl-defmethod semantic-analyze-interesting-tag
((context semantic-analyze-context-assignment))
"Try the base, and if that fails, return what we are assigning into."
(or (cl-call-next-method) (car-safe (oref context :assignee))))
;;; ANALYSIS
;;
;; Start out with routines that will calculate useful parts of
;; the general analyzer function. These could be used directly
;; by an application that doesn't need to calculate the full
;; context.
(define-overloadable-function semantic-analyze-find-tag-sequence
(sequence &optional scope typereturn throwsym &rest flags)
"Attempt to find all tags in SEQUENCE.
Optional argument LOCALVAR is the list of local variables to use when
finding the details on the first element of SEQUENCE in case
it is not found in the global set of tables.
Optional argument SCOPE are additional terminals to search which are currently
scoped. These are not local variables, but symbols available in a structure
which doesn't need to be dereferenced.
Optional argument TYPERETURN is a symbol in which the types of all found
will be stored. If nil, that data is thrown away.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.")
(defun semantic-analyze-find-tag-sequence-default
;; Note: overloadable fcn uses &rest, but it is a list already, so we don't need
;; to do that in the -default.
(sequence &optional scope typereturn throwsym flags)
"Attempt to find all tags in SEQUENCE.
SCOPE are extra tags which are in scope.
TYPERETURN is a symbol in which to place a list of tag classes that
are found in SEQUENCE.
Optional argument THROWSYM specifies a symbol the throw on non-recoverable error.
Remaining arguments FLAGS are additional flags to apply when searching.
This function knows of flags:
`mustbeclassvariable'"
(let ((s sequence) ; copy of the sequence
(tmp nil) ; tmp find variable
(tag nil) ; tag return list
(tagtype nil) ; tag types return list
(fname nil)
(miniscope (when scope (clone scope)))
(tagclass (if (memq 'mustbeclassvariable flags)
'variable nil))
)
;; First order check. Is this wholly contained in the typecache?
(setq tmp (semanticdb-typecache-find sequence))
(when tmp
(if (or (not tagclass) (semantic-tag-of-class-p tmp tagclass))
;; We are effectively done...
(setq s nil
tag (list tmp))
;; tagclass doesn't match, so fail this.
(setq tmp nil)))
(unless tmp
;; For tag class filtering, only apply the filter if the first entry
;; is also the only entry.
(let ((lftagclass (if (= (length s) 1) tagclass)))
;; For the first entry, it better be a variable, but it might
;; be in the local context too.
;; NOTE: Don't forget c++ namespace foo::bar.
(setq tmp (or
;; Is this tag within our scope. Scopes can sometimes
;; shadow other things, so it goes first.
(and scope (semantic-scope-find (car s) lftagclass scope))
;; Find the tag out there... somewhere, but not in scope
(semantic-analyze-find-tag (car s) lftagclass)
))
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp lftagclass)))
(if (not (semantic-tag-p tmp))
(if throwsym
(throw throwsym "Cannot find definition")
(error "Cannot find definition for \"%s\"" (car s))))
(setq s (cdr s))
(setq tag (cons tmp tag)) ; tag is nil here...
(setq fname (semantic-tag-file-name tmp))
))
;; For the middle entries
(while s
;; Using the tag found in TMP, let's find the tag
;; representing the full typeographic information of its
;; type, and use that to determine the search context for
;; (car s)
(let* ((tmptype
;; In some cases the found TMP is a type,
;; and we can use it directly.
(cond ((semantic-tag-of-class-p tmp 'type)
(or (semantic-analyze-type tmp miniscope)
tmp))
(t
(semantic-analyze-tag-type tmp miniscope))))
(typefile
(when tmptype
(semantic-tag-file-name tmptype)))
(slots nil))
;; Get the children
(setq slots (semantic-analyze-scoped-type-parts tmptype scope))
;; find (car s) in the list o slots
(setq tmp (semantic-find-tags-by-name (car s) slots))
;; If we have lots
(if (and (listp tmp) (semantic-tag-p (car tmp)))
(setq tmp (semantic-analyze-select-best-tag tmp)))
;; Make sure we have a tag.
(if (not (semantic-tag-p tmp))
(if (cdr s)
;; In the middle, we need to keep seeking our types out.
(error "Cannot find definition for \"%s\"" (car s))
;; Else, it's ok to end with a non-tag
(setq tmp (car s))))
(setq fname (or typefile fname))
(when (and fname (semantic-tag-p tmp)
(not (semantic-tag-in-buffer-p tmp)))
(semantic--tag-put-property tmp :filename fname))
(setq tag (cons tmp tag))
(setq tagtype (cons tmptype tagtype))
(when miniscope
(let ((rawscope
(apply 'append
(mapcar 'semantic-tag-type-members tagtype))))
(oset miniscope fullscope rawscope)))
)
(setq s (cdr s)))
(if typereturn (set typereturn (nreverse tagtype)))
;; Return the mess
(nreverse tag)))
(defun semantic-analyze-find-tag (name &optional tagclass scope)
"Return the first tag found with NAME or nil if not found.
Optional argument TAGCLASS specifies the class of tag to return,
such as 'function or 'variable.
Optional argument SCOPE specifies a scope object which has
additional tags which are in SCOPE and do not need prefixing to
find.
This is a wrapper on top of semanticdb, semanticdb typecache,
semantic-scope, and semantic search functions. Almost all
searches use the same arguments."
(let ((namelst (if (consp name) name ;; test if pre-split.
(semantic-analyze-split-name name))))
(cond
;; If the splitter gives us a list, use the sequence finder
;; to get the list. Since this routine is expected to return
;; only one tag, return the LAST tag found from the sequence
;; which is supposedly the nested reference.
;;
;; Of note, the SEQUENCE function below calls this function
;; (recursively now) so the names that we get from the above
;; fcn better not, in turn, be splittable.
((listp namelst)
;; If we had a split, then this is likely a c++ style namespace::name sequence,
;; so take a short-cut through the typecache.
(or (semanticdb-typecache-find namelst)
;; Ok, not there, try the usual...
(let ((seq (semantic-analyze-find-tag-sequence
namelst scope nil)))
(semantic-analyze-select-best-tag seq tagclass)
)))
;; If NAME is solo, then do our searches for it here.
((stringp namelst)
(let ((retlist (and scope (semantic-scope-find name tagclass scope))))
(if retlist
(semantic-analyze-select-best-tag
retlist tagclass)
(if (eq tagclass 'type)
(semanticdb-typecache-find name)
;; Search in the typecache. First entries in a sequence are
;; often there.
(setq retlist (semanticdb-typecache-find name))
(if (and retlist (or (not tagclass)
(semantic-tag-of-class-p retlist 'tagclass)))
retlist
(semantic-analyze-select-best-tag
(semanticdb-strip-find-results
(semanticdb-find-tags-by-name name)
'name)
tagclass)
)))))
)))
;;; SHORT ANALYSIS
;;
;; Create a mini-analysis of just the symbol under point.
;;
(define-overloadable-function semantic-analyze-current-symbol
(analyzehookfcn &optional position)
"Call ANALYZEHOOKFCN after analyzing the symbol under POSITION.
The ANALYZEHOOKFCN is called with the current symbol bounds, and the
analyzed prefix. It should take the arguments (START END PREFIX).
The ANALYZEHOOKFCN is only called if some sort of prefix with bounds was
found under POSITION.
The results of ANALYZEHOOKFCN is returned, or nil if there was nothing to
call it with.
For regular analysis, you should call `semantic-analyze-current-context'
to calculate the context information. The purpose for this function is
to provide a large number of non-cached analysis for filtering symbols."
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(save-match-data
(save-excursion
(:override)))
)
(defun semantic-analyze-current-symbol-default (analyzehookfcn position)
"Call ANALYZEHOOKFCN on the analyzed symbol at POSITION."
(let* ((semantic-analyze-error-stack nil)
(LLstart (current-time))
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
(scope (semantic-calculate-scope position))
(end nil)
)
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
;; If debug on error is on, allow debugging in this fcn.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable)))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(error (semantic-analyze-push-error err))))
(setq end (current-time))
;;(message "Analysis took %.2f sec" (semantic-elapsed-time LLstart end))
)
(when prefix
(prog1
(funcall analyzehookfcn (car bounds) (cdr bounds) prefix)
;;(setq end (current-time))
;;(message "hookfcn took %.5f sec" (semantic-elapsed-time LLstart end))
)
)))
;;; MAIN ANALYSIS
;;
;; Create a full-up context analysis.
;;
;;;###autoload
(define-overloadable-function semantic-analyze-current-context (&optional position)
"Analyze the current context at optional POSITION.
If called interactively, display interesting information about POSITION
in a separate buffer.
Returns an object based on symbol `semantic-analyze-context'.
This function can be overridden with the symbol `analyze-context'.
When overriding this function, your override will be called while
cursor is at POSITION. In addition, your function will not be called
if a cached copy of the return object is found."
(interactive "d")
;; Only do this in a Semantic enabled buffer.
(when (not (semantic-active-p))
(error "Cannot analyze buffers not supported by Semantic"))
;; Always refresh out tags in a safe way before doing the
;; context.
(semantic-refresh-tags-safe)
;; Do the rest of the analysis.
(if (not position) (setq position (point)))
(save-excursion
(goto-char position)
(let* ((answer (semantic-get-cache-data 'current-context)))
(with-syntax-table semantic-lex-syntax-table
(when (not answer)
(setq answer (:override))
(when (and answer (oref answer bounds))
(with-slots (bounds) answer
(semantic-cache-data-to-buffer (current-buffer)
(car bounds)
(cdr bounds)
answer
'current-context
'exit-cache-zone)))
;; Check for interactivity
(when (called-interactively-p 'any)
(if answer
(semantic-analyze-pop-to-context answer)
(message "No Context."))
))
answer))))
(defun semantic-analyze-current-context-default (position)
"Analyze the current context at POSITION.
Returns an object based on symbol `semantic-analyze-context'."
(let* ((semantic-analyze-error-stack nil)
(context-return nil)
(prefixandbounds (semantic-ctxt-current-symbol-and-bounds (or position (point))))
(prefix (car prefixandbounds))
(bounds (nth 2 prefixandbounds))
;; @todo - vv too early to really know this answer! vv
(prefixclass (semantic-ctxt-current-class-list))
(prefixtypes nil)
(scope (semantic-calculate-scope position))
(function nil)
(fntag nil)
arg fntagend argtag
assign asstag newseq
)
;; Pattern for Analysis:
;;
;; Step 1: Calculate DataTypes in Scope:
;;
;; a) Calculate the scope (above)
;;
;; Step 2: Parse context
;;
;; a) Identify function being called, or variable assignment,
;; and find source tags for those references
;; b) Identify the prefix (text cursor is on) and find the source
;; tags for those references.
;;
;; Step 3: Assemble an object
;;
;; Step 2 a:
(setq function (semantic-ctxt-current-function))
(when function
;; Calculate the argument for the function if there is one.
(setq arg (semantic-ctxt-current-argument))
;; Find a tag related to the function name.
(condition-case err
(setq fntag
(semantic-analyze-find-tag-sequence function scope))
(error (semantic-analyze-push-error err)))
;; fntag can have the last entry as just a string, meaning we
;; could not find the core datatype. In this case, the searches
;; below will not work.
(when (stringp (car (last fntag)))
;; Take a wild guess!
(setcar (last fntag) (semantic-tag (car (last fntag)) 'function))
)
(when fntag
(let ((fcn (semantic-find-tags-by-class 'function fntag)))
(when (not fcn)
(let ((ty (semantic-find-tags-by-class 'type fntag)))
(when ty
;; We might have a constructor with the same name as
;; the found datatype.
(setq fcn (semantic-find-tags-by-name
(semantic-tag-name (car ty))
(semantic-tag-type-members (car ty))))
(if fcn
(let ((lp fcn))
(while lp
(when (semantic-tag-get-attribute (car lp)
:constructor)
(setq fcn (cons (car lp) fcn)))
(setq lp (cdr lp))))
;; Give up, go old school
(setq fcn fntag))
)))
(setq fntagend (car (reverse fcn))
argtag
(when (semantic-tag-p fntagend)
(nth (1- arg) (semantic-tag-function-arguments fntagend)))
fntag fcn))))
;; Step 2 b:
;; Only do work if we have bounds (meaning a prefix to complete)
(when bounds
(if debug-on-error
(catch 'unfindable
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes 'unfindable))
;; If there's an alias, dereference it and analyze
;; sequence again.
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes 'unfindable))))
;; Debug on error is off. Capture errors and move on
(condition-case err
;; NOTE: This line is duplicated in
;; semantic-analyzer-debug-global-symbol
;; You will need to update both places.
(progn
(setq prefix (semantic-analyze-find-tag-sequence
prefix scope 'prefixtypes))
(when (setq newseq
(semantic-analyze-dereference-alias prefix))
(setq prefix (semantic-analyze-find-tag-sequence
newseq scope 'prefixtypes))))
(error (semantic-analyze-push-error err))))
)
;; Step 3:
(cond
(fntag
;; If we found a tag for our function, we can go into
;; functional context analysis mode, meaning we have a type
;; for the argument.
(setq context-return
(semantic-analyze-context-functionarg
"functionargument"
:buffer (current-buffer)
:function fntag
:index arg
:argument (list argtag)
:scope scope
:prefix prefix
:prefixclass prefixclass
:bounds bounds
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; No function, try assignment
((and (setq assign (semantic-ctxt-current-assignment))
;; We have some sort of an assignment
(condition-case err
(setq asstag (semantic-analyze-find-tag-sequence
assign scope nil nil 'mustbeclassvariable))
(error (semantic-analyze-push-error err)
nil)))
(setq context-return
(semantic-analyze-context-assignment
"assignment"
:buffer (current-buffer)
:assignee asstag
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
;; TODO: Identify return value condition.
;;((setq return .... what to do?)
;; ...)
(bounds
;; Nothing in particular
(setq context-return
(semantic-analyze-context
"context"
:buffer (current-buffer)
:scope scope
:bounds bounds
:prefix prefix
:prefixclass prefixclass
:prefixtypes prefixtypes
:errors semantic-analyze-error-stack)))
(t (setq context-return nil))
)
;; Return our context.
context-return))
(defun semantic-analyze-dereference-alias (taglist)
"Dereference first tag in TAGLIST if it is an alias.
Returns a sequence of names which can then be fed again into
`semantic-analyze-find-tag-sequence'.
Returns nil if no alias was found."
(when (eq (semantic-tag-get-attribute (car taglist) :kind) 'alias)
(let ((tagname
(semantic-analyze-split-name
(semantic-tag-name
(car (semantic-tag-get-attribute (car taglist) :members))))))
(append (if (listp tagname)
tagname
(list tagname))
(cdr taglist)))))
(defun semantic-adebug-analyze (&optional ctxt)
"Perform `semantic-analyze-current-context'.
Display the results as a debug list.
Optional argument CTXT is the context to show."
(interactive)
(require 'data-debug)
(let ((start (current-time))
(ctxt (or ctxt (semantic-analyze-current-context)))
(end (current-time)))
(if (not ctxt)
(message "No Analyzer Results")
(message "Analysis took %.2f seconds."
(semantic-elapsed-time start end))
(semantic-analyze-pulse ctxt)
(if ctxt
(progn
(data-debug-new-buffer "*Analyzer ADEBUG*")
(data-debug-insert-object-slots ctxt "]"))
(message "No Context to analyze here.")))))
;;; DEBUG OUTPUT
;;
;; Friendly output of a context analysis.
;;
(declare-function pulse-momentary-highlight-region "pulse")
(cl-defmethod semantic-analyze-pulse ((context semantic-analyze-context))
"Pulse the region that CONTEXT affects."
(require 'pulse)
(with-current-buffer (oref context :buffer)
(let ((bounds (oref context :bounds)))
(when bounds
(pulse-momentary-highlight-region (car bounds) (cdr bounds))))))
(defcustom semantic-analyze-summary-function 'semantic-format-tag-prototype
"Function to use when creating items in Imenu.
Some useful functions are found in `semantic-format-tag-functions'."
:group 'semantic
:type semantic-format-tag-custom-list)
(defun semantic-analyze-princ-sequence (sequence &optional prefix buff)
"Send the tag SEQUENCE to standard out.
Use PREFIX as a label.
Use BUFF as a source of override methods."
;; If there is no sequence, at least show the field as being empty.
(unless sequence (princ prefix) (princ "<none>\n"))
;; Display the sequence column aligned.
(while sequence
(princ prefix)
(cond
((semantic-tag-p (car sequence))
(princ (funcall semantic-analyze-summary-function
(car sequence))))
((stringp (car sequence))
(princ "\"")
(princ (semantic--format-colorize-text (car sequence) 'variable))
(princ "\""))
(t
(princ (format "'%S" (car sequence)))))
(princ "\n")
(setq sequence (cdr sequence))
(setq prefix (make-string (length prefix) ? ))
))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context prefix) "Prefix: " )
(semantic-analyze-princ-sequence (oref context prefixclass) "Prefix Classes: ")
(semantic-analyze-princ-sequence (oref context prefixtypes) "Prefix Types: ")
(semantic-analyze-princ-sequence (oref context errors) "Encountered Errors: ")
(princ "--------\n")
;(semantic-analyze-princ-sequence (oref context scopetypes) "Scope Types: ")
;(semantic-analyze-princ-sequence (oref context scope) "Scope: ")
;(semantic-analyze-princ-sequence (oref context localvariables) "LocalVars: ")
(when (oref context scope)
(semantic-analyze-show (oref context scope)))
)
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-assignment))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context assignee) "Assignee: ")
(cl-call-next-method))
(cl-defmethod semantic-analyze-show ((context semantic-analyze-context-functionarg))
"Insert CONTEXT into the current buffer in a nice way."
(semantic-analyze-princ-sequence (oref context function) "Function: ")
(princ "Argument Index: ")
(princ (oref context index))
(princ "\n")
(semantic-analyze-princ-sequence (oref context argument) "Argument: ")
(cl-call-next-method))
(defun semantic-analyze-pop-to-context (context)
"Display CONTEXT in a temporary buffer.
CONTEXT's content is described in `semantic-analyze-current-context'."
(semantic-analyze-pulse context)
(with-output-to-temp-buffer "*Semantic Context Analysis*"
(princ "Context Type: ")
(princ (eieio-object-name context))
(princ "\n")
(princ "Bounds: ")
(princ (oref context bounds))
(princ "\n")
(semantic-analyze-show context)
)
(shrink-window-if-larger-than-buffer
(get-buffer-window "*Semantic Context Analysis*"))
)
(provide 'semantic/analyze)
;; Local variables:
;; generated-autoload-file: "loaddefs.el"
;; generated-autoload-load-name: "semantic/analyze"
;; End:
;;; semantic/analyze.el ends here
|
[
{
"context": " --- Helm Incremental Grep.\n\n;; Copyright (C) 2012 Thierry Volpiatto <thierry.volpiatto@gmail.com>\n\n;; This program is",
"end": 84,
"score": 0.9998903274536133,
"start": 67,
"tag": "NAME",
"value": "Thierry Volpiatto"
},
{
"context": "l Grep.\n\n;; Copyright (C) 2012 Thierry Volpiatto <thierry.volpiatto@gmail.com>\n\n;; This program is free software; you can redis",
"end": 113,
"score": 0.9999315142631531,
"start": 86,
"tag": "EMAIL",
"value": "thierry.volpiatto@gmail.com"
}
] | emacs/emacs-config/helm/helm-grep.el | cyborginstitute/stack | 3 | ;;; helm-grep.el --- Helm Incremental Grep.
;; Copyright (C) 2012 Thierry Volpiatto <thierry.volpiatto@gmail.com>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(eval-when-compile (require 'cl))
(require 'helm)
(require 'grep)
(require 'helm-files)
(require 'helm-regexp)
(declare-function helm-elscreen-find-file "helm-elscreen" (file))
(defgroup helm-grep nil
"Grep related Applications and libraries for Helm."
:group 'helm)
(defcustom helm-c-grep-use-ioccur-style-keys t
"Use Arrow keys to jump to occurences."
:group 'helm-grep
:type 'boolean)
(defcustom helm-c-pdfgrep-default-read-command "xpdf '%f' %p"
"Default command to read pdf files from pdfgrep.
Where '%f' format spec is filename and '%p' is page number"
:group 'helm-grep
:type 'string)
(defcustom helm-c-grep-max-length-history 100
"Max number of elements to save in `helm-c-grep-history'."
:group 'helm-grep
:type 'integer)
;;; Faces
;;
;;
(defface helm-grep-match
'((t (:inherit match)))
"Face used to highlight grep matches."
:group 'helm-grep)
(defface helm-grep-file
'((t (:foreground "BlueViolet" :underline t)))
"Face used to highlight grep results filenames."
:group 'helm-grep)
(defface helm-grep-lineno
'((t (:foreground "Darkorange1")))
"Face used to highlight grep number lines."
:group 'helm-grep)
(defface helm-grep-running
'((t (:foreground "Red")))
"Face used in mode line when grep is running."
:group 'helm-grep)
(defface helm-grep-finish
'((t (:foreground "Green")))
"Face used in mode line when grep is finish."
:group 'helm-grep)
(defvar helm-c-grep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-c o") 'helm-c-grep-run-other-window-action)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-x C-s") 'helm-c-grep-run-save-buffer)
(when helm-c-grep-use-ioccur-style-keys
(define-key map (kbd "<right>") 'helm-c-grep-run-persistent-action)
(define-key map (kbd "<left>") 'helm-c-grep-run-default-action))
(define-key map (kbd "C-c ?") 'helm-grep-help)
(delq nil map))
"Keymap used in Grep sources.")
(defvar helm-c-pdfgrep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-c ?") 'helm-pdfgrep-help)
map)
"Keymap used in pdfgrep.")
(defvar helm-c-grep-default-command
"grep -d skip %e -niH -e %p %f"
"Default grep format command for `helm-do-grep-1'.
Where:
'%e' format spec is for --exclude or --include grep options.
'%p' format spec is for pattern.
'%f' format spec is for filenames.")
(defvar helm-c-grep-default-recurse-command
"grep -d recurse %e -niH -e %p %f"
"Default recursive grep format command for `helm-do-grep-1'.
See `helm-c-grep-default-command' for format specs.")
(defvar helm-c-default-zgrep-command "zgrep -niH -e %p %f")
(defvar helm-c-rzgrep-cache (make-hash-table :test 'equal))
(defvar helm-c-grep-default-function 'helm-c-grep-init)
(defvar helm-c-grep-debug-command-line nil
"Turn on helm grep command-line debugging when non--nil.")
(defvar helm-c-zgrep-recurse-flag nil)
(defvar helm-c-grep-history nil)
(defun helm-c-grep-prepare-candidates (candidates)
"Prepare filenames and directories CANDIDATES for grep command line."
;; If one or more candidate is a directory, search in all files
;; of this candidate (e.g /home/user/directory/*).
;; If r option is enabled search also in subdidrectories.
;; We need here to expand wildcards to support crap windows filenames
;; as grep doesn't accept quoted wildcards (e.g "dir/*.el").
(if helm-c-zgrep-recurse-flag
(mapconcat 'shell-quote-argument candidates " ")
(loop for i in candidates append
(cond ( ;; Candidate is a directory and we use recursion.
(and (file-directory-p i)
(helm-c-grep-recurse-p))
(list (expand-file-name i)))
;; Candidate is a directory, search in all files.
((file-directory-p i)
(file-expand-wildcards
(concat (file-name-as-directory (expand-file-name i)) "*") t))
;; Candidate is a file or wildcard and we use recursion, use the
;; current directory instead of candidate.
((and (or (file-exists-p i) (string-match "\*" i))
(helm-c-grep-recurse-p))
(list (expand-file-name
(directory-file-name ; Needed for windoze.
(file-name-directory (directory-file-name i))))))
;; Candidate use wildcard.
((string-match "^\*" (helm-c-basename i))
(file-expand-wildcards i t))
;; Else should be one or more file.
(t (list i))) into all-files
finally return
(mapconcat 'shell-quote-argument all-files " "))))
(defun helm-c-grep-recurse-p ()
"Check if `helm-do-grep-1' have switched to recursive."
(let ((args (replace-regexp-in-string
"grep" "" helm-c-grep-default-command)))
(string-match-p "r\\|recurse" args)))
(defun helm-c-grep-init (only-files &optional include zgrep)
"Start an asynchronous grep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(ignored-files (mapconcat
#'(lambda (x)
(concat "--exclude=" (shell-quote-argument x)))
grep-find-ignored-files " "))
(ignored-dirs (mapconcat
;; Need grep version >=2.5.4 of Gnuwin32 on windoze.
#'(lambda (x)
(concat "--exclude-dir=" (shell-quote-argument x)))
grep-find-ignored-directories " "))
(exclude (if (helm-c-grep-recurse-p)
(concat (or include ignored-files) " " ignored-dirs)
ignored-files))
(cmd-line (format-spec
helm-c-grep-default-command
(delq nil
(list (unless zgrep (cons ?e exclude))
(cons ?p (shell-quote-argument helm-pattern))
(cons ?f fnargs))))))
(when helm-c-grep-debug-command-line
(with-current-buffer (get-buffer-create "*any grep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (when (get-process "grep-process")
(propertize "[Grep Process Running] "
'face 'helm-grep-running)))))
(force-mode-line-update nil)
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "grep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "grep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line)
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize
(format "[Grep Process Finished - (%s results)] "
(let ((nlines (1- (count-lines
(point-min)
(point-max)))))
(if (> nlines 0) nlines 0)))
'face 'helm-grep-finish))))
(force-mode-line-update nil))))))))
(defun helm-c-grep-action (candidate &optional where mark)
"Define a default action for `helm-do-grep' on CANDIDATE.
WHERE can be one of other-window, elscreen, other-frame."
(let* ((split (helm-c-grep-split-line candidate))
(lineno (string-to-number (nth 1 split)))
(loc-fname (car split))
(tramp-method (file-remote-p helm-ff-default-directory 'method))
(tramp-host (file-remote-p helm-ff-default-directory 'host))
(tramp-prefix (concat "/" tramp-method ":" tramp-host ":"))
(fname (if tramp-host
(concat tramp-prefix loc-fname) loc-fname)))
(case where
(other-window (find-file-other-window fname))
(elscreen (helm-elscreen-find-file fname))
(other-frame (find-file-other-frame fname))
(grep (helm-c-grep-save-results-1))
(t (find-file fname)))
(unless (eq where 'grep)
(helm-goto-line lineno))
(when mark
(set-marker (mark-marker) (point))
(push-mark (point) 'nomsg))
;; Save history
(unless (or helm-in-persistent-action
(string= helm-pattern ""))
(setq helm-c-grep-history
(cons helm-pattern
(delete helm-pattern helm-c-grep-history)))
(when (> (length helm-c-grep-history)
helm-c-grep-max-length-history)
(setq helm-c-grep-history
(delete (car (last helm-c-grep-history))
helm-c-grep-history))))))
(defun helm-c-grep-other-window (candidate)
"Jump to result in other window from helm grep."
(helm-c-grep-action candidate 'other-window))
(defun helm-c-grep-other-frame (candidate)
"Jump to result in other frame from helm grep."
(helm-c-grep-action candidate 'other-frame))
(defun helm-c-grep-jump-elscreen (candidate)
"Jump to result in elscreen from helm grep."
(helm-c-grep-action candidate 'elscreen))
(defun helm-c-grep-save-results (_candidate)
(helm-c-grep-action _candidate 'grep))
(defun helm-c-grep-save-results-1 ()
"Save helm grep result in a `grep-mode' buffer."
(let ((buf "*grep*")
new-buf)
(when (get-buffer buf)
(setq new-buf (read-string "GrepBufferName: " buf))
(loop for b in (helm-c-buffer-list)
when (and (string= new-buf b)
(not (y-or-n-p
(format "Buffer `%s' already exists overwrite? "
new-buf))))
do (setq new-buf (read-string "GrepBufferName: " "*grep ")))
(setq buf new-buf))
(with-current-buffer (get-buffer-create buf)
(let ((inhibit-read-only t))
(erase-buffer)
(insert "-*- mode: grep -*-\n\n"
(format "Grep Results for `%s':\n\n" helm-pattern))
(save-excursion
(insert (with-current-buffer helm-buffer
(goto-char (point-min)) (forward-line 1)
(buffer-substring (point) (point-max))))
(grep-mode))))
(message "Helm Grep Results saved in `%s' buffer" buf)))
(defun helm-c-grep-persistent-action (candidate)
"Persistent action for `helm-do-grep'.
With a prefix arg record CANDIDATE in `mark-ring'."
(if current-prefix-arg
(helm-c-grep-action candidate nil 'mark)
(helm-c-grep-action candidate))
(helm-match-line-color-current-line))
(defun helm-c-grep-guess-extensions (files)
"Try to guess file extensions in FILES list when using grep recurse.
These extensions will be added to command line with --include arg of grep."
(loop
with glob-list = nil
with lst = (if (file-directory-p (car files))
(directory-files
(car files) nil
directory-files-no-dot-files-regexp)
files)
for i in lst
for ext = (file-name-extension i t)
for glob = (and ext (not (string= ext ""))
(concat "*" ext))
unless (or (not glob)
(member glob glob-list)
(member glob grep-find-ignored-files))
collect glob into glob-list
finally return glob-list))
(defun helm-do-grep-1 (only &optional recurse zgrep)
"Launch grep with a list of ONLY files.
When RECURSE is given use -r option of grep and prompt user
to set the --include args of grep.
You can give more than one arg separated by space.
e.g *.el *.py *.tex.
If it's empty --exclude `grep-find-ignored-files' is used instead."
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
(exts (helm-c-grep-guess-extensions only))
(globs (and (not zgrep) (mapconcat 'identity exts " ")))
(include-files (and recurse (not zgrep)
(read-string "OnlyExt(*.[ext]): "
globs)))
;; Set `minibuffer-history' AFTER includes-files
;; to avoid storing wild-cards here.
(minibuffer-history helm-c-grep-history)
(helm-c-grep-default-command
(cond ((and recurse zgrep) helm-c-default-zgrep-command)
(recurse helm-c-grep-default-recurse-command)
(zgrep helm-c-default-zgrep-command)
(t helm-c-grep-default-command)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
(when include-files
(setq include-files
(and (not (string= include-files ""))
(mapconcat #'(lambda (x)
(concat "--include=" (shell-quote-argument x)))
(split-string include-files) " "))))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "Grep")
(header-name . (lambda (name)
(concat name "(C-c ? Help)")))
(candidates
. (lambda ()
(funcall helm-c-grep-default-function only include-files zgrep)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-grep-mode-line-string)
(keymap . ,helm-c-grep-map)
(action . ,(delq
nil
`(("Find File" . helm-c-grep-action)
("Find file other frame" . helm-c-grep-other-frame)
,(and (locate-library "elscreen")
'("Find file in Elscreen"
. helm-c-grep-jump-elscreen))
("Save results in grep buffer" . helm-c-grep-save-results)
("Find file other window" . helm-c-grep-other-window))))
(persistent-action . helm-c-grep-persistent-action)
(persistent-help . "Jump to line (`C-u' Record in mark ring)")
(requires-pattern . 3)
(delayed)))
:buffer "*helm grep*")))
(defun helm-ff-zgrep-1 (flist recursive)
(unwind-protect
(let* ((def-dir (or helm-ff-default-directory
default-directory))
(only (if recursive
(or (gethash def-dir helm-c-rzgrep-cache)
(puthash
def-dir
(helm-c-walk-directory
def-dir
:directories nil
:path 'full
:match ".*\\(\.gz\\|\.bz\\|\.xz\\|\.lzma\\)$")
helm-c-rzgrep-cache))
flist)))
(when recursive (setq helm-c-zgrep-recurse-flag t))
(helm-do-grep-1 only recursive 'zgrep))
(setq helm-c-zgrep-recurse-flag nil)))
(defun helm-c-grep-split-line (line)
"Split a grep output line."
(let (beg fname lineno str)
;; Don't print until grep line is valid.
(when (string-match "\\(.*\\)\\(:[0-9]+:\\)\\(.*\\)" line)
(with-temp-buffer
(insert line)
(goto-char (point-min))
(setq beg (point))
(forward-char 2)
(re-search-forward ":" nil t)
(setq fname (buffer-substring-no-properties beg (1- (point))))
(setq beg (point))
(re-search-forward ":" nil t)
(setq lineno (buffer-substring-no-properties beg (1- (point))))
(setq str (buffer-substring-no-properties (point) (point-at-eol))))
(list fname lineno str))))
(defun helm-c-grep-cand-transformer (candidates sources)
"Filtered candidate transformer function for `helm-do-grep'."
(loop for i in candidates
for split = (and i (helm-c-grep-split-line i))
for fname = (car split)
for lineno = (nth 1 split)
for str = (nth 2 split)
when (and fname lineno str)
collect
(cons (concat (propertize (file-name-nondirectory fname)
'face 'helm-grep-file
'help-echo fname) ":"
(propertize lineno 'face 'helm-grep-lineno) ":"
(helm-c-grep-highlight-match str))
i)))
(defun helm-c-grep-highlight-match (str)
"Highlight in string STR all occurences matching `helm-pattern'."
(condition-case nil
(with-temp-buffer
(insert str)
(goto-char (point-min))
(while (and (re-search-forward helm-pattern nil t)
(> (- (match-end 0) (match-beginning 0)) 0))
(add-text-properties
(match-beginning 0) (match-end 0)
'(face helm-grep-match)))
(buffer-string))
(error nil)))
;; Go to next or precedent file (common to etags and grep).
(defun helm-c-goto-next-or-prec-file (n)
"Go to next or precedent candidate file in helm grep/etags buffers.
If N is positive go forward otherwise go backward."
(with-helm-window
(let* ((current-line-list (split-string
(buffer-substring
(point-at-bol)
(point-at-eol)) ":"))
(current-fname (nth 0 current-line-list))
(fn-b-o-f (if (eq n 1) 'eobp 'bobp)))
(catch 'break
(while (not (funcall fn-b-o-f))
(forward-line n) ; Go forward or backward depending of n value.
(unless (search-forward current-fname (point-at-eol) t)
(helm-mark-current-line)
(throw 'break nil))))
(cond ((and (eq n 1) (eobp))
(re-search-backward ".")
(forward-line 0)
(helm-mark-current-line))
((and (< n 1) (bobp))
(forward-line 1)
(helm-mark-current-line))))))
;;;###autoload
(defun helm-c-goto-precedent-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file -1))
;;;###autoload
(defun helm-c-goto-next-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file 1))
;;;###autoload
(defun helm-c-grep-run-persistent-action ()
"Run grep persistent action from `helm-do-grep-1'."
(interactive)
(helm-attrset 'jump-persistent 'helm-c-grep-persistent-action)
(helm-execute-persistent-action 'jump-persistent))
;;;###autoload
(defun helm-c-grep-run-default-action ()
"Run grep default action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-action))
;;;###autoload
(defun helm-c-grep-run-other-window-action ()
"Run grep goto other window action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-other-window))
;;;###autoload
(defun helm-c-grep-run-save-buffer ()
"Run grep save results action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-save-results))
;;; Grep buffers
;;
;;
(defun helm-c-grep-buffers-1 (candidate &optional zgrep)
"Run grep on all file--buffers or CANDIDATE if it is a file--buffer.
If one of selected buffers is not a file--buffer,
it is ignored and grep will run on all others file--buffers.
If only one candidate is selected and it is not a file--buffer,
switch to this buffer and run `helm-occur'.
If a prefix arg is given run grep on all buffers ignoring non--file-buffers."
(let* ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(cands (if prefarg
(buffer-list)
(helm-marked-candidates)))
(win-conf (current-window-configuration))
;; Non--fname buffers are ignored.
(bufs (loop for buf in cands
for fname = (buffer-file-name (get-buffer buf))
when fname
collect (expand-file-name fname))))
(if bufs
(if zgrep
(helm-do-grep-1 bufs nil 'zgrep)
(helm-do-grep-1 bufs))
;; bufs is empty, thats mean we have only CANDIDATE
;; and it is not a buffer-filename, fallback to occur.
(helm-c-switch-to-buffer candidate)
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
(helm-occur)
(when (eq helm-exit-status 1)
(set-window-configuration win-conf)))))
(defun helm-c-grep-buffers (candidate)
"Action to grep buffers."
(helm-c-grep-buffers-1 candidate))
(defun helm-c-zgrep-buffers (candidate)
"Action to zgrep buffers."
(helm-c-grep-buffers-1 candidate 'zgrep))
;;; Helm interface for pdfgrep
;; pdfgrep program <http://pdfgrep.sourceforge.net/>
;; and a pdf-reader (e.g xpdf) are needed.
;;
(defvar helm-c-pdfgrep-default-command "pdfgrep --color never -niH %s %s")
(defvar helm-c-pdfgrep-default-function 'helm-c-pdfgrep-init)
(defvar helm-c-pdfgrep-debug-command-line nil)
(defun helm-c-pdfgrep-init (only-files)
"Start an asynchronous pdfgrep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(cmd-line (format helm-c-pdfgrep-default-command
helm-pattern
fnargs)))
(when helm-c-pdfgrep-debug-command-line
(with-current-buffer (get-buffer-create "*any pdfgrep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize "(Pdfgrep Process Running) "
'face '((:foreground "red"))))))
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "pdfgrep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "pdfgrep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line))
(force-mode-line-update nil)))))))
(defun helm-do-pdfgrep-1 (only)
"Launch pdfgrep with a list of ONLY files."
(unless (executable-find "pdfgrep")
(error "Error: No such program `pdfgrep'."))
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; If `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "PdfGrep")
(candidates
. (lambda ()
(funcall helm-c-pdfgrep-default-function only)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-pdfgrep-mode-line-string)
(action . helm-c-pdfgrep-action)
(persistent-help . "Jump to PDF Page")
(requires-pattern . 3)
(delayed)))
:keymap helm-c-pdfgrep-map
:buffer "*helm grep*")))
(defun helm-c-pdfgrep-action (candidate)
(let* ((split (helm-c-grep-split-line candidate))
(pageno (nth 1 split))
(fname (car split)))
(start-file-process-shell-command
"pdf-reader" nil
(format-spec helm-c-pdfgrep-default-read-command
(list (cons ?f fname) (cons ?p pageno))))))
;;;###autoload
(defun helm-do-grep ()
"Preconfigured helm for grep.
Contrarily to Emacs `grep' no default directory is given, but
the full path of candidates in ONLY.
That allow to grep different files not only in `default-directory' but anywhere
by marking them (C-<SPACE>). If one or more directory is selected
grep will search in all files of these directories.
You can use also wildcard in the base name of candidate.
If a prefix arg is given use the -r option of grep.
The prefix arg can be passed before or after start.
See also `helm-do-grep-1'."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(prefarg (or current-prefix-arg helm-current-prefix-arg)))
(helm-do-grep-1 only prefarg)))
;;;###autoload
(defun helm-do-zgrep ()
"Preconfigured helm for zgrep."
(interactive)
(let ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(ls (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer))))))
(helm-ff-zgrep-1 ls prefarg)))
;;;###autoload
(defun helm-do-pdfgrep ()
"Preconfigured helm for pdfgrep."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:test #'(lambda (file)
(or (string= (file-name-extension file) "pdf")
(string= (file-name-extension file) "PDF")
(file-directory-p file)))
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(helm-c-grep-default-function 'helm-c-pdfgrep-init))
(helm-do-pdfgrep-1 only)))
(provide 'helm-grep)
;;; helm-grep.el ends here
| 46997 | ;;; helm-grep.el --- Helm Incremental Grep.
;; Copyright (C) 2012 <NAME> <<EMAIL>>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(eval-when-compile (require 'cl))
(require 'helm)
(require 'grep)
(require 'helm-files)
(require 'helm-regexp)
(declare-function helm-elscreen-find-file "helm-elscreen" (file))
(defgroup helm-grep nil
"Grep related Applications and libraries for Helm."
:group 'helm)
(defcustom helm-c-grep-use-ioccur-style-keys t
"Use Arrow keys to jump to occurences."
:group 'helm-grep
:type 'boolean)
(defcustom helm-c-pdfgrep-default-read-command "xpdf '%f' %p"
"Default command to read pdf files from pdfgrep.
Where '%f' format spec is filename and '%p' is page number"
:group 'helm-grep
:type 'string)
(defcustom helm-c-grep-max-length-history 100
"Max number of elements to save in `helm-c-grep-history'."
:group 'helm-grep
:type 'integer)
;;; Faces
;;
;;
(defface helm-grep-match
'((t (:inherit match)))
"Face used to highlight grep matches."
:group 'helm-grep)
(defface helm-grep-file
'((t (:foreground "BlueViolet" :underline t)))
"Face used to highlight grep results filenames."
:group 'helm-grep)
(defface helm-grep-lineno
'((t (:foreground "Darkorange1")))
"Face used to highlight grep number lines."
:group 'helm-grep)
(defface helm-grep-running
'((t (:foreground "Red")))
"Face used in mode line when grep is running."
:group 'helm-grep)
(defface helm-grep-finish
'((t (:foreground "Green")))
"Face used in mode line when grep is finish."
:group 'helm-grep)
(defvar helm-c-grep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-c o") 'helm-c-grep-run-other-window-action)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-x C-s") 'helm-c-grep-run-save-buffer)
(when helm-c-grep-use-ioccur-style-keys
(define-key map (kbd "<right>") 'helm-c-grep-run-persistent-action)
(define-key map (kbd "<left>") 'helm-c-grep-run-default-action))
(define-key map (kbd "C-c ?") 'helm-grep-help)
(delq nil map))
"Keymap used in Grep sources.")
(defvar helm-c-pdfgrep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-c ?") 'helm-pdfgrep-help)
map)
"Keymap used in pdfgrep.")
(defvar helm-c-grep-default-command
"grep -d skip %e -niH -e %p %f"
"Default grep format command for `helm-do-grep-1'.
Where:
'%e' format spec is for --exclude or --include grep options.
'%p' format spec is for pattern.
'%f' format spec is for filenames.")
(defvar helm-c-grep-default-recurse-command
"grep -d recurse %e -niH -e %p %f"
"Default recursive grep format command for `helm-do-grep-1'.
See `helm-c-grep-default-command' for format specs.")
(defvar helm-c-default-zgrep-command "zgrep -niH -e %p %f")
(defvar helm-c-rzgrep-cache (make-hash-table :test 'equal))
(defvar helm-c-grep-default-function 'helm-c-grep-init)
(defvar helm-c-grep-debug-command-line nil
"Turn on helm grep command-line debugging when non--nil.")
(defvar helm-c-zgrep-recurse-flag nil)
(defvar helm-c-grep-history nil)
(defun helm-c-grep-prepare-candidates (candidates)
"Prepare filenames and directories CANDIDATES for grep command line."
;; If one or more candidate is a directory, search in all files
;; of this candidate (e.g /home/user/directory/*).
;; If r option is enabled search also in subdidrectories.
;; We need here to expand wildcards to support crap windows filenames
;; as grep doesn't accept quoted wildcards (e.g "dir/*.el").
(if helm-c-zgrep-recurse-flag
(mapconcat 'shell-quote-argument candidates " ")
(loop for i in candidates append
(cond ( ;; Candidate is a directory and we use recursion.
(and (file-directory-p i)
(helm-c-grep-recurse-p))
(list (expand-file-name i)))
;; Candidate is a directory, search in all files.
((file-directory-p i)
(file-expand-wildcards
(concat (file-name-as-directory (expand-file-name i)) "*") t))
;; Candidate is a file or wildcard and we use recursion, use the
;; current directory instead of candidate.
((and (or (file-exists-p i) (string-match "\*" i))
(helm-c-grep-recurse-p))
(list (expand-file-name
(directory-file-name ; Needed for windoze.
(file-name-directory (directory-file-name i))))))
;; Candidate use wildcard.
((string-match "^\*" (helm-c-basename i))
(file-expand-wildcards i t))
;; Else should be one or more file.
(t (list i))) into all-files
finally return
(mapconcat 'shell-quote-argument all-files " "))))
(defun helm-c-grep-recurse-p ()
"Check if `helm-do-grep-1' have switched to recursive."
(let ((args (replace-regexp-in-string
"grep" "" helm-c-grep-default-command)))
(string-match-p "r\\|recurse" args)))
(defun helm-c-grep-init (only-files &optional include zgrep)
"Start an asynchronous grep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(ignored-files (mapconcat
#'(lambda (x)
(concat "--exclude=" (shell-quote-argument x)))
grep-find-ignored-files " "))
(ignored-dirs (mapconcat
;; Need grep version >=2.5.4 of Gnuwin32 on windoze.
#'(lambda (x)
(concat "--exclude-dir=" (shell-quote-argument x)))
grep-find-ignored-directories " "))
(exclude (if (helm-c-grep-recurse-p)
(concat (or include ignored-files) " " ignored-dirs)
ignored-files))
(cmd-line (format-spec
helm-c-grep-default-command
(delq nil
(list (unless zgrep (cons ?e exclude))
(cons ?p (shell-quote-argument helm-pattern))
(cons ?f fnargs))))))
(when helm-c-grep-debug-command-line
(with-current-buffer (get-buffer-create "*any grep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (when (get-process "grep-process")
(propertize "[Grep Process Running] "
'face 'helm-grep-running)))))
(force-mode-line-update nil)
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "grep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "grep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line)
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize
(format "[Grep Process Finished - (%s results)] "
(let ((nlines (1- (count-lines
(point-min)
(point-max)))))
(if (> nlines 0) nlines 0)))
'face 'helm-grep-finish))))
(force-mode-line-update nil))))))))
(defun helm-c-grep-action (candidate &optional where mark)
"Define a default action for `helm-do-grep' on CANDIDATE.
WHERE can be one of other-window, elscreen, other-frame."
(let* ((split (helm-c-grep-split-line candidate))
(lineno (string-to-number (nth 1 split)))
(loc-fname (car split))
(tramp-method (file-remote-p helm-ff-default-directory 'method))
(tramp-host (file-remote-p helm-ff-default-directory 'host))
(tramp-prefix (concat "/" tramp-method ":" tramp-host ":"))
(fname (if tramp-host
(concat tramp-prefix loc-fname) loc-fname)))
(case where
(other-window (find-file-other-window fname))
(elscreen (helm-elscreen-find-file fname))
(other-frame (find-file-other-frame fname))
(grep (helm-c-grep-save-results-1))
(t (find-file fname)))
(unless (eq where 'grep)
(helm-goto-line lineno))
(when mark
(set-marker (mark-marker) (point))
(push-mark (point) 'nomsg))
;; Save history
(unless (or helm-in-persistent-action
(string= helm-pattern ""))
(setq helm-c-grep-history
(cons helm-pattern
(delete helm-pattern helm-c-grep-history)))
(when (> (length helm-c-grep-history)
helm-c-grep-max-length-history)
(setq helm-c-grep-history
(delete (car (last helm-c-grep-history))
helm-c-grep-history))))))
(defun helm-c-grep-other-window (candidate)
"Jump to result in other window from helm grep."
(helm-c-grep-action candidate 'other-window))
(defun helm-c-grep-other-frame (candidate)
"Jump to result in other frame from helm grep."
(helm-c-grep-action candidate 'other-frame))
(defun helm-c-grep-jump-elscreen (candidate)
"Jump to result in elscreen from helm grep."
(helm-c-grep-action candidate 'elscreen))
(defun helm-c-grep-save-results (_candidate)
(helm-c-grep-action _candidate 'grep))
(defun helm-c-grep-save-results-1 ()
"Save helm grep result in a `grep-mode' buffer."
(let ((buf "*grep*")
new-buf)
(when (get-buffer buf)
(setq new-buf (read-string "GrepBufferName: " buf))
(loop for b in (helm-c-buffer-list)
when (and (string= new-buf b)
(not (y-or-n-p
(format "Buffer `%s' already exists overwrite? "
new-buf))))
do (setq new-buf (read-string "GrepBufferName: " "*grep ")))
(setq buf new-buf))
(with-current-buffer (get-buffer-create buf)
(let ((inhibit-read-only t))
(erase-buffer)
(insert "-*- mode: grep -*-\n\n"
(format "Grep Results for `%s':\n\n" helm-pattern))
(save-excursion
(insert (with-current-buffer helm-buffer
(goto-char (point-min)) (forward-line 1)
(buffer-substring (point) (point-max))))
(grep-mode))))
(message "Helm Grep Results saved in `%s' buffer" buf)))
(defun helm-c-grep-persistent-action (candidate)
"Persistent action for `helm-do-grep'.
With a prefix arg record CANDIDATE in `mark-ring'."
(if current-prefix-arg
(helm-c-grep-action candidate nil 'mark)
(helm-c-grep-action candidate))
(helm-match-line-color-current-line))
(defun helm-c-grep-guess-extensions (files)
"Try to guess file extensions in FILES list when using grep recurse.
These extensions will be added to command line with --include arg of grep."
(loop
with glob-list = nil
with lst = (if (file-directory-p (car files))
(directory-files
(car files) nil
directory-files-no-dot-files-regexp)
files)
for i in lst
for ext = (file-name-extension i t)
for glob = (and ext (not (string= ext ""))
(concat "*" ext))
unless (or (not glob)
(member glob glob-list)
(member glob grep-find-ignored-files))
collect glob into glob-list
finally return glob-list))
(defun helm-do-grep-1 (only &optional recurse zgrep)
"Launch grep with a list of ONLY files.
When RECURSE is given use -r option of grep and prompt user
to set the --include args of grep.
You can give more than one arg separated by space.
e.g *.el *.py *.tex.
If it's empty --exclude `grep-find-ignored-files' is used instead."
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
(exts (helm-c-grep-guess-extensions only))
(globs (and (not zgrep) (mapconcat 'identity exts " ")))
(include-files (and recurse (not zgrep)
(read-string "OnlyExt(*.[ext]): "
globs)))
;; Set `minibuffer-history' AFTER includes-files
;; to avoid storing wild-cards here.
(minibuffer-history helm-c-grep-history)
(helm-c-grep-default-command
(cond ((and recurse zgrep) helm-c-default-zgrep-command)
(recurse helm-c-grep-default-recurse-command)
(zgrep helm-c-default-zgrep-command)
(t helm-c-grep-default-command)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
(when include-files
(setq include-files
(and (not (string= include-files ""))
(mapconcat #'(lambda (x)
(concat "--include=" (shell-quote-argument x)))
(split-string include-files) " "))))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "Grep")
(header-name . (lambda (name)
(concat name "(C-c ? Help)")))
(candidates
. (lambda ()
(funcall helm-c-grep-default-function only include-files zgrep)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-grep-mode-line-string)
(keymap . ,helm-c-grep-map)
(action . ,(delq
nil
`(("Find File" . helm-c-grep-action)
("Find file other frame" . helm-c-grep-other-frame)
,(and (locate-library "elscreen")
'("Find file in Elscreen"
. helm-c-grep-jump-elscreen))
("Save results in grep buffer" . helm-c-grep-save-results)
("Find file other window" . helm-c-grep-other-window))))
(persistent-action . helm-c-grep-persistent-action)
(persistent-help . "Jump to line (`C-u' Record in mark ring)")
(requires-pattern . 3)
(delayed)))
:buffer "*helm grep*")))
(defun helm-ff-zgrep-1 (flist recursive)
(unwind-protect
(let* ((def-dir (or helm-ff-default-directory
default-directory))
(only (if recursive
(or (gethash def-dir helm-c-rzgrep-cache)
(puthash
def-dir
(helm-c-walk-directory
def-dir
:directories nil
:path 'full
:match ".*\\(\.gz\\|\.bz\\|\.xz\\|\.lzma\\)$")
helm-c-rzgrep-cache))
flist)))
(when recursive (setq helm-c-zgrep-recurse-flag t))
(helm-do-grep-1 only recursive 'zgrep))
(setq helm-c-zgrep-recurse-flag nil)))
(defun helm-c-grep-split-line (line)
"Split a grep output line."
(let (beg fname lineno str)
;; Don't print until grep line is valid.
(when (string-match "\\(.*\\)\\(:[0-9]+:\\)\\(.*\\)" line)
(with-temp-buffer
(insert line)
(goto-char (point-min))
(setq beg (point))
(forward-char 2)
(re-search-forward ":" nil t)
(setq fname (buffer-substring-no-properties beg (1- (point))))
(setq beg (point))
(re-search-forward ":" nil t)
(setq lineno (buffer-substring-no-properties beg (1- (point))))
(setq str (buffer-substring-no-properties (point) (point-at-eol))))
(list fname lineno str))))
(defun helm-c-grep-cand-transformer (candidates sources)
"Filtered candidate transformer function for `helm-do-grep'."
(loop for i in candidates
for split = (and i (helm-c-grep-split-line i))
for fname = (car split)
for lineno = (nth 1 split)
for str = (nth 2 split)
when (and fname lineno str)
collect
(cons (concat (propertize (file-name-nondirectory fname)
'face 'helm-grep-file
'help-echo fname) ":"
(propertize lineno 'face 'helm-grep-lineno) ":"
(helm-c-grep-highlight-match str))
i)))
(defun helm-c-grep-highlight-match (str)
"Highlight in string STR all occurences matching `helm-pattern'."
(condition-case nil
(with-temp-buffer
(insert str)
(goto-char (point-min))
(while (and (re-search-forward helm-pattern nil t)
(> (- (match-end 0) (match-beginning 0)) 0))
(add-text-properties
(match-beginning 0) (match-end 0)
'(face helm-grep-match)))
(buffer-string))
(error nil)))
;; Go to next or precedent file (common to etags and grep).
(defun helm-c-goto-next-or-prec-file (n)
"Go to next or precedent candidate file in helm grep/etags buffers.
If N is positive go forward otherwise go backward."
(with-helm-window
(let* ((current-line-list (split-string
(buffer-substring
(point-at-bol)
(point-at-eol)) ":"))
(current-fname (nth 0 current-line-list))
(fn-b-o-f (if (eq n 1) 'eobp 'bobp)))
(catch 'break
(while (not (funcall fn-b-o-f))
(forward-line n) ; Go forward or backward depending of n value.
(unless (search-forward current-fname (point-at-eol) t)
(helm-mark-current-line)
(throw 'break nil))))
(cond ((and (eq n 1) (eobp))
(re-search-backward ".")
(forward-line 0)
(helm-mark-current-line))
((and (< n 1) (bobp))
(forward-line 1)
(helm-mark-current-line))))))
;;;###autoload
(defun helm-c-goto-precedent-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file -1))
;;;###autoload
(defun helm-c-goto-next-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file 1))
;;;###autoload
(defun helm-c-grep-run-persistent-action ()
"Run grep persistent action from `helm-do-grep-1'."
(interactive)
(helm-attrset 'jump-persistent 'helm-c-grep-persistent-action)
(helm-execute-persistent-action 'jump-persistent))
;;;###autoload
(defun helm-c-grep-run-default-action ()
"Run grep default action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-action))
;;;###autoload
(defun helm-c-grep-run-other-window-action ()
"Run grep goto other window action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-other-window))
;;;###autoload
(defun helm-c-grep-run-save-buffer ()
"Run grep save results action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-save-results))
;;; Grep buffers
;;
;;
(defun helm-c-grep-buffers-1 (candidate &optional zgrep)
"Run grep on all file--buffers or CANDIDATE if it is a file--buffer.
If one of selected buffers is not a file--buffer,
it is ignored and grep will run on all others file--buffers.
If only one candidate is selected and it is not a file--buffer,
switch to this buffer and run `helm-occur'.
If a prefix arg is given run grep on all buffers ignoring non--file-buffers."
(let* ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(cands (if prefarg
(buffer-list)
(helm-marked-candidates)))
(win-conf (current-window-configuration))
;; Non--fname buffers are ignored.
(bufs (loop for buf in cands
for fname = (buffer-file-name (get-buffer buf))
when fname
collect (expand-file-name fname))))
(if bufs
(if zgrep
(helm-do-grep-1 bufs nil 'zgrep)
(helm-do-grep-1 bufs))
;; bufs is empty, thats mean we have only CANDIDATE
;; and it is not a buffer-filename, fallback to occur.
(helm-c-switch-to-buffer candidate)
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
(helm-occur)
(when (eq helm-exit-status 1)
(set-window-configuration win-conf)))))
(defun helm-c-grep-buffers (candidate)
"Action to grep buffers."
(helm-c-grep-buffers-1 candidate))
(defun helm-c-zgrep-buffers (candidate)
"Action to zgrep buffers."
(helm-c-grep-buffers-1 candidate 'zgrep))
;;; Helm interface for pdfgrep
;; pdfgrep program <http://pdfgrep.sourceforge.net/>
;; and a pdf-reader (e.g xpdf) are needed.
;;
(defvar helm-c-pdfgrep-default-command "pdfgrep --color never -niH %s %s")
(defvar helm-c-pdfgrep-default-function 'helm-c-pdfgrep-init)
(defvar helm-c-pdfgrep-debug-command-line nil)
(defun helm-c-pdfgrep-init (only-files)
"Start an asynchronous pdfgrep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(cmd-line (format helm-c-pdfgrep-default-command
helm-pattern
fnargs)))
(when helm-c-pdfgrep-debug-command-line
(with-current-buffer (get-buffer-create "*any pdfgrep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize "(Pdfgrep Process Running) "
'face '((:foreground "red"))))))
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "pdfgrep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "pdfgrep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line))
(force-mode-line-update nil)))))))
(defun helm-do-pdfgrep-1 (only)
"Launch pdfgrep with a list of ONLY files."
(unless (executable-find "pdfgrep")
(error "Error: No such program `pdfgrep'."))
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; If `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "PdfGrep")
(candidates
. (lambda ()
(funcall helm-c-pdfgrep-default-function only)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-pdfgrep-mode-line-string)
(action . helm-c-pdfgrep-action)
(persistent-help . "Jump to PDF Page")
(requires-pattern . 3)
(delayed)))
:keymap helm-c-pdfgrep-map
:buffer "*helm grep*")))
(defun helm-c-pdfgrep-action (candidate)
(let* ((split (helm-c-grep-split-line candidate))
(pageno (nth 1 split))
(fname (car split)))
(start-file-process-shell-command
"pdf-reader" nil
(format-spec helm-c-pdfgrep-default-read-command
(list (cons ?f fname) (cons ?p pageno))))))
;;;###autoload
(defun helm-do-grep ()
"Preconfigured helm for grep.
Contrarily to Emacs `grep' no default directory is given, but
the full path of candidates in ONLY.
That allow to grep different files not only in `default-directory' but anywhere
by marking them (C-<SPACE>). If one or more directory is selected
grep will search in all files of these directories.
You can use also wildcard in the base name of candidate.
If a prefix arg is given use the -r option of grep.
The prefix arg can be passed before or after start.
See also `helm-do-grep-1'."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(prefarg (or current-prefix-arg helm-current-prefix-arg)))
(helm-do-grep-1 only prefarg)))
;;;###autoload
(defun helm-do-zgrep ()
"Preconfigured helm for zgrep."
(interactive)
(let ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(ls (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer))))))
(helm-ff-zgrep-1 ls prefarg)))
;;;###autoload
(defun helm-do-pdfgrep ()
"Preconfigured helm for pdfgrep."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:test #'(lambda (file)
(or (string= (file-name-extension file) "pdf")
(string= (file-name-extension file) "PDF")
(file-directory-p file)))
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(helm-c-grep-default-function 'helm-c-pdfgrep-init))
(helm-do-pdfgrep-1 only)))
(provide 'helm-grep)
;;; helm-grep.el ends here
| true | ;;; helm-grep.el --- Helm Incremental Grep.
;; Copyright (C) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Code:
(eval-when-compile (require 'cl))
(require 'helm)
(require 'grep)
(require 'helm-files)
(require 'helm-regexp)
(declare-function helm-elscreen-find-file "helm-elscreen" (file))
(defgroup helm-grep nil
"Grep related Applications and libraries for Helm."
:group 'helm)
(defcustom helm-c-grep-use-ioccur-style-keys t
"Use Arrow keys to jump to occurences."
:group 'helm-grep
:type 'boolean)
(defcustom helm-c-pdfgrep-default-read-command "xpdf '%f' %p"
"Default command to read pdf files from pdfgrep.
Where '%f' format spec is filename and '%p' is page number"
:group 'helm-grep
:type 'string)
(defcustom helm-c-grep-max-length-history 100
"Max number of elements to save in `helm-c-grep-history'."
:group 'helm-grep
:type 'integer)
;;; Faces
;;
;;
(defface helm-grep-match
'((t (:inherit match)))
"Face used to highlight grep matches."
:group 'helm-grep)
(defface helm-grep-file
'((t (:foreground "BlueViolet" :underline t)))
"Face used to highlight grep results filenames."
:group 'helm-grep)
(defface helm-grep-lineno
'((t (:foreground "Darkorange1")))
"Face used to highlight grep number lines."
:group 'helm-grep)
(defface helm-grep-running
'((t (:foreground "Red")))
"Face used in mode line when grep is running."
:group 'helm-grep)
(defface helm-grep-finish
'((t (:foreground "Green")))
"Face used in mode line when grep is finish."
:group 'helm-grep)
(defvar helm-c-grep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-c o") 'helm-c-grep-run-other-window-action)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-x C-s") 'helm-c-grep-run-save-buffer)
(when helm-c-grep-use-ioccur-style-keys
(define-key map (kbd "<right>") 'helm-c-grep-run-persistent-action)
(define-key map (kbd "<left>") 'helm-c-grep-run-default-action))
(define-key map (kbd "C-c ?") 'helm-grep-help)
(delq nil map))
"Keymap used in Grep sources.")
(defvar helm-c-pdfgrep-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map helm-map)
(define-key map (kbd "M-<down>") 'helm-c-goto-next-file)
(define-key map (kbd "M-<up>") 'helm-c-goto-precedent-file)
(define-key map (kbd "C-w") 'helm-yank-text-at-point)
(define-key map (kbd "C-c ?") 'helm-pdfgrep-help)
map)
"Keymap used in pdfgrep.")
(defvar helm-c-grep-default-command
"grep -d skip %e -niH -e %p %f"
"Default grep format command for `helm-do-grep-1'.
Where:
'%e' format spec is for --exclude or --include grep options.
'%p' format spec is for pattern.
'%f' format spec is for filenames.")
(defvar helm-c-grep-default-recurse-command
"grep -d recurse %e -niH -e %p %f"
"Default recursive grep format command for `helm-do-grep-1'.
See `helm-c-grep-default-command' for format specs.")
(defvar helm-c-default-zgrep-command "zgrep -niH -e %p %f")
(defvar helm-c-rzgrep-cache (make-hash-table :test 'equal))
(defvar helm-c-grep-default-function 'helm-c-grep-init)
(defvar helm-c-grep-debug-command-line nil
"Turn on helm grep command-line debugging when non--nil.")
(defvar helm-c-zgrep-recurse-flag nil)
(defvar helm-c-grep-history nil)
(defun helm-c-grep-prepare-candidates (candidates)
"Prepare filenames and directories CANDIDATES for grep command line."
;; If one or more candidate is a directory, search in all files
;; of this candidate (e.g /home/user/directory/*).
;; If r option is enabled search also in subdidrectories.
;; We need here to expand wildcards to support crap windows filenames
;; as grep doesn't accept quoted wildcards (e.g "dir/*.el").
(if helm-c-zgrep-recurse-flag
(mapconcat 'shell-quote-argument candidates " ")
(loop for i in candidates append
(cond ( ;; Candidate is a directory and we use recursion.
(and (file-directory-p i)
(helm-c-grep-recurse-p))
(list (expand-file-name i)))
;; Candidate is a directory, search in all files.
((file-directory-p i)
(file-expand-wildcards
(concat (file-name-as-directory (expand-file-name i)) "*") t))
;; Candidate is a file or wildcard and we use recursion, use the
;; current directory instead of candidate.
((and (or (file-exists-p i) (string-match "\*" i))
(helm-c-grep-recurse-p))
(list (expand-file-name
(directory-file-name ; Needed for windoze.
(file-name-directory (directory-file-name i))))))
;; Candidate use wildcard.
((string-match "^\*" (helm-c-basename i))
(file-expand-wildcards i t))
;; Else should be one or more file.
(t (list i))) into all-files
finally return
(mapconcat 'shell-quote-argument all-files " "))))
(defun helm-c-grep-recurse-p ()
"Check if `helm-do-grep-1' have switched to recursive."
(let ((args (replace-regexp-in-string
"grep" "" helm-c-grep-default-command)))
(string-match-p "r\\|recurse" args)))
(defun helm-c-grep-init (only-files &optional include zgrep)
"Start an asynchronous grep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(ignored-files (mapconcat
#'(lambda (x)
(concat "--exclude=" (shell-quote-argument x)))
grep-find-ignored-files " "))
(ignored-dirs (mapconcat
;; Need grep version >=2.5.4 of Gnuwin32 on windoze.
#'(lambda (x)
(concat "--exclude-dir=" (shell-quote-argument x)))
grep-find-ignored-directories " "))
(exclude (if (helm-c-grep-recurse-p)
(concat (or include ignored-files) " " ignored-dirs)
ignored-files))
(cmd-line (format-spec
helm-c-grep-default-command
(delq nil
(list (unless zgrep (cons ?e exclude))
(cons ?p (shell-quote-argument helm-pattern))
(cons ?f fnargs))))))
(when helm-c-grep-debug-command-line
(with-current-buffer (get-buffer-create "*any grep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (when (get-process "grep-process")
(propertize "[Grep Process Running] "
'face 'helm-grep-running)))))
(force-mode-line-update nil)
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "grep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "grep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line)
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize
(format "[Grep Process Finished - (%s results)] "
(let ((nlines (1- (count-lines
(point-min)
(point-max)))))
(if (> nlines 0) nlines 0)))
'face 'helm-grep-finish))))
(force-mode-line-update nil))))))))
(defun helm-c-grep-action (candidate &optional where mark)
"Define a default action for `helm-do-grep' on CANDIDATE.
WHERE can be one of other-window, elscreen, other-frame."
(let* ((split (helm-c-grep-split-line candidate))
(lineno (string-to-number (nth 1 split)))
(loc-fname (car split))
(tramp-method (file-remote-p helm-ff-default-directory 'method))
(tramp-host (file-remote-p helm-ff-default-directory 'host))
(tramp-prefix (concat "/" tramp-method ":" tramp-host ":"))
(fname (if tramp-host
(concat tramp-prefix loc-fname) loc-fname)))
(case where
(other-window (find-file-other-window fname))
(elscreen (helm-elscreen-find-file fname))
(other-frame (find-file-other-frame fname))
(grep (helm-c-grep-save-results-1))
(t (find-file fname)))
(unless (eq where 'grep)
(helm-goto-line lineno))
(when mark
(set-marker (mark-marker) (point))
(push-mark (point) 'nomsg))
;; Save history
(unless (or helm-in-persistent-action
(string= helm-pattern ""))
(setq helm-c-grep-history
(cons helm-pattern
(delete helm-pattern helm-c-grep-history)))
(when (> (length helm-c-grep-history)
helm-c-grep-max-length-history)
(setq helm-c-grep-history
(delete (car (last helm-c-grep-history))
helm-c-grep-history))))))
(defun helm-c-grep-other-window (candidate)
"Jump to result in other window from helm grep."
(helm-c-grep-action candidate 'other-window))
(defun helm-c-grep-other-frame (candidate)
"Jump to result in other frame from helm grep."
(helm-c-grep-action candidate 'other-frame))
(defun helm-c-grep-jump-elscreen (candidate)
"Jump to result in elscreen from helm grep."
(helm-c-grep-action candidate 'elscreen))
(defun helm-c-grep-save-results (_candidate)
(helm-c-grep-action _candidate 'grep))
(defun helm-c-grep-save-results-1 ()
"Save helm grep result in a `grep-mode' buffer."
(let ((buf "*grep*")
new-buf)
(when (get-buffer buf)
(setq new-buf (read-string "GrepBufferName: " buf))
(loop for b in (helm-c-buffer-list)
when (and (string= new-buf b)
(not (y-or-n-p
(format "Buffer `%s' already exists overwrite? "
new-buf))))
do (setq new-buf (read-string "GrepBufferName: " "*grep ")))
(setq buf new-buf))
(with-current-buffer (get-buffer-create buf)
(let ((inhibit-read-only t))
(erase-buffer)
(insert "-*- mode: grep -*-\n\n"
(format "Grep Results for `%s':\n\n" helm-pattern))
(save-excursion
(insert (with-current-buffer helm-buffer
(goto-char (point-min)) (forward-line 1)
(buffer-substring (point) (point-max))))
(grep-mode))))
(message "Helm Grep Results saved in `%s' buffer" buf)))
(defun helm-c-grep-persistent-action (candidate)
"Persistent action for `helm-do-grep'.
With a prefix arg record CANDIDATE in `mark-ring'."
(if current-prefix-arg
(helm-c-grep-action candidate nil 'mark)
(helm-c-grep-action candidate))
(helm-match-line-color-current-line))
(defun helm-c-grep-guess-extensions (files)
"Try to guess file extensions in FILES list when using grep recurse.
These extensions will be added to command line with --include arg of grep."
(loop
with glob-list = nil
with lst = (if (file-directory-p (car files))
(directory-files
(car files) nil
directory-files-no-dot-files-regexp)
files)
for i in lst
for ext = (file-name-extension i t)
for glob = (and ext (not (string= ext ""))
(concat "*" ext))
unless (or (not glob)
(member glob glob-list)
(member glob grep-find-ignored-files))
collect glob into glob-list
finally return glob-list))
(defun helm-do-grep-1 (only &optional recurse zgrep)
"Launch grep with a list of ONLY files.
When RECURSE is given use -r option of grep and prompt user
to set the --include args of grep.
You can give more than one arg separated by space.
e.g *.el *.py *.tex.
If it's empty --exclude `grep-find-ignored-files' is used instead."
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
(exts (helm-c-grep-guess-extensions only))
(globs (and (not zgrep) (mapconcat 'identity exts " ")))
(include-files (and recurse (not zgrep)
(read-string "OnlyExt(*.[ext]): "
globs)))
;; Set `minibuffer-history' AFTER includes-files
;; to avoid storing wild-cards here.
(minibuffer-history helm-c-grep-history)
(helm-c-grep-default-command
(cond ((and recurse zgrep) helm-c-default-zgrep-command)
(recurse helm-c-grep-default-recurse-command)
(zgrep helm-c-default-zgrep-command)
(t helm-c-grep-default-command)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
(when include-files
(setq include-files
(and (not (string= include-files ""))
(mapconcat #'(lambda (x)
(concat "--include=" (shell-quote-argument x)))
(split-string include-files) " "))))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "Grep")
(header-name . (lambda (name)
(concat name "(C-c ? Help)")))
(candidates
. (lambda ()
(funcall helm-c-grep-default-function only include-files zgrep)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-grep-mode-line-string)
(keymap . ,helm-c-grep-map)
(action . ,(delq
nil
`(("Find File" . helm-c-grep-action)
("Find file other frame" . helm-c-grep-other-frame)
,(and (locate-library "elscreen")
'("Find file in Elscreen"
. helm-c-grep-jump-elscreen))
("Save results in grep buffer" . helm-c-grep-save-results)
("Find file other window" . helm-c-grep-other-window))))
(persistent-action . helm-c-grep-persistent-action)
(persistent-help . "Jump to line (`C-u' Record in mark ring)")
(requires-pattern . 3)
(delayed)))
:buffer "*helm grep*")))
(defun helm-ff-zgrep-1 (flist recursive)
(unwind-protect
(let* ((def-dir (or helm-ff-default-directory
default-directory))
(only (if recursive
(or (gethash def-dir helm-c-rzgrep-cache)
(puthash
def-dir
(helm-c-walk-directory
def-dir
:directories nil
:path 'full
:match ".*\\(\.gz\\|\.bz\\|\.xz\\|\.lzma\\)$")
helm-c-rzgrep-cache))
flist)))
(when recursive (setq helm-c-zgrep-recurse-flag t))
(helm-do-grep-1 only recursive 'zgrep))
(setq helm-c-zgrep-recurse-flag nil)))
(defun helm-c-grep-split-line (line)
"Split a grep output line."
(let (beg fname lineno str)
;; Don't print until grep line is valid.
(when (string-match "\\(.*\\)\\(:[0-9]+:\\)\\(.*\\)" line)
(with-temp-buffer
(insert line)
(goto-char (point-min))
(setq beg (point))
(forward-char 2)
(re-search-forward ":" nil t)
(setq fname (buffer-substring-no-properties beg (1- (point))))
(setq beg (point))
(re-search-forward ":" nil t)
(setq lineno (buffer-substring-no-properties beg (1- (point))))
(setq str (buffer-substring-no-properties (point) (point-at-eol))))
(list fname lineno str))))
(defun helm-c-grep-cand-transformer (candidates sources)
"Filtered candidate transformer function for `helm-do-grep'."
(loop for i in candidates
for split = (and i (helm-c-grep-split-line i))
for fname = (car split)
for lineno = (nth 1 split)
for str = (nth 2 split)
when (and fname lineno str)
collect
(cons (concat (propertize (file-name-nondirectory fname)
'face 'helm-grep-file
'help-echo fname) ":"
(propertize lineno 'face 'helm-grep-lineno) ":"
(helm-c-grep-highlight-match str))
i)))
(defun helm-c-grep-highlight-match (str)
"Highlight in string STR all occurences matching `helm-pattern'."
(condition-case nil
(with-temp-buffer
(insert str)
(goto-char (point-min))
(while (and (re-search-forward helm-pattern nil t)
(> (- (match-end 0) (match-beginning 0)) 0))
(add-text-properties
(match-beginning 0) (match-end 0)
'(face helm-grep-match)))
(buffer-string))
(error nil)))
;; Go to next or precedent file (common to etags and grep).
(defun helm-c-goto-next-or-prec-file (n)
"Go to next or precedent candidate file in helm grep/etags buffers.
If N is positive go forward otherwise go backward."
(with-helm-window
(let* ((current-line-list (split-string
(buffer-substring
(point-at-bol)
(point-at-eol)) ":"))
(current-fname (nth 0 current-line-list))
(fn-b-o-f (if (eq n 1) 'eobp 'bobp)))
(catch 'break
(while (not (funcall fn-b-o-f))
(forward-line n) ; Go forward or backward depending of n value.
(unless (search-forward current-fname (point-at-eol) t)
(helm-mark-current-line)
(throw 'break nil))))
(cond ((and (eq n 1) (eobp))
(re-search-backward ".")
(forward-line 0)
(helm-mark-current-line))
((and (< n 1) (bobp))
(forward-line 1)
(helm-mark-current-line))))))
;;;###autoload
(defun helm-c-goto-precedent-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file -1))
;;;###autoload
(defun helm-c-goto-next-file ()
"Go to precedent file in helm grep/etags buffers."
(interactive)
(helm-c-goto-next-or-prec-file 1))
;;;###autoload
(defun helm-c-grep-run-persistent-action ()
"Run grep persistent action from `helm-do-grep-1'."
(interactive)
(helm-attrset 'jump-persistent 'helm-c-grep-persistent-action)
(helm-execute-persistent-action 'jump-persistent))
;;;###autoload
(defun helm-c-grep-run-default-action ()
"Run grep default action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-action))
;;;###autoload
(defun helm-c-grep-run-other-window-action ()
"Run grep goto other window action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-other-window))
;;;###autoload
(defun helm-c-grep-run-save-buffer ()
"Run grep save results action from `helm-do-grep-1'."
(interactive)
(helm-c-quit-and-execute-action 'helm-c-grep-save-results))
;;; Grep buffers
;;
;;
(defun helm-c-grep-buffers-1 (candidate &optional zgrep)
"Run grep on all file--buffers or CANDIDATE if it is a file--buffer.
If one of selected buffers is not a file--buffer,
it is ignored and grep will run on all others file--buffers.
If only one candidate is selected and it is not a file--buffer,
switch to this buffer and run `helm-occur'.
If a prefix arg is given run grep on all buffers ignoring non--file-buffers."
(let* ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(cands (if prefarg
(buffer-list)
(helm-marked-candidates)))
(win-conf (current-window-configuration))
;; Non--fname buffers are ignored.
(bufs (loop for buf in cands
for fname = (buffer-file-name (get-buffer buf))
when fname
collect (expand-file-name fname))))
(if bufs
(if zgrep
(helm-do-grep-1 bufs nil 'zgrep)
(helm-do-grep-1 bufs))
;; bufs is empty, thats mean we have only CANDIDATE
;; and it is not a buffer-filename, fallback to occur.
(helm-c-switch-to-buffer candidate)
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
(helm-occur)
(when (eq helm-exit-status 1)
(set-window-configuration win-conf)))))
(defun helm-c-grep-buffers (candidate)
"Action to grep buffers."
(helm-c-grep-buffers-1 candidate))
(defun helm-c-zgrep-buffers (candidate)
"Action to zgrep buffers."
(helm-c-grep-buffers-1 candidate 'zgrep))
;;; Helm interface for pdfgrep
;; pdfgrep program <http://pdfgrep.sourceforge.net/>
;; and a pdf-reader (e.g xpdf) are needed.
;;
(defvar helm-c-pdfgrep-default-command "pdfgrep --color never -niH %s %s")
(defvar helm-c-pdfgrep-default-function 'helm-c-pdfgrep-init)
(defvar helm-c-pdfgrep-debug-command-line nil)
(defun helm-c-pdfgrep-init (only-files)
"Start an asynchronous pdfgrep process in ONLY-FILES list."
(let* ((fnargs (helm-c-grep-prepare-candidates
(if (file-remote-p helm-ff-default-directory)
(mapcar #'(lambda (x)
(file-remote-p x 'localname))
only-files)
only-files)))
(cmd-line (format helm-c-pdfgrep-default-command
helm-pattern
fnargs)))
(when helm-c-pdfgrep-debug-command-line
(with-current-buffer (get-buffer-create "*any pdfgrep debug*")
(goto-char (point-max))
(insert (concat ">>> " cmd-line "\n\n"))))
(setq mode-line-format
'(" " mode-line-buffer-identification " "
(line-number-mode "%l") " "
(:eval (propertize "(Pdfgrep Process Running) "
'face '((:foreground "red"))))))
(prog1
(let ((default-directory helm-ff-default-directory))
(start-file-process-shell-command "pdfgrep-process" nil cmd-line))
(message nil)
(set-process-sentinel
(get-process "pdfgrep-process")
#'(lambda (process event)
(when (string= event "finished\n")
(with-helm-window
(helm-update-move-first-line))
(force-mode-line-update nil)))))))
(defun helm-do-pdfgrep-1 (only)
"Launch pdfgrep with a list of ONLY files."
(unless (executable-find "pdfgrep")
(error "Error: No such program `pdfgrep'."))
(let* ((helm-compile-source-functions
;; rule out helm-match-plugin because the input is one regexp.
(delq 'helm-compile-source--match-plugin
(copy-sequence helm-compile-source-functions)))
;; Disable match-plugin and use here own highlighting.
(helm-mp-highlight-delay nil))
;; When called as action from an other source e.g *-find-files
;; we have to kill action buffer.
(when (get-buffer helm-action-buffer)
(kill-buffer helm-action-buffer))
;; If `helm-find-files' haven't already started,
;; give a default value to `helm-ff-default-directory'.
(setq helm-ff-default-directory (or helm-ff-default-directory
default-directory))
(helm
:sources
`(((name . "PdfGrep")
(candidates
. (lambda ()
(funcall helm-c-pdfgrep-default-function only)))
(filtered-candidate-transformer helm-c-grep-cand-transformer)
(candidate-number-limit . 9999)
(mode-line . helm-pdfgrep-mode-line-string)
(action . helm-c-pdfgrep-action)
(persistent-help . "Jump to PDF Page")
(requires-pattern . 3)
(delayed)))
:keymap helm-c-pdfgrep-map
:buffer "*helm grep*")))
(defun helm-c-pdfgrep-action (candidate)
(let* ((split (helm-c-grep-split-line candidate))
(pageno (nth 1 split))
(fname (car split)))
(start-file-process-shell-command
"pdf-reader" nil
(format-spec helm-c-pdfgrep-default-read-command
(list (cons ?f fname) (cons ?p pageno))))))
;;;###autoload
(defun helm-do-grep ()
"Preconfigured helm for grep.
Contrarily to Emacs `grep' no default directory is given, but
the full path of candidates in ONLY.
That allow to grep different files not only in `default-directory' but anywhere
by marking them (C-<SPACE>). If one or more directory is selected
grep will search in all files of these directories.
You can use also wildcard in the base name of candidate.
If a prefix arg is given use the -r option of grep.
The prefix arg can be passed before or after start.
See also `helm-do-grep-1'."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(prefarg (or current-prefix-arg helm-current-prefix-arg)))
(helm-do-grep-1 only prefarg)))
;;;###autoload
(defun helm-do-zgrep ()
"Preconfigured helm for zgrep."
(interactive)
(let ((prefarg (or current-prefix-arg helm-current-prefix-arg))
(ls (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer))))))
(helm-ff-zgrep-1 ls prefarg)))
;;;###autoload
(defun helm-do-pdfgrep ()
"Preconfigured helm for pdfgrep."
(interactive)
(let ((only (helm-c-read-file-name
"Search in file(s): "
:marked-candidates t
:test #'(lambda (file)
(or (string= (file-name-extension file) "pdf")
(string= (file-name-extension file) "PDF")
(file-directory-p file)))
:preselect (or (dired-get-filename nil t)
(buffer-file-name (current-buffer)))))
(helm-c-grep-default-function 'helm-c-pdfgrep-init))
(helm-do-pdfgrep-1 only)))
(provide 'helm-grep)
;;; helm-grep.el ends here
|
[
{
"context": "l *alk-membase-default-host*))\n (username \"Administrator\")\n (password \"adsasd\"))\n (when (equal v",
"end": 1371,
"score": 0.9983456134796143,
"start": 1358,
"tag": "USERNAME",
"value": "Administrator"
},
{
"context": " (username \"Administrator\")\n (password \"adsasd\"))\n (when (equal value \"\")\n (setq value *",
"end": 1399,
"score": 0.9992318153381348,
"start": 1393,
"tag": "PASSWORD",
"value": "adsasd"
},
{
"context": "et\" \"-O-\" \"-q\" \"--user=Administrator\" \"--password=asdasd\" \"http://lh:9000/pools/default\")\n\n(defun alk-memb",
"end": 2451,
"score": 0.9968995451927185,
"start": 2445,
"tag": "PASSWORD",
"value": "asdasd"
},
{
"context": " \"-name\" \"membasectl@127.0.0.1\" \"-hidden\"\n ",
"end": 4578,
"score": 0.9996813535690308,
"start": 4569,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | brain/membase[exp].el | phaticusthiccy/Eva | 6 | ;; https://github.com/alk/elisp-regex-dsl
(require 'regex-dsl)
;;; http://cvs.savannah.gnu.org/viewvc/*checkout*/emacs/lisp/json.el?root=emacs
(require 'json)
(setq *alk-membase-default-host* "user:port")
(setq *alk-membase-host-split-re* (redsl-to-regexp '(concat (line-begin)
(\? (concat (cap-group (literal ".*?"))
(\? (concat ":" (cap-group (literal ".*?"))))
"@"))
(cap-group (literal ".*?"))
(\? (concat ":" (cap-group (+ (char-set "0-9")))))
(line-end))))
;; (save-match-data
;; (let ((*alk-membase-default-host* "user:port"))
;; (string-match *alk-membase-host-split-re* *alk-membase-default-host*)
;; (list (match-string 1 *alk-membase-default-host*)
;; (match-string 2 *alk-membase-default-host*)
;; (match-string 3 *alk-membase-default-host*))))
(defun alk-membase-read-host ()
(let ((value (read-from-minibuffer (concat "host (" *alk-membase-default-host* "): ") nil nil nil nil *alk-membase-default-host*))
(username "Administrator")
(password "adsasd"))
(when (equal value "")
(setq value *alk-membase-default-host*))
value
(save-match-data
(string-match *alk-membase-host-split-re* value)
(let ((username (or (match-string 1 value) username))
(password (or (match-string 2 value) password))
(host (match-string 3 value))
(port (or (match-string 4 value) "8091")))
(list username password host port)))))
;; (alk-membase-read-host)
(defun alk-with-output-in-buffer (fun &rest call-process-args)
(with-temp-buffer
(let ((status (apply #'call-process
(car call-process-args)
""
(list (current-buffer) nil)
nil
(cdr call-process-args))))
(if (eql status 0)
(funcall fun)
(message "%s exited with status %d" (car call-process-args) status)
nil))))
;; (alk-with-output-in-buffer #'(lambda () (buffer-string)) "wget" "-O-" "-q" "--user=Administrator" "--password=asdasd" "http://lh:9000/pools/default")
(defun alk-membase-grab-node-and-cookie (username password host port)
;; (message "grabbing cookie from: %S\n" (list username password host port))
(let* ((json (alk-with-output-in-buffer #'(lambda ()
;; (message "raw output: %S\n" (buffer-string))
(beginning-of-buffer)
(json-read))
"wget" "-O-" "-q"
(concat "--header=Authorization: Basic "
(base64-encode-string (concat username ":" password)))
(concat "http://" host ":" port "/pools/default")))
(nodes (assoc 'nodes json))
(first-node (elt (cdr nodes) 0))
(cookie (cdr (assoc 'otpCookie first-node)))
(otp-node (cdr (assoc 'otpNode first-node))))
(message "cookie and node: %S\n" (list cookie otp-node))
(list otp-node cookie)))
(defun alk-membase-setup-distel (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(setq derl-cookie otp-cookie)
(setq erl-nodename-cache (intern otp-node))
(setq distel-modeline-node otp-node)
(force-mode-line-update)))
;; (call-interactively 'alk-membase-setup-distel)
(defun alk-membase-shell (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(unless (and otp-node otp-cookie)
(error "Failed to grap node name and cookie"))
(let ((inferior-erlang-machine-options `("-setcookie" ,otp-cookie
"-name" "membasectl@127.0.0.1" "-hidden"
,@inferior-erlang-machine-options)))
(run-erlang)
(let ((proc (get-buffer-process (current-buffer))))
(comint-send-string proc (format "net_kernel:set_net_ticktime(rpc:call('%s', net_kernel, get_net_ticktime, [])).\n" otp-node))
(sleep-for 0.1)
(comint-send-string proc "")
(sleep-for 0.1)
(comint-send-string proc (concat "r '" otp-node "'\n"))
(sleep-for 0.1)
(comint-send-string proc (concat "c 2\n"))))))
| 21137 | ;; https://github.com/alk/elisp-regex-dsl
(require 'regex-dsl)
;;; http://cvs.savannah.gnu.org/viewvc/*checkout*/emacs/lisp/json.el?root=emacs
(require 'json)
(setq *alk-membase-default-host* "user:port")
(setq *alk-membase-host-split-re* (redsl-to-regexp '(concat (line-begin)
(\? (concat (cap-group (literal ".*?"))
(\? (concat ":" (cap-group (literal ".*?"))))
"@"))
(cap-group (literal ".*?"))
(\? (concat ":" (cap-group (+ (char-set "0-9")))))
(line-end))))
;; (save-match-data
;; (let ((*alk-membase-default-host* "user:port"))
;; (string-match *alk-membase-host-split-re* *alk-membase-default-host*)
;; (list (match-string 1 *alk-membase-default-host*)
;; (match-string 2 *alk-membase-default-host*)
;; (match-string 3 *alk-membase-default-host*))))
(defun alk-membase-read-host ()
(let ((value (read-from-minibuffer (concat "host (" *alk-membase-default-host* "): ") nil nil nil nil *alk-membase-default-host*))
(username "Administrator")
(password "<PASSWORD>"))
(when (equal value "")
(setq value *alk-membase-default-host*))
value
(save-match-data
(string-match *alk-membase-host-split-re* value)
(let ((username (or (match-string 1 value) username))
(password (or (match-string 2 value) password))
(host (match-string 3 value))
(port (or (match-string 4 value) "8091")))
(list username password host port)))))
;; (alk-membase-read-host)
(defun alk-with-output-in-buffer (fun &rest call-process-args)
(with-temp-buffer
(let ((status (apply #'call-process
(car call-process-args)
""
(list (current-buffer) nil)
nil
(cdr call-process-args))))
(if (eql status 0)
(funcall fun)
(message "%s exited with status %d" (car call-process-args) status)
nil))))
;; (alk-with-output-in-buffer #'(lambda () (buffer-string)) "wget" "-O-" "-q" "--user=Administrator" "--password=<PASSWORD>" "http://lh:9000/pools/default")
(defun alk-membase-grab-node-and-cookie (username password host port)
;; (message "grabbing cookie from: %S\n" (list username password host port))
(let* ((json (alk-with-output-in-buffer #'(lambda ()
;; (message "raw output: %S\n" (buffer-string))
(beginning-of-buffer)
(json-read))
"wget" "-O-" "-q"
(concat "--header=Authorization: Basic "
(base64-encode-string (concat username ":" password)))
(concat "http://" host ":" port "/pools/default")))
(nodes (assoc 'nodes json))
(first-node (elt (cdr nodes) 0))
(cookie (cdr (assoc 'otpCookie first-node)))
(otp-node (cdr (assoc 'otpNode first-node))))
(message "cookie and node: %S\n" (list cookie otp-node))
(list otp-node cookie)))
(defun alk-membase-setup-distel (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(setq derl-cookie otp-cookie)
(setq erl-nodename-cache (intern otp-node))
(setq distel-modeline-node otp-node)
(force-mode-line-update)))
;; (call-interactively 'alk-membase-setup-distel)
(defun alk-membase-shell (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(unless (and otp-node otp-cookie)
(error "Failed to grap node name and cookie"))
(let ((inferior-erlang-machine-options `("-setcookie" ,otp-cookie
"-name" "membasectl@127.0.0.1" "-hidden"
,@inferior-erlang-machine-options)))
(run-erlang)
(let ((proc (get-buffer-process (current-buffer))))
(comint-send-string proc (format "net_kernel:set_net_ticktime(rpc:call('%s', net_kernel, get_net_ticktime, [])).\n" otp-node))
(sleep-for 0.1)
(comint-send-string proc "")
(sleep-for 0.1)
(comint-send-string proc (concat "r '" otp-node "'\n"))
(sleep-for 0.1)
(comint-send-string proc (concat "c 2\n"))))))
| true | ;; https://github.com/alk/elisp-regex-dsl
(require 'regex-dsl)
;;; http://cvs.savannah.gnu.org/viewvc/*checkout*/emacs/lisp/json.el?root=emacs
(require 'json)
(setq *alk-membase-default-host* "user:port")
(setq *alk-membase-host-split-re* (redsl-to-regexp '(concat (line-begin)
(\? (concat (cap-group (literal ".*?"))
(\? (concat ":" (cap-group (literal ".*?"))))
"@"))
(cap-group (literal ".*?"))
(\? (concat ":" (cap-group (+ (char-set "0-9")))))
(line-end))))
;; (save-match-data
;; (let ((*alk-membase-default-host* "user:port"))
;; (string-match *alk-membase-host-split-re* *alk-membase-default-host*)
;; (list (match-string 1 *alk-membase-default-host*)
;; (match-string 2 *alk-membase-default-host*)
;; (match-string 3 *alk-membase-default-host*))))
(defun alk-membase-read-host ()
(let ((value (read-from-minibuffer (concat "host (" *alk-membase-default-host* "): ") nil nil nil nil *alk-membase-default-host*))
(username "Administrator")
(password "PI:PASSWORD:<PASSWORD>END_PI"))
(when (equal value "")
(setq value *alk-membase-default-host*))
value
(save-match-data
(string-match *alk-membase-host-split-re* value)
(let ((username (or (match-string 1 value) username))
(password (or (match-string 2 value) password))
(host (match-string 3 value))
(port (or (match-string 4 value) "8091")))
(list username password host port)))))
;; (alk-membase-read-host)
(defun alk-with-output-in-buffer (fun &rest call-process-args)
(with-temp-buffer
(let ((status (apply #'call-process
(car call-process-args)
""
(list (current-buffer) nil)
nil
(cdr call-process-args))))
(if (eql status 0)
(funcall fun)
(message "%s exited with status %d" (car call-process-args) status)
nil))))
;; (alk-with-output-in-buffer #'(lambda () (buffer-string)) "wget" "-O-" "-q" "--user=Administrator" "--password=PI:PASSWORD:<PASSWORD>END_PI" "http://lh:9000/pools/default")
(defun alk-membase-grab-node-and-cookie (username password host port)
;; (message "grabbing cookie from: %S\n" (list username password host port))
(let* ((json (alk-with-output-in-buffer #'(lambda ()
;; (message "raw output: %S\n" (buffer-string))
(beginning-of-buffer)
(json-read))
"wget" "-O-" "-q"
(concat "--header=Authorization: Basic "
(base64-encode-string (concat username ":" password)))
(concat "http://" host ":" port "/pools/default")))
(nodes (assoc 'nodes json))
(first-node (elt (cdr nodes) 0))
(cookie (cdr (assoc 'otpCookie first-node)))
(otp-node (cdr (assoc 'otpNode first-node))))
(message "cookie and node: %S\n" (list cookie otp-node))
(list otp-node cookie)))
(defun alk-membase-setup-distel (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(setq derl-cookie otp-cookie)
(setq erl-nodename-cache (intern otp-node))
(setq distel-modeline-node otp-node)
(force-mode-line-update)))
;; (call-interactively 'alk-membase-setup-distel)
(defun alk-membase-shell (username password host port)
(interactive (alk-membase-read-host))
(let* ((rv (alk-membase-grab-node-and-cookie username password host port))
(otp-node (car rv))
(otp-cookie (cadr rv)))
(message "cookie and node: %S\n" (list otp-cookie otp-node))
(unless (and otp-node otp-cookie)
(error "Failed to grap node name and cookie"))
(let ((inferior-erlang-machine-options `("-setcookie" ,otp-cookie
"-name" "membasectl@127.0.0.1" "-hidden"
,@inferior-erlang-machine-options)))
(run-erlang)
(let ((proc (get-buffer-process (current-buffer))))
(comint-send-string proc (format "net_kernel:set_net_ticktime(rpc:call('%s', net_kernel, get_net_ticktime, [])).\n" otp-node))
(sleep-for 0.1)
(comint-send-string proc "")
(sleep-for 0.1)
(comint-send-string proc (concat "r '" otp-node "'\n"))
(sleep-for 0.1)
(comint-send-string proc (concat "c 2\n"))))))
|
[
{
"context": "lexical-binding: t -*-\n\n;; Copyright (C) 2021-2022 Debanjum Singh Solanky\n\n;; Author: Debanjum Singh Solanky <debanjum AT g",
"end": 142,
"score": 0.999891459941864,
"start": 120,
"tag": "NAME",
"value": "Debanjum Singh Solanky"
},
{
"context": "t (C) 2021-2022 Debanjum Singh Solanky\n\n;; Author: Debanjum Singh Solanky <debanjum AT gmail DOT com>\n;; Description: Gener",
"end": 177,
"score": 0.999891996383667,
"start": 155,
"tag": "NAME",
"value": "Debanjum Singh Solanky"
},
{
"context": "gh Solanky\n\n;; Author: Debanjum Singh Solanky <debanjum AT gmail DOT com>\n;; Description: Generate code",
"end": 185,
"score": 0.5384224653244019,
"start": 182,
"tag": "EMAIL",
"value": "anj"
},
{
"context": "ires: ((emacs \"25.1\"))\n;; URL: https://github.com/debanjum/codex-completion\n\n;; This file is NOT part of GNU",
"end": 419,
"score": 0.7863909602165222,
"start": 411,
"tag": "USERNAME",
"value": "debanjum"
}
] | codex-completion.el | debanjum/codex-completion | 7 | ;;; codex-completion.el --- OpenAI Codex powered Code Completion -*- lexical-binding: t -*-
;; Copyright (C) 2021-2022 Debanjum Singh Solanky
;; Author: Debanjum Singh Solanky <debanjum AT gmail DOT com>
;; Description: Generate code from program description and code
;; Keywords: abbrev, matching, auto-complete, programming
;; Version: 0.1.0
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/debanjum/codex-completion
;; This file is NOT part of GNU Emacs.
;;; License:
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package enables code generation, completion using Codex by OpenAI
;; The models code generation capabilities are exposed via an HTTP API
;; Pass instructions as code, code comments, code skeleton or a combination
;; The model will generate code based on your instructions
;;; Code:
(require 'json)
(require 'url)
(require 'url-http)
(defvar url-http-end-of-headers)
(defcustom codex-completion-openai-api-token nil
"Token to access the OpenAI API."
:group 'codex-completion
:type 'string)
(defcustom codex-completion-openai-api-url "https://api.openai.com/v1/engines/davinci-codex/completions"
"URL to access the specific OpenAI Model."
:group 'codex-completion
:type 'string)
(defun codex-completion--get-current-paragraph-until-point ()
"Return text from point to previous empty line."
(interactive)
(replace-regexp-in-string
"^[ \t]*\n" ""
(buffer-substring-no-properties
(point)
(save-excursion
(backward-paragraph)
(point)))))
(defun codex-completion--get-completion-from-api ()
"Call OpenAI API and return suggested completion from response"
(car
(with-current-buffer
(url-retrieve-synchronously
codex-completion-openai-api-url)
(goto-char url-http-end-of-headers)
;; extract completion from response
(codex-completion--get-completions-from-response (json-read)))))
(defun codex-completion--get-completions-from-response (json)
"Get the completion suggestions from the json response"
(let ((completions (cdr (assoc 'choices json))))
(mapcar (lambda (completion)
(cdr (assoc 'text completion)))
completions)))
;;;###autoload
(defun codex-complete-region (beginning end)
"Query OpenAI Codex to generate code taking current region as context"
(interactive "r")
(let* ((region (buffer-substring-no-properties beginning end))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,region)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete-query (query)
"Query OpenAI Codex to generate code taking `query` passed by user as context"
(interactive "sQuery: ")
(let* ((query (text-before-previous-empty-line))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,query)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete ()
"Query OpenAI Codex to generate code. Provide current paragraph till point as context"
(interactive)
(let* ((paragraph (codex-completion--get-current-paragraph-until-point))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,paragraph)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
(provide 'codex-completion)
;;; codex-completion.el ends here
| 19328 | ;;; codex-completion.el --- OpenAI Codex powered Code Completion -*- lexical-binding: t -*-
;; Copyright (C) 2021-2022 <NAME>
;; Author: <NAME> <deb<EMAIL>um AT gmail DOT com>
;; Description: Generate code from program description and code
;; Keywords: abbrev, matching, auto-complete, programming
;; Version: 0.1.0
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/debanjum/codex-completion
;; This file is NOT part of GNU Emacs.
;;; License:
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package enables code generation, completion using Codex by OpenAI
;; The models code generation capabilities are exposed via an HTTP API
;; Pass instructions as code, code comments, code skeleton or a combination
;; The model will generate code based on your instructions
;;; Code:
(require 'json)
(require 'url)
(require 'url-http)
(defvar url-http-end-of-headers)
(defcustom codex-completion-openai-api-token nil
"Token to access the OpenAI API."
:group 'codex-completion
:type 'string)
(defcustom codex-completion-openai-api-url "https://api.openai.com/v1/engines/davinci-codex/completions"
"URL to access the specific OpenAI Model."
:group 'codex-completion
:type 'string)
(defun codex-completion--get-current-paragraph-until-point ()
"Return text from point to previous empty line."
(interactive)
(replace-regexp-in-string
"^[ \t]*\n" ""
(buffer-substring-no-properties
(point)
(save-excursion
(backward-paragraph)
(point)))))
(defun codex-completion--get-completion-from-api ()
"Call OpenAI API and return suggested completion from response"
(car
(with-current-buffer
(url-retrieve-synchronously
codex-completion-openai-api-url)
(goto-char url-http-end-of-headers)
;; extract completion from response
(codex-completion--get-completions-from-response (json-read)))))
(defun codex-completion--get-completions-from-response (json)
"Get the completion suggestions from the json response"
(let ((completions (cdr (assoc 'choices json))))
(mapcar (lambda (completion)
(cdr (assoc 'text completion)))
completions)))
;;;###autoload
(defun codex-complete-region (beginning end)
"Query OpenAI Codex to generate code taking current region as context"
(interactive "r")
(let* ((region (buffer-substring-no-properties beginning end))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,region)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete-query (query)
"Query OpenAI Codex to generate code taking `query` passed by user as context"
(interactive "sQuery: ")
(let* ((query (text-before-previous-empty-line))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,query)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete ()
"Query OpenAI Codex to generate code. Provide current paragraph till point as context"
(interactive)
(let* ((paragraph (codex-completion--get-current-paragraph-until-point))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,paragraph)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
(provide 'codex-completion)
;;; codex-completion.el ends here
| true | ;;; codex-completion.el --- OpenAI Codex powered Code Completion -*- lexical-binding: t -*-
;; Copyright (C) 2021-2022 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <debPI:EMAIL:<EMAIL>END_PIum AT gmail DOT com>
;; Description: Generate code from program description and code
;; Keywords: abbrev, matching, auto-complete, programming
;; Version: 0.1.0
;; Package-Requires: ((emacs "25.1"))
;; URL: https://github.com/debanjum/codex-completion
;; This file is NOT part of GNU Emacs.
;;; License:
;; 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 3
;; of the License, 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package enables code generation, completion using Codex by OpenAI
;; The models code generation capabilities are exposed via an HTTP API
;; Pass instructions as code, code comments, code skeleton or a combination
;; The model will generate code based on your instructions
;;; Code:
(require 'json)
(require 'url)
(require 'url-http)
(defvar url-http-end-of-headers)
(defcustom codex-completion-openai-api-token nil
"Token to access the OpenAI API."
:group 'codex-completion
:type 'string)
(defcustom codex-completion-openai-api-url "https://api.openai.com/v1/engines/davinci-codex/completions"
"URL to access the specific OpenAI Model."
:group 'codex-completion
:type 'string)
(defun codex-completion--get-current-paragraph-until-point ()
"Return text from point to previous empty line."
(interactive)
(replace-regexp-in-string
"^[ \t]*\n" ""
(buffer-substring-no-properties
(point)
(save-excursion
(backward-paragraph)
(point)))))
(defun codex-completion--get-completion-from-api ()
"Call OpenAI API and return suggested completion from response"
(car
(with-current-buffer
(url-retrieve-synchronously
codex-completion-openai-api-url)
(goto-char url-http-end-of-headers)
;; extract completion from response
(codex-completion--get-completions-from-response (json-read)))))
(defun codex-completion--get-completions-from-response (json)
"Get the completion suggestions from the json response"
(let ((completions (cdr (assoc 'choices json))))
(mapcar (lambda (completion)
(cdr (assoc 'text completion)))
completions)))
;;;###autoload
(defun codex-complete-region (beginning end)
"Query OpenAI Codex to generate code taking current region as context"
(interactive "r")
(let* ((region (buffer-substring-no-properties beginning end))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,region)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete-query (query)
"Query OpenAI Codex to generate code taking `query` passed by user as context"
(interactive "sQuery: ")
(let* ((query (text-before-previous-empty-line))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,query)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
;;;###autoload
(defun codex-complete ()
"Query OpenAI Codex to generate code. Provide current paragraph till point as context"
(interactive)
(let* ((paragraph (codex-completion--get-current-paragraph-until-point))
(bearer-token (format "Bearer %s" codex-completion-openai-api-token))
(url-request-method "POST")
(url-request-extra-headers
`(("Content-Type" . "application/json")
("Authorization" . ,bearer-token)))
(url-request-data
(json-encode `(("prompt" . ,paragraph)
("max_tokens" . 64)
("temperature" . 0)
("top_p" . 1)
("frequency_penalty" . 0)
("presence_penalty" . 0)))))
(insert
(codex-completion--get-completion-from-api))))
(provide 'codex-completion)
;;; codex-completion.el ends here
|
[
{
"context": "work right.\n '(custom-safe-themes\n (quote\n (\"2b8dff32b9018d88e24044eb60d8f3829bd6bbeab754e70799b78593af1c3aba\" \"179561378080af1e960d4fef173c0879c77fb4a4ac3569c",
"end": 429,
"score": 0.9638327360153198,
"start": 365,
"tag": "KEY",
"value": "2b8dff32b9018d88e24044eb60d8f3829bd6bbeab754e70799b78593af1c3aba"
},
{
"context": "24044eb60d8f3829bd6bbeab754e70799b78593af1c3aba\" \"179561378080af1e960d4fef173c0879c77fb4a4ac3569c044880f005abfc2be\" \"9b88b8c64dc30188514f19d1be732ee71cc905b04b0c2c7",
"end": 496,
"score": 0.9591354727745056,
"start": 432,
"tag": "KEY",
"value": "179561378080af1e960d4fef173c0879c77fb4a4ac3569c044880f005abfc2be"
},
{
"context": "60d4fef173c0879c77fb4a4ac3569c044880f005abfc2be\" \"9b88b8c64dc30188514f19d1be732ee71cc905b04b0c2c7eb1194528fcebbea4\" \"84d2f9eeb3f82d619ca4bfffe5f157282f4779732f48a5a",
"end": 563,
"score": 0.9880399107933044,
"start": 499,
"tag": "KEY",
"value": "9b88b8c64dc30188514f19d1be732ee71cc905b04b0c2c7eb1194528fcebbea4"
},
{
"context": "14f19d1be732ee71cc905b04b0c2c7eb1194528fcebbea4\" \"84d2f9eeb3f82d619ca4bfffe5f157282f4779732f48a5ac1484d94d5ff5b279\" \"a27c00821ccfd5a78b01e4f35dc056706dd9ede09a8b90c",
"end": 630,
"score": 0.9634190201759338,
"start": 566,
"tag": "KEY",
"value": "84d2f9eeb3f82d619ca4bfffe5f157282f4779732f48a5ac1484d94d5ff5b279"
},
{
"context": "ca4bfffe5f157282f4779732f48a5ac1484d94d5ff5b279\" \"a27c00821ccfd5a78b01e4f35dc056706dd9ede09a8b90c6955ae6a390eb1c1e\" default)))\n '(package-selected-packages\n (quot",
"end": 697,
"score": 0.8965094685554504,
"start": 633,
"tag": "KEY",
"value": "a27c00821ccfd5a78b01e4f35dc056706dd9ede09a8b90c6955ae6a390eb1c1e"
}
] | emacs/init.el | ssoteloserrano/dotfiles | 0 | (org-babel-load-file
(expand-file-name
"config.org"
user-emacs-directory))
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
(quote
("2b8dff32b9018d88e24044eb60d8f3829bd6bbeab754e70799b78593af1c3aba" "179561378080af1e960d4fef173c0879c77fb4a4ac3569c044880f005abfc2be" "9b88b8c64dc30188514f19d1be732ee71cc905b04b0c2c7eb1194528fcebbea4" "84d2f9eeb3f82d619ca4bfffe5f157282f4779732f48a5ac1484d94d5ff5b279" "a27c00821ccfd5a78b01e4f35dc056706dd9ede09a8b90c6955ae6a390eb1c1e" default)))
'(package-selected-packages
(quote
(elpy evil-nerd-commenter ivy-rich counsel ivy peep-dired dired-open all-the-icons-dired sudo-edit emojify gcmh ## projectile dashboard eshell-syntax-highlighting evil-org org-superstar org-bullets general airline-themes smart-mode-line-powerline-theme smart-mode-line evil-commentary doom-themes doom-modeline which-key evil-terminal-cursor-changer afternoon-theme evil-tutor evil-collection evil use-package))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(cursor ((t (:background "brightblack" :foreground "brightgreen"))))
'(mode-line ((t (:background "brightred" :foreground "black" :box nil)))))
| 37648 | (org-babel-load-file
(expand-file-name
"config.org"
user-emacs-directory))
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
(quote
("<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" default)))
'(package-selected-packages
(quote
(elpy evil-nerd-commenter ivy-rich counsel ivy peep-dired dired-open all-the-icons-dired sudo-edit emojify gcmh ## projectile dashboard eshell-syntax-highlighting evil-org org-superstar org-bullets general airline-themes smart-mode-line-powerline-theme smart-mode-line evil-commentary doom-themes doom-modeline which-key evil-terminal-cursor-changer afternoon-theme evil-tutor evil-collection evil use-package))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(cursor ((t (:background "brightblack" :foreground "brightgreen"))))
'(mode-line ((t (:background "brightred" :foreground "black" :box nil)))))
| true | (org-babel-load-file
(expand-file-name
"config.org"
user-emacs-directory))
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(custom-safe-themes
(quote
("PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" default)))
'(package-selected-packages
(quote
(elpy evil-nerd-commenter ivy-rich counsel ivy peep-dired dired-open all-the-icons-dired sudo-edit emojify gcmh ## projectile dashboard eshell-syntax-highlighting evil-org org-superstar org-bullets general airline-themes smart-mode-line-powerline-theme smart-mode-line evil-commentary doom-themes doom-modeline which-key evil-terminal-cursor-changer afternoon-theme evil-tutor evil-collection evil use-package))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(cursor ((t (:background "brightblack" :foreground "brightgreen"))))
'(mode-line ((t (:background "brightred" :foreground "black" :box nil)))))
|
[
{
"context": "ll of my configuration (including org)\n\n;; Author: Aaron Brink <aaronlbrink@gmail.com>\n;; Version: 1.0\n;; Keywor",
"end": 77,
"score": 0.9998063445091248,
"start": 66,
"tag": "NAME",
"value": "Aaron Brink"
},
{
"context": "guration (including org)\n\n;; Author: Aaron Brink <aaronlbrink@gmail.com>\n;; Version: 1.0\n;; Keywords: emacs-config\n;; URL",
"end": 100,
"score": 0.9999327063560486,
"start": 79,
"tag": "EMAIL",
"value": "aaronlbrink@gmail.com"
},
{
"context": "Keywords: emacs-config\n;; URL: https://gitlab.com/aaronlbrink\n\n;;; Commentary:\n;; I still have no idea about so",
"end": 182,
"score": 0.9974445104598999,
"start": 171,
"tag": "USERNAME",
"value": "aaronlbrink"
},
{
"context": "ows collapsable directories\n;; https://github.com/emacsorphanage/direx\n(use-package direx)\n(global-set-key (kbd \"C",
"end": 462,
"score": 0.9701986312866211,
"start": 448,
"tag": "USERNAME",
"value": "emacsorphanage"
},
{
"context": "on* with\n;; C-g at anytime.\n;; https://github.com/emacsorphanage/popwin\n(use-package popwin)\n(popwin-mode 1)\n\n\n(pu",
"end": 902,
"score": 0.93316251039505,
"start": 888,
"tag": "USERNAME",
"value": "emacsorphanage"
},
{
"context": ";; when saving an org file.\n;; https://github.com/jamcha-aa/auto-org-md\n(use-package auto-org-md)\n\n\n;; Show o",
"end": 3885,
"score": 0.9994847178459167,
"start": 3876,
"tag": "USERNAME",
"value": "jamcha-aa"
},
{
"context": "/your todos being displayed\n;; https://github.com/enisozgen/idle-org-agenda\n(use-package idle-org-agenda\n :a",
"end": 4068,
"score": 0.9996222257614136,
"start": 4059,
"tag": "USERNAME",
"value": "enisozgen"
},
{
"context": "; https://editorconfig.org/\n;; https://github.com/editorconfig/editorconfig-emacs\n(use-package editorconfig\n :c",
"end": 4402,
"score": 0.9992804527282715,
"start": 4390,
"tag": "USERNAME",
"value": "editorconfig"
},
{
"context": "requently used M-x commands\n;; https://github.com/nonsequitur/smex\n(use-package smex)\n\n\n;; Simple tools for min",
"end": 5436,
"score": 0.9995133876800537,
"start": 5425,
"tag": "USERNAME",
"value": "nonsequitur"
},
{
"context": "ced alternative to isearch)\n;; https://github.com/abo-abo/swiper (includes all 3)\n(use-package ivy\n :confi",
"end": 5701,
"score": 0.9984543919563293,
"start": 5694,
"tag": "USERNAME",
"value": "abo-abo"
},
{
"context": "k, and projectile packages.\n;; https://github.com/emacs-lsp/lsp-mode\n(use-package lsp-mode\n :hook\n ((prog-m",
"end": 6168,
"score": 0.997183084487915,
"start": 6159,
"tag": "USERNAME",
"value": "emacs-lsp"
},
{
"context": " necessity of this package.\n;; https://github.com/tigersoldier/company-lsp\n(use-package company-lsp)\n \n\n;; Proj",
"end": 6962,
"score": 0.9997093677520752,
"start": 6950,
"tag": "USERNAME",
"value": "tigersoldier"
},
{
"context": "y visited files in project,\n;; https://github.com/bbatsov/projectile\n(use-package projectile\n :config\n (p",
"end": 7311,
"score": 0.999672532081604,
"start": 7304,
"tag": "USERNAME",
"value": "bbatsov"
},
{
"context": " welcome screen\n(setq initial-scratch-message \"Hi, Aaron!\")\n\n(provide 'all)\n;;; all.el ends here\n",
"end": 10965,
"score": 0.9945871829986572,
"start": 10960,
"tag": "NAME",
"value": "Aaron"
}
] | custom/all.el | aaronlbrink/.emacs.d | 0 | ;;; all.el -- all of my configuration (including org)
;; Author: Aaron Brink <aaronlbrink@gmail.com>
;; Version: 1.0
;; Keywords: emacs-config
;; URL: https://gitlab.com/aaronlbrink
;;; Commentary:
;; I still have no idea about some of this stuff.
;;; Code:
(provide 'all)
;;
;; --- Start Customizing Individual Packages ---
;;
;; Simple directory explorer
;; Like VSCode's left panel which shows collapsable directories
;; https://github.com/emacsorphanage/direx
(use-package direx)
(global-set-key (kbd "C-x C-j") 'direx:jump-to-directory)
;; uh, next line exists above..what's the difference between jump-to-directory and
;; jump-to-directory-other-window?
;; (global-set-key (kbd "C-x C-j") 'direx:jump-to-directory-other-window)
;; Popup window manager
;; Allows you to close what should be temporary buffers such as *Completion* with
;; C-g at anytime.
;; https://github.com/emacsorphanage/popwin
(use-package popwin)
(popwin-mode 1)
(push '(direx:direx-mode :position left :width 37 :dedicated t )
popwin:special-display-config)
;; Org mode
;; For notes, TODO lists, and document creation with a plain-text system
;; https://orgmode.org/
(use-package org
:mode (("\\.org$" . org-mode))
:ensure org-plus-contrib
:bind ("M-q" . 'toggle-truncate-lines)
:config
(progn
;; config stuff
(setq org-return-follows-link t)
(setq org-agenda-files '("~/org"))
(setq org-agenda-custom-commands
' (
("H" "Office and Home Lists"
((agenda)
(tags-todo "OFFICE")
(tags-todo "HOME")
(tags-todo "COMPUTER")
(tags-todo "MOVIE")
(tags-todo "READING")))
("D" "Daily Action List"
(
(agenda "" ((org-agenda-ndays 1)
(org-agenda-sorting-strategy
(quote ((agenda time-up priority-down tag-up) )))
(org-deadline-warning-days 0)
))))
)
)
(setq org-refile-targets ' (("work.org" :maxlevel . 4)
("main.org" :maxlevel . 2)
("gtd.org" :maxlevel . 1)
("someday.org" :level . 1)))
)
:hook (
(after-change-major-mode . (lambda() (electric-indent-mode -1)))
)
)
;; org-capture templates
(setq org-capture-templates
'(("t" "Todo" entry (file+headline "~/org/gtd.org" "Tasks")
"* TODO %?\n %i\n %a \nAdded: %U")
("j" "Journal" entry (file+datetree "~/org/journal.org")
"* %?\nEntered on %U\n %i\n %a")
("s" "Todo" entry (file+headline "~/org/someday.org" "Someday")
"* %?\n %i\n %a \nAdded: %U")
)
)
;; org-capture keybindings (these are speedy! no need to use the org template menu to
;; add a capture/note)
(define-key global-map "\C-ct"
(lambda () (interactive) (org-capture nil "t")))
(define-key global-map "\C-cj"
(lambda () (interactive) (org-capture nil "j")))
(define-key global-map "\C-cs"
(lambda () (interactive) (org-capture nil "s")))
;; org-mode requires these (see https://orgmode.org/manual/Activation.html)
;; taking these lines out will cause things like C-c l to return undefined command
(global-set-key (kbd "C-c l") 'org-store-link)
(global-set-key (kbd "C-c a") 'org-agenda)
(global-set-key (kbd "C-c c") 'org-capture)
(global-set-key "\C-ca" 'org-agenda)
(setq org-list-allow-alphabetical t)
;; Org Specific Packages
;; Autocreate Markdown files from org
;; If enabled (M-x auto-org-md-mode), a markdown file will automatically be created
;; when saving an org file.
;; https://github.com/jamcha-aa/auto-org-md
(use-package auto-org-md)
;; Show org-agenda view after timeout
;; Idling in an org-file result in the agenda/your todos being displayed
;; https://github.com/enisozgen/idle-org-agenda
(use-package idle-org-agenda
:after org-agenda
:ensure t
:config (idle-org-agenda-mode))
;; Support .editorconfig files in projects
;; Helps ensure everyone's editor comes to agreement on things like the number
;; of spaces to indent lines, etc.
;; https://editorconfig.org/
;; https://github.com/editorconfig/editorconfig-emacs
(use-package editorconfig
:config
(editorconfig-mode 1))
;; COMPlete ANYthing
;; Text completion framework
;; M-n and M-p to select completions, C-s and C-r and C-o to search through completions
;; https://company-mode.github.io/
(use-package company
:config
(global-company-mode 1))
;; Syntax checking
;; Checks for syntax errors while you type and highlights errors. Also works with Emac's
;; error buffer, which can be viewed to see all errors.
;; M-g n go to next error
;; Language support: https://www.flycheck.org/en/latest/languages.html#flycheck-languages
;; https://www.flycheck.org/en/latest/index.html
(use-package flycheck
:ensure t
:init (global-flycheck-mode)
(progn (setq-default flycheck-emacs-lisp-load-path 'inherit))
)
;; Display fly-check messages inline with code
(use-package flycheck-inline
:config
(with-eval-after-load 'flycheck (global-flycheck-inline-mode)))
;; M-x enhancement
;; Shows recent and frequently used M-x commands
;; https://github.com/nonsequitur/smex
(use-package smex)
;; Simple tools for minibuffer completion
;; Ivy includes 3 subparts: Ivy itself (list completion), Counsel (Ivy-enhanced versions
;; of common Emacs commands, and Swiper (Ivy-enhanced alternative to isearch)
;; https://github.com/abo-abo/swiper (includes all 3)
(use-package ivy
:config
(ivy-mode 1)
:bind* (
("\C-s" . swiper)
("M-x" . counsel-M-x) ; M-x use counsel
("C-x C-f" . counsel-find-file)) ; C-x C-f use counsel-find-file
)
;; Client for Language Server Protocol
;; Adds support for LSP and trys to provide an IDE-like experience with optional integration
;; ability with the popular company, flycheck, and projectile packages.
;; https://github.com/emacs-lsp/lsp-mode
(use-package lsp-mode
:hook
((prog-major-mode . lsp-prog-major-mode-enable)
(lsp-after-open-hook . lsp-enable-imenu)
(prog-mode . lsp))
:config
(setq
lsp-enable-snippet nil))
;; LSP UI stuff. See how to configure useful things:
;; https://emacs-lsp.github.io/lsp-ui/
(use-package lsp-ui
:config
(setq lsp-ui-doc-enable nil
lsp-ui-peek-enable nil
lsp-ui-sideline-enable nil
lsp-ui-imenu-enable nil
lsp-ui-flycheck-enable t)
:hook
(lsp-mode . lsp-ui-mode))
;; Company completion backend for lsp-mode
;; Provides some things like using "." to trigger completion.
;; I need to invest sometime to understand how the LSP framework actually works to really
;; understand the necessity of this package.
;; https://github.com/tigersoldier/company-lsp
(use-package company-lsp)
;; Project interaction library
;; Provides navigation and management features on the project-level. If a directory has
;; a .git directory, then it's a project. Somethings you can do: find files in project,
;; visit project in dired, jump to recently visited files in project,
;; https://github.com/bbatsov/projectile
(use-package projectile
:config
(projectile-mode 1)
:ensure t
:bind-keymap (("C-c p" . projectile-command-map))
)
;;(setq projectile-project-search-path '("/home/aaron/ldev/personal" "/home/aaron/ldev/brinkdevelopmentllc/kyros/"))
;; Web Development Stuff
(add-to-list 'auto-mode-alist '("\\.js\\'" . js-mode))
;; TypeScript configuration
(use-package tide)
(defun setup-tide-mode ()
(interactive)
(tide-setup)
(setq flycheck-check-syntax-automatically '(save mode-enabled))
(eldoc-mode 1)
(tide-hl-identifier-mode +1))
(use-package web-mode
:config
(with-eval-after-load 'tide
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . web-mode))
(add-hook 'web-mode-hook
(lambda ()
(when (string-equal "tsx" (file-name-extension buffer-file-name))
(setup-tide-mode))))
;; enable typescript-tslint checker
(flycheck-add-mode 'typescript-tslint 'web-mode)))
;;
;; --- Theming ---
;;
(load-theme 'misterioso t)
;; Custom Theme ~ab
;; https://www.gnu.org/software/emacs/manual/html_node/emacs/Custom-Themes.html
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(fringe-mode 6 nil (fringe))
'(linum-format 'dynamic)
'(package-archives
'(("gnu" . "http://elpa.gnu.org/packages/")
("melpa-stable" . "https://stable.melpa.org/packages/")
("melpa" . "https://melpa.org/packages/")))
'(package-selected-packages
'(misterioso idle-org-agenda auto-org-md org-plus-contrib monokai-theme sudoku tramp speed-type soothe-theme org-bullets a js2-mode auctex w3m web-mode tide projectile ace-window grandshell-theme alect-themes alect-theme lua-mode boon-qwerty counsel smex ivy lsp-ui flycheck-inline flycheck ido-vertical-mode company-lsp company lsp-mode cherry-blossom-theme editorconfig use-package)))
;; Custom Theme, Typefaces
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:stipple nil :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 130 :width normal :family "Source Code Pro")))))
(set-cursor-color "#aaaaaa")
;;(set-background-color "#282828")
(set-face-foreground 'vertical-border (face-background 'fringe))
(set-face-attribute 'default nil :height 20)
;; For Mac OS X
(when (eq system-type 'darwin)
(set-face-attribute 'default nil :family "Source Code Pro")
;; default font size (point * 10)
;;
;; WARNING! Depending on the default font,
;; if the size is not supported very well, the frame will be clipped
;; so that the beginning of the buffer may not be visible correctly.
(set-face-attribute 'default nil :height 145)
)
;; The theme for company (a plugin) does not get set by Custom.
(require 'color)
(let ((bg (face-attribute 'default :background)))
(custom-set-faces
`(company-scrollbar-bg ((t (:background ,(color-lighten-name bg 10)))))
`(company-scrollbar-fg ((t (:background ,(color-lighten-name bg 5)))))
`(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))
`(company-tooltip-common ((t (:inherit font-lock-constant-face))))))
;; Don't show welcome screen
(setq initial-scratch-message "Hi, Aaron!")
(provide 'all)
;;; all.el ends here
| 52090 | ;;; all.el -- all of my configuration (including org)
;; Author: <NAME> <<EMAIL>>
;; Version: 1.0
;; Keywords: emacs-config
;; URL: https://gitlab.com/aaronlbrink
;;; Commentary:
;; I still have no idea about some of this stuff.
;;; Code:
(provide 'all)
;;
;; --- Start Customizing Individual Packages ---
;;
;; Simple directory explorer
;; Like VSCode's left panel which shows collapsable directories
;; https://github.com/emacsorphanage/direx
(use-package direx)
(global-set-key (kbd "C-x C-j") 'direx:jump-to-directory)
;; uh, next line exists above..what's the difference between jump-to-directory and
;; jump-to-directory-other-window?
;; (global-set-key (kbd "C-x C-j") 'direx:jump-to-directory-other-window)
;; Popup window manager
;; Allows you to close what should be temporary buffers such as *Completion* with
;; C-g at anytime.
;; https://github.com/emacsorphanage/popwin
(use-package popwin)
(popwin-mode 1)
(push '(direx:direx-mode :position left :width 37 :dedicated t )
popwin:special-display-config)
;; Org mode
;; For notes, TODO lists, and document creation with a plain-text system
;; https://orgmode.org/
(use-package org
:mode (("\\.org$" . org-mode))
:ensure org-plus-contrib
:bind ("M-q" . 'toggle-truncate-lines)
:config
(progn
;; config stuff
(setq org-return-follows-link t)
(setq org-agenda-files '("~/org"))
(setq org-agenda-custom-commands
' (
("H" "Office and Home Lists"
((agenda)
(tags-todo "OFFICE")
(tags-todo "HOME")
(tags-todo "COMPUTER")
(tags-todo "MOVIE")
(tags-todo "READING")))
("D" "Daily Action List"
(
(agenda "" ((org-agenda-ndays 1)
(org-agenda-sorting-strategy
(quote ((agenda time-up priority-down tag-up) )))
(org-deadline-warning-days 0)
))))
)
)
(setq org-refile-targets ' (("work.org" :maxlevel . 4)
("main.org" :maxlevel . 2)
("gtd.org" :maxlevel . 1)
("someday.org" :level . 1)))
)
:hook (
(after-change-major-mode . (lambda() (electric-indent-mode -1)))
)
)
;; org-capture templates
(setq org-capture-templates
'(("t" "Todo" entry (file+headline "~/org/gtd.org" "Tasks")
"* TODO %?\n %i\n %a \nAdded: %U")
("j" "Journal" entry (file+datetree "~/org/journal.org")
"* %?\nEntered on %U\n %i\n %a")
("s" "Todo" entry (file+headline "~/org/someday.org" "Someday")
"* %?\n %i\n %a \nAdded: %U")
)
)
;; org-capture keybindings (these are speedy! no need to use the org template menu to
;; add a capture/note)
(define-key global-map "\C-ct"
(lambda () (interactive) (org-capture nil "t")))
(define-key global-map "\C-cj"
(lambda () (interactive) (org-capture nil "j")))
(define-key global-map "\C-cs"
(lambda () (interactive) (org-capture nil "s")))
;; org-mode requires these (see https://orgmode.org/manual/Activation.html)
;; taking these lines out will cause things like C-c l to return undefined command
(global-set-key (kbd "C-c l") 'org-store-link)
(global-set-key (kbd "C-c a") 'org-agenda)
(global-set-key (kbd "C-c c") 'org-capture)
(global-set-key "\C-ca" 'org-agenda)
(setq org-list-allow-alphabetical t)
;; Org Specific Packages
;; Autocreate Markdown files from org
;; If enabled (M-x auto-org-md-mode), a markdown file will automatically be created
;; when saving an org file.
;; https://github.com/jamcha-aa/auto-org-md
(use-package auto-org-md)
;; Show org-agenda view after timeout
;; Idling in an org-file result in the agenda/your todos being displayed
;; https://github.com/enisozgen/idle-org-agenda
(use-package idle-org-agenda
:after org-agenda
:ensure t
:config (idle-org-agenda-mode))
;; Support .editorconfig files in projects
;; Helps ensure everyone's editor comes to agreement on things like the number
;; of spaces to indent lines, etc.
;; https://editorconfig.org/
;; https://github.com/editorconfig/editorconfig-emacs
(use-package editorconfig
:config
(editorconfig-mode 1))
;; COMPlete ANYthing
;; Text completion framework
;; M-n and M-p to select completions, C-s and C-r and C-o to search through completions
;; https://company-mode.github.io/
(use-package company
:config
(global-company-mode 1))
;; Syntax checking
;; Checks for syntax errors while you type and highlights errors. Also works with Emac's
;; error buffer, which can be viewed to see all errors.
;; M-g n go to next error
;; Language support: https://www.flycheck.org/en/latest/languages.html#flycheck-languages
;; https://www.flycheck.org/en/latest/index.html
(use-package flycheck
:ensure t
:init (global-flycheck-mode)
(progn (setq-default flycheck-emacs-lisp-load-path 'inherit))
)
;; Display fly-check messages inline with code
(use-package flycheck-inline
:config
(with-eval-after-load 'flycheck (global-flycheck-inline-mode)))
;; M-x enhancement
;; Shows recent and frequently used M-x commands
;; https://github.com/nonsequitur/smex
(use-package smex)
;; Simple tools for minibuffer completion
;; Ivy includes 3 subparts: Ivy itself (list completion), Counsel (Ivy-enhanced versions
;; of common Emacs commands, and Swiper (Ivy-enhanced alternative to isearch)
;; https://github.com/abo-abo/swiper (includes all 3)
(use-package ivy
:config
(ivy-mode 1)
:bind* (
("\C-s" . swiper)
("M-x" . counsel-M-x) ; M-x use counsel
("C-x C-f" . counsel-find-file)) ; C-x C-f use counsel-find-file
)
;; Client for Language Server Protocol
;; Adds support for LSP and trys to provide an IDE-like experience with optional integration
;; ability with the popular company, flycheck, and projectile packages.
;; https://github.com/emacs-lsp/lsp-mode
(use-package lsp-mode
:hook
((prog-major-mode . lsp-prog-major-mode-enable)
(lsp-after-open-hook . lsp-enable-imenu)
(prog-mode . lsp))
:config
(setq
lsp-enable-snippet nil))
;; LSP UI stuff. See how to configure useful things:
;; https://emacs-lsp.github.io/lsp-ui/
(use-package lsp-ui
:config
(setq lsp-ui-doc-enable nil
lsp-ui-peek-enable nil
lsp-ui-sideline-enable nil
lsp-ui-imenu-enable nil
lsp-ui-flycheck-enable t)
:hook
(lsp-mode . lsp-ui-mode))
;; Company completion backend for lsp-mode
;; Provides some things like using "." to trigger completion.
;; I need to invest sometime to understand how the LSP framework actually works to really
;; understand the necessity of this package.
;; https://github.com/tigersoldier/company-lsp
(use-package company-lsp)
;; Project interaction library
;; Provides navigation and management features on the project-level. If a directory has
;; a .git directory, then it's a project. Somethings you can do: find files in project,
;; visit project in dired, jump to recently visited files in project,
;; https://github.com/bbatsov/projectile
(use-package projectile
:config
(projectile-mode 1)
:ensure t
:bind-keymap (("C-c p" . projectile-command-map))
)
;;(setq projectile-project-search-path '("/home/aaron/ldev/personal" "/home/aaron/ldev/brinkdevelopmentllc/kyros/"))
;; Web Development Stuff
(add-to-list 'auto-mode-alist '("\\.js\\'" . js-mode))
;; TypeScript configuration
(use-package tide)
(defun setup-tide-mode ()
(interactive)
(tide-setup)
(setq flycheck-check-syntax-automatically '(save mode-enabled))
(eldoc-mode 1)
(tide-hl-identifier-mode +1))
(use-package web-mode
:config
(with-eval-after-load 'tide
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . web-mode))
(add-hook 'web-mode-hook
(lambda ()
(when (string-equal "tsx" (file-name-extension buffer-file-name))
(setup-tide-mode))))
;; enable typescript-tslint checker
(flycheck-add-mode 'typescript-tslint 'web-mode)))
;;
;; --- Theming ---
;;
(load-theme 'misterioso t)
;; Custom Theme ~ab
;; https://www.gnu.org/software/emacs/manual/html_node/emacs/Custom-Themes.html
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(fringe-mode 6 nil (fringe))
'(linum-format 'dynamic)
'(package-archives
'(("gnu" . "http://elpa.gnu.org/packages/")
("melpa-stable" . "https://stable.melpa.org/packages/")
("melpa" . "https://melpa.org/packages/")))
'(package-selected-packages
'(misterioso idle-org-agenda auto-org-md org-plus-contrib monokai-theme sudoku tramp speed-type soothe-theme org-bullets a js2-mode auctex w3m web-mode tide projectile ace-window grandshell-theme alect-themes alect-theme lua-mode boon-qwerty counsel smex ivy lsp-ui flycheck-inline flycheck ido-vertical-mode company-lsp company lsp-mode cherry-blossom-theme editorconfig use-package)))
;; Custom Theme, Typefaces
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:stipple nil :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 130 :width normal :family "Source Code Pro")))))
(set-cursor-color "#aaaaaa")
;;(set-background-color "#282828")
(set-face-foreground 'vertical-border (face-background 'fringe))
(set-face-attribute 'default nil :height 20)
;; For Mac OS X
(when (eq system-type 'darwin)
(set-face-attribute 'default nil :family "Source Code Pro")
;; default font size (point * 10)
;;
;; WARNING! Depending on the default font,
;; if the size is not supported very well, the frame will be clipped
;; so that the beginning of the buffer may not be visible correctly.
(set-face-attribute 'default nil :height 145)
)
;; The theme for company (a plugin) does not get set by Custom.
(require 'color)
(let ((bg (face-attribute 'default :background)))
(custom-set-faces
`(company-scrollbar-bg ((t (:background ,(color-lighten-name bg 10)))))
`(company-scrollbar-fg ((t (:background ,(color-lighten-name bg 5)))))
`(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))
`(company-tooltip-common ((t (:inherit font-lock-constant-face))))))
;; Don't show welcome screen
(setq initial-scratch-message "Hi, <NAME>!")
(provide 'all)
;;; all.el ends here
| true | ;;; all.el -- all of my configuration (including org)
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Version: 1.0
;; Keywords: emacs-config
;; URL: https://gitlab.com/aaronlbrink
;;; Commentary:
;; I still have no idea about some of this stuff.
;;; Code:
(provide 'all)
;;
;; --- Start Customizing Individual Packages ---
;;
;; Simple directory explorer
;; Like VSCode's left panel which shows collapsable directories
;; https://github.com/emacsorphanage/direx
(use-package direx)
(global-set-key (kbd "C-x C-j") 'direx:jump-to-directory)
;; uh, next line exists above..what's the difference between jump-to-directory and
;; jump-to-directory-other-window?
;; (global-set-key (kbd "C-x C-j") 'direx:jump-to-directory-other-window)
;; Popup window manager
;; Allows you to close what should be temporary buffers such as *Completion* with
;; C-g at anytime.
;; https://github.com/emacsorphanage/popwin
(use-package popwin)
(popwin-mode 1)
(push '(direx:direx-mode :position left :width 37 :dedicated t )
popwin:special-display-config)
;; Org mode
;; For notes, TODO lists, and document creation with a plain-text system
;; https://orgmode.org/
(use-package org
:mode (("\\.org$" . org-mode))
:ensure org-plus-contrib
:bind ("M-q" . 'toggle-truncate-lines)
:config
(progn
;; config stuff
(setq org-return-follows-link t)
(setq org-agenda-files '("~/org"))
(setq org-agenda-custom-commands
' (
("H" "Office and Home Lists"
((agenda)
(tags-todo "OFFICE")
(tags-todo "HOME")
(tags-todo "COMPUTER")
(tags-todo "MOVIE")
(tags-todo "READING")))
("D" "Daily Action List"
(
(agenda "" ((org-agenda-ndays 1)
(org-agenda-sorting-strategy
(quote ((agenda time-up priority-down tag-up) )))
(org-deadline-warning-days 0)
))))
)
)
(setq org-refile-targets ' (("work.org" :maxlevel . 4)
("main.org" :maxlevel . 2)
("gtd.org" :maxlevel . 1)
("someday.org" :level . 1)))
)
:hook (
(after-change-major-mode . (lambda() (electric-indent-mode -1)))
)
)
;; org-capture templates
(setq org-capture-templates
'(("t" "Todo" entry (file+headline "~/org/gtd.org" "Tasks")
"* TODO %?\n %i\n %a \nAdded: %U")
("j" "Journal" entry (file+datetree "~/org/journal.org")
"* %?\nEntered on %U\n %i\n %a")
("s" "Todo" entry (file+headline "~/org/someday.org" "Someday")
"* %?\n %i\n %a \nAdded: %U")
)
)
;; org-capture keybindings (these are speedy! no need to use the org template menu to
;; add a capture/note)
(define-key global-map "\C-ct"
(lambda () (interactive) (org-capture nil "t")))
(define-key global-map "\C-cj"
(lambda () (interactive) (org-capture nil "j")))
(define-key global-map "\C-cs"
(lambda () (interactive) (org-capture nil "s")))
;; org-mode requires these (see https://orgmode.org/manual/Activation.html)
;; taking these lines out will cause things like C-c l to return undefined command
(global-set-key (kbd "C-c l") 'org-store-link)
(global-set-key (kbd "C-c a") 'org-agenda)
(global-set-key (kbd "C-c c") 'org-capture)
(global-set-key "\C-ca" 'org-agenda)
(setq org-list-allow-alphabetical t)
;; Org Specific Packages
;; Autocreate Markdown files from org
;; If enabled (M-x auto-org-md-mode), a markdown file will automatically be created
;; when saving an org file.
;; https://github.com/jamcha-aa/auto-org-md
(use-package auto-org-md)
;; Show org-agenda view after timeout
;; Idling in an org-file result in the agenda/your todos being displayed
;; https://github.com/enisozgen/idle-org-agenda
(use-package idle-org-agenda
:after org-agenda
:ensure t
:config (idle-org-agenda-mode))
;; Support .editorconfig files in projects
;; Helps ensure everyone's editor comes to agreement on things like the number
;; of spaces to indent lines, etc.
;; https://editorconfig.org/
;; https://github.com/editorconfig/editorconfig-emacs
(use-package editorconfig
:config
(editorconfig-mode 1))
;; COMPlete ANYthing
;; Text completion framework
;; M-n and M-p to select completions, C-s and C-r and C-o to search through completions
;; https://company-mode.github.io/
(use-package company
:config
(global-company-mode 1))
;; Syntax checking
;; Checks for syntax errors while you type and highlights errors. Also works with Emac's
;; error buffer, which can be viewed to see all errors.
;; M-g n go to next error
;; Language support: https://www.flycheck.org/en/latest/languages.html#flycheck-languages
;; https://www.flycheck.org/en/latest/index.html
(use-package flycheck
:ensure t
:init (global-flycheck-mode)
(progn (setq-default flycheck-emacs-lisp-load-path 'inherit))
)
;; Display fly-check messages inline with code
(use-package flycheck-inline
:config
(with-eval-after-load 'flycheck (global-flycheck-inline-mode)))
;; M-x enhancement
;; Shows recent and frequently used M-x commands
;; https://github.com/nonsequitur/smex
(use-package smex)
;; Simple tools for minibuffer completion
;; Ivy includes 3 subparts: Ivy itself (list completion), Counsel (Ivy-enhanced versions
;; of common Emacs commands, and Swiper (Ivy-enhanced alternative to isearch)
;; https://github.com/abo-abo/swiper (includes all 3)
(use-package ivy
:config
(ivy-mode 1)
:bind* (
("\C-s" . swiper)
("M-x" . counsel-M-x) ; M-x use counsel
("C-x C-f" . counsel-find-file)) ; C-x C-f use counsel-find-file
)
;; Client for Language Server Protocol
;; Adds support for LSP and trys to provide an IDE-like experience with optional integration
;; ability with the popular company, flycheck, and projectile packages.
;; https://github.com/emacs-lsp/lsp-mode
(use-package lsp-mode
:hook
((prog-major-mode . lsp-prog-major-mode-enable)
(lsp-after-open-hook . lsp-enable-imenu)
(prog-mode . lsp))
:config
(setq
lsp-enable-snippet nil))
;; LSP UI stuff. See how to configure useful things:
;; https://emacs-lsp.github.io/lsp-ui/
(use-package lsp-ui
:config
(setq lsp-ui-doc-enable nil
lsp-ui-peek-enable nil
lsp-ui-sideline-enable nil
lsp-ui-imenu-enable nil
lsp-ui-flycheck-enable t)
:hook
(lsp-mode . lsp-ui-mode))
;; Company completion backend for lsp-mode
;; Provides some things like using "." to trigger completion.
;; I need to invest sometime to understand how the LSP framework actually works to really
;; understand the necessity of this package.
;; https://github.com/tigersoldier/company-lsp
(use-package company-lsp)
;; Project interaction library
;; Provides navigation and management features on the project-level. If a directory has
;; a .git directory, then it's a project. Somethings you can do: find files in project,
;; visit project in dired, jump to recently visited files in project,
;; https://github.com/bbatsov/projectile
(use-package projectile
:config
(projectile-mode 1)
:ensure t
:bind-keymap (("C-c p" . projectile-command-map))
)
;;(setq projectile-project-search-path '("/home/aaron/ldev/personal" "/home/aaron/ldev/brinkdevelopmentllc/kyros/"))
;; Web Development Stuff
(add-to-list 'auto-mode-alist '("\\.js\\'" . js-mode))
;; TypeScript configuration
(use-package tide)
(defun setup-tide-mode ()
(interactive)
(tide-setup)
(setq flycheck-check-syntax-automatically '(save mode-enabled))
(eldoc-mode 1)
(tide-hl-identifier-mode +1))
(use-package web-mode
:config
(with-eval-after-load 'tide
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . web-mode))
(add-hook 'web-mode-hook
(lambda ()
(when (string-equal "tsx" (file-name-extension buffer-file-name))
(setup-tide-mode))))
;; enable typescript-tslint checker
(flycheck-add-mode 'typescript-tslint 'web-mode)))
;;
;; --- Theming ---
;;
(load-theme 'misterioso t)
;; Custom Theme ~ab
;; https://www.gnu.org/software/emacs/manual/html_node/emacs/Custom-Themes.html
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(fringe-mode 6 nil (fringe))
'(linum-format 'dynamic)
'(package-archives
'(("gnu" . "http://elpa.gnu.org/packages/")
("melpa-stable" . "https://stable.melpa.org/packages/")
("melpa" . "https://melpa.org/packages/")))
'(package-selected-packages
'(misterioso idle-org-agenda auto-org-md org-plus-contrib monokai-theme sudoku tramp speed-type soothe-theme org-bullets a js2-mode auctex w3m web-mode tide projectile ace-window grandshell-theme alect-themes alect-theme lua-mode boon-qwerty counsel smex ivy lsp-ui flycheck-inline flycheck ido-vertical-mode company-lsp company lsp-mode cherry-blossom-theme editorconfig use-package)))
;; Custom Theme, Typefaces
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:stipple nil :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 130 :width normal :family "Source Code Pro")))))
(set-cursor-color "#aaaaaa")
;;(set-background-color "#282828")
(set-face-foreground 'vertical-border (face-background 'fringe))
(set-face-attribute 'default nil :height 20)
;; For Mac OS X
(when (eq system-type 'darwin)
(set-face-attribute 'default nil :family "Source Code Pro")
;; default font size (point * 10)
;;
;; WARNING! Depending on the default font,
;; if the size is not supported very well, the frame will be clipped
;; so that the beginning of the buffer may not be visible correctly.
(set-face-attribute 'default nil :height 145)
)
;; The theme for company (a plugin) does not get set by Custom.
(require 'color)
(let ((bg (face-attribute 'default :background)))
(custom-set-faces
`(company-scrollbar-bg ((t (:background ,(color-lighten-name bg 10)))))
`(company-scrollbar-fg ((t (:background ,(color-lighten-name bg 5)))))
`(company-tooltip-selection ((t (:inherit font-lock-function-name-face))))
`(company-tooltip-common ((t (:inherit font-lock-constant-face))))))
;; Don't show welcome screen
(setq initial-scratch-message "Hi, PI:NAME:<NAME>END_PI!")
(provide 'all)
;;; all.el ends here
|
[
{
"context": "log terms as trees in Emacs\n\n;; Copyright (C) 2020 Markus Triska (triska@metalevel.at)\n\n;; To try it, you need the",
"end": 92,
"score": 0.9998694658279419,
"start": 79,
"tag": "NAME",
"value": "Markus Triska"
},
{
"context": "es in Emacs\n\n;; Copyright (C) 2020 Markus Triska (triska@metalevel.at)\n\n;; To try it, you need the following programs i",
"end": 113,
"score": 0.9999338984489441,
"start": 94,
"tag": "EMAIL",
"value": "triska@metalevel.at"
}
] | tools/showterm.el | Skgland/scryer-prolog | 1,092 | ;;; showterm.el --- Show Prolog terms as trees in Emacs
;; Copyright (C) 2020 Markus Triska (triska@metalevel.at)
;; To try it, you need the following programs installed:
;;
;; - Scryer Prolog
;; - `dot' (from Graphviz)
;; - `convert' (from ImageMagick)
;;
;; Copy showterm.el and showterm.pl to the same directory,
;; say ~/scryer-prolog/tools/, and add to your .emacs:
;;
;; (load "~/scryer-prolog/tools/showterm.el")
;;
;; If necessary, set `scryer-prolog-path' to the Scryer Prolog
;; executable by adding to your .emacs (adapting as appropriate):
;;
;; (setq scryer-prolog-path "/usr/local/bin/scryer-prolog")
;;
;; The function `showterm' draws the Prolog term in the region as a
;; tree. You can invoke it with M-x showterm RET, or for example by
;; binding it to a key in your .emacs, and then pressing that key:
;;
;; (global-set-key [f12] 'showterm)
;;
;; Enjoy!
(defvar scryer-prolog-path
(or (executable-find "scryer-prolog")
"~/scryer-prolog/target/release/scryer-prolog")
"Path of the Scryer Prolog executable.")
(defvar showterm-pl-file
(format "%s%s"
(if load-in-progress
(file-name-directory load-file-name)
default-directory)
"showterm.pl")
"Path to showterm.pl, used to produce a graph as input for `dot'.")
(defvar showterm-pixel-width 500
"Width of the drawn term in pixels.")
(defun showterm (from to)
(interactive "r")
(unless (use-region-p)
(error "No region"))
(let ((str (buffer-substring-no-properties from to))
op-declarations)
(save-excursion
;; rudimentary support for op/3 directives.
(goto-char (point-min))
(while (re-search-forward "^:-[ \t]*\\(op(.*,.*,.*)[ \t]*\\.\\).*$" nil t)
(push (match-string 1) op-declarations))
(setq op-declarations (reverse op-declarations)))
(with-temp-buffer
(set-buffer-multibyte nil)
(let ((proc (start-process "scryer-showterm" (current-buffer)
scryer-prolog-path
showterm-pl-file)))
(showterm-wait-for-prompt)
(while op-declarations
(send-string proc (format "%s\n" (pop op-declarations)))
(showterm-wait-for-prompt))
(send-string proc (concat "dot, halt.\n" str " .\n"))
(showterm-wait-for-process proc t)
(setq str (buffer-string)))
(erase-buffer)
(let ((proc (start-process "dot" (current-buffer) "dot"
"-Gdpi=300"
"-T" "png")))
(send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc)
(setq str (buffer-string))
(erase-buffer))
(let ((proc (let (process-connection-type)
(start-process "convert" (current-buffer)
"convert"
"png:-"
"-gravity" "center"
"-background" "white"
"-scale" (format "%dx%d"
showterm-pixel-width
showterm-pixel-width)
"-extent" (format "%dx" showterm-pixel-width)
"png:-"))))
(process-send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc))
(let ((img (create-image (buffer-string) 'png t))
(fit-window-to-buffer-horizontally t)
(buf (get-buffer-create "term-tree")))
(with-current-buffer buf
(erase-buffer)
(setq mode-line-format ""
cursor-in-non-selected-windows nil)
(insert-image img)
(insert "\n"))
(fit-window-to-buffer (display-buffer-in-side-window buf '((side . right))))))))
(defun showterm-wait-for-prompt ()
(let ((str (regexp-quote "?- "))
seen)
(while (not seen)
(accept-process-output nil 0.01)
(save-excursion
(move-beginning-of-line nil)
(setq seen (looking-at str))))
(erase-buffer)))
(defun showterm-wait-for-process (proc &optional check-for-error)
(set-process-sentinel proc (lambda (proc event)))
(while (eq (process-status proc) 'run)
(accept-process-output nil 0.1)
(when check-for-error
(goto-char (point-min))
(when (looking-at "caught: error(syntax_error")
(delete-process proc)
(error "Syntax error, term cannot be displayed")))))
| 24666 | ;;; showterm.el --- Show Prolog terms as trees in Emacs
;; Copyright (C) 2020 <NAME> (<EMAIL>)
;; To try it, you need the following programs installed:
;;
;; - Scryer Prolog
;; - `dot' (from Graphviz)
;; - `convert' (from ImageMagick)
;;
;; Copy showterm.el and showterm.pl to the same directory,
;; say ~/scryer-prolog/tools/, and add to your .emacs:
;;
;; (load "~/scryer-prolog/tools/showterm.el")
;;
;; If necessary, set `scryer-prolog-path' to the Scryer Prolog
;; executable by adding to your .emacs (adapting as appropriate):
;;
;; (setq scryer-prolog-path "/usr/local/bin/scryer-prolog")
;;
;; The function `showterm' draws the Prolog term in the region as a
;; tree. You can invoke it with M-x showterm RET, or for example by
;; binding it to a key in your .emacs, and then pressing that key:
;;
;; (global-set-key [f12] 'showterm)
;;
;; Enjoy!
(defvar scryer-prolog-path
(or (executable-find "scryer-prolog")
"~/scryer-prolog/target/release/scryer-prolog")
"Path of the Scryer Prolog executable.")
(defvar showterm-pl-file
(format "%s%s"
(if load-in-progress
(file-name-directory load-file-name)
default-directory)
"showterm.pl")
"Path to showterm.pl, used to produce a graph as input for `dot'.")
(defvar showterm-pixel-width 500
"Width of the drawn term in pixels.")
(defun showterm (from to)
(interactive "r")
(unless (use-region-p)
(error "No region"))
(let ((str (buffer-substring-no-properties from to))
op-declarations)
(save-excursion
;; rudimentary support for op/3 directives.
(goto-char (point-min))
(while (re-search-forward "^:-[ \t]*\\(op(.*,.*,.*)[ \t]*\\.\\).*$" nil t)
(push (match-string 1) op-declarations))
(setq op-declarations (reverse op-declarations)))
(with-temp-buffer
(set-buffer-multibyte nil)
(let ((proc (start-process "scryer-showterm" (current-buffer)
scryer-prolog-path
showterm-pl-file)))
(showterm-wait-for-prompt)
(while op-declarations
(send-string proc (format "%s\n" (pop op-declarations)))
(showterm-wait-for-prompt))
(send-string proc (concat "dot, halt.\n" str " .\n"))
(showterm-wait-for-process proc t)
(setq str (buffer-string)))
(erase-buffer)
(let ((proc (start-process "dot" (current-buffer) "dot"
"-Gdpi=300"
"-T" "png")))
(send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc)
(setq str (buffer-string))
(erase-buffer))
(let ((proc (let (process-connection-type)
(start-process "convert" (current-buffer)
"convert"
"png:-"
"-gravity" "center"
"-background" "white"
"-scale" (format "%dx%d"
showterm-pixel-width
showterm-pixel-width)
"-extent" (format "%dx" showterm-pixel-width)
"png:-"))))
(process-send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc))
(let ((img (create-image (buffer-string) 'png t))
(fit-window-to-buffer-horizontally t)
(buf (get-buffer-create "term-tree")))
(with-current-buffer buf
(erase-buffer)
(setq mode-line-format ""
cursor-in-non-selected-windows nil)
(insert-image img)
(insert "\n"))
(fit-window-to-buffer (display-buffer-in-side-window buf '((side . right))))))))
(defun showterm-wait-for-prompt ()
(let ((str (regexp-quote "?- "))
seen)
(while (not seen)
(accept-process-output nil 0.01)
(save-excursion
(move-beginning-of-line nil)
(setq seen (looking-at str))))
(erase-buffer)))
(defun showterm-wait-for-process (proc &optional check-for-error)
(set-process-sentinel proc (lambda (proc event)))
(while (eq (process-status proc) 'run)
(accept-process-output nil 0.1)
(when check-for-error
(goto-char (point-min))
(when (looking-at "caught: error(syntax_error")
(delete-process proc)
(error "Syntax error, term cannot be displayed")))))
| true | ;;; showterm.el --- Show Prolog terms as trees in Emacs
;; Copyright (C) 2020 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;; To try it, you need the following programs installed:
;;
;; - Scryer Prolog
;; - `dot' (from Graphviz)
;; - `convert' (from ImageMagick)
;;
;; Copy showterm.el and showterm.pl to the same directory,
;; say ~/scryer-prolog/tools/, and add to your .emacs:
;;
;; (load "~/scryer-prolog/tools/showterm.el")
;;
;; If necessary, set `scryer-prolog-path' to the Scryer Prolog
;; executable by adding to your .emacs (adapting as appropriate):
;;
;; (setq scryer-prolog-path "/usr/local/bin/scryer-prolog")
;;
;; The function `showterm' draws the Prolog term in the region as a
;; tree. You can invoke it with M-x showterm RET, or for example by
;; binding it to a key in your .emacs, and then pressing that key:
;;
;; (global-set-key [f12] 'showterm)
;;
;; Enjoy!
(defvar scryer-prolog-path
(or (executable-find "scryer-prolog")
"~/scryer-prolog/target/release/scryer-prolog")
"Path of the Scryer Prolog executable.")
(defvar showterm-pl-file
(format "%s%s"
(if load-in-progress
(file-name-directory load-file-name)
default-directory)
"showterm.pl")
"Path to showterm.pl, used to produce a graph as input for `dot'.")
(defvar showterm-pixel-width 500
"Width of the drawn term in pixels.")
(defun showterm (from to)
(interactive "r")
(unless (use-region-p)
(error "No region"))
(let ((str (buffer-substring-no-properties from to))
op-declarations)
(save-excursion
;; rudimentary support for op/3 directives.
(goto-char (point-min))
(while (re-search-forward "^:-[ \t]*\\(op(.*,.*,.*)[ \t]*\\.\\).*$" nil t)
(push (match-string 1) op-declarations))
(setq op-declarations (reverse op-declarations)))
(with-temp-buffer
(set-buffer-multibyte nil)
(let ((proc (start-process "scryer-showterm" (current-buffer)
scryer-prolog-path
showterm-pl-file)))
(showterm-wait-for-prompt)
(while op-declarations
(send-string proc (format "%s\n" (pop op-declarations)))
(showterm-wait-for-prompt))
(send-string proc (concat "dot, halt.\n" str " .\n"))
(showterm-wait-for-process proc t)
(setq str (buffer-string)))
(erase-buffer)
(let ((proc (start-process "dot" (current-buffer) "dot"
"-Gdpi=300"
"-T" "png")))
(send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc)
(setq str (buffer-string))
(erase-buffer))
(let ((proc (let (process-connection-type)
(start-process "convert" (current-buffer)
"convert"
"png:-"
"-gravity" "center"
"-background" "white"
"-scale" (format "%dx%d"
showterm-pixel-width
showterm-pixel-width)
"-extent" (format "%dx" showterm-pixel-width)
"png:-"))))
(process-send-string proc str)
(process-send-eof proc)
(showterm-wait-for-process proc))
(let ((img (create-image (buffer-string) 'png t))
(fit-window-to-buffer-horizontally t)
(buf (get-buffer-create "term-tree")))
(with-current-buffer buf
(erase-buffer)
(setq mode-line-format ""
cursor-in-non-selected-windows nil)
(insert-image img)
(insert "\n"))
(fit-window-to-buffer (display-buffer-in-side-window buf '((side . right))))))))
(defun showterm-wait-for-prompt ()
(let ((str (regexp-quote "?- "))
seen)
(while (not seen)
(accept-process-output nil 0.01)
(save-excursion
(move-beginning-of-line nil)
(setq seen (looking-at str))))
(erase-buffer)))
(defun showterm-wait-for-process (proc &optional check-for-error)
(set-process-sentinel proc (lambda (proc event)))
(while (eq (process-status proc) 'run)
(accept-process-output nil 0.1)
(when check-for-error
(goto-char (point-min))
(when (looking-at "caught: error(syntax_error")
(delete-process proc)
(error "Syntax error, term cannot be displayed")))))
|
[
{
"context": "eric portions of EMPI\n\n;; Copyright (C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>",
"end": 85,
"score": 0.9998714327812195,
"start": 75,
"tag": "NAME",
"value": "R.Ramkumar"
},
{
"context": " Copyright (C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>\n;; Created: \t12 May 200",
"end": 109,
"score": 0.9998821020126343,
"start": 99,
"tag": "NAME",
"value": "R.Ramkumar"
},
{
"context": "C) 2004, 2005 R.Ramkumar\n\n;; Author: \tR.Ramkumar <andyetitmoves@gmail.com>\n;; Created: \t12 May 2004\n;; Version: \t1.0\n;; Key",
"end": 134,
"score": 0.9999266862869263,
"start": 111,
"tag": "EMAIL",
"value": "andyetitmoves@gmail.com"
},
{
"context": " this\n;; program's author (send electronic mail to andyetitmoves@gmail.com)\n;; or from the Free Software Foundation, Inc.,\n;",
"end": 880,
"score": 0.9999285936355591,
"start": 857,
"tag": "EMAIL",
"value": "andyetitmoves@gmail.com"
}
] | elisp/empi/empi-core.el | andyetitmoves/dot-files | 1 | ;;; EMPI-CORE.EL --- Generic portions of EMPI
;; Copyright (C) 2004, 2005 R.Ramkumar
;; Author: R.Ramkumar <andyetitmoves@gmail.com>
;; Created: 12 May 2004
;; Version: 1.0
;; Keywords: empi, music
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to andyetitmoves@gmail.com)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; This is EMPI, or The Emacs Media Player Interface, a generic package to
;; interface any media player with Emacs and make it offer its services through
;; an unified interface written in Emacs Lisp. An obvious question which comes
;; to one's mind is "why this package when there are plenty of packages around
;; enabling one to play music in emacs?". True, there are, but most of them have
;; their limitations. The most common limitation is that the interfacing is done
;; to a specific player, usually mpg123 or mpg321. This means that the user is
;; tied to that player, and believe me, people have strong preferences regarding
;; this. This indicates a clear lack of extensibility, as someone has to write a
;; few thousand lines of code everytime a new player comes up. Further,
;; obviously, there is no unified user interface for all these packages. Instead
;; of nitpicking at other packages, it would be better to see the features of
;; EMPI, they provide a good overview of the motivation behind this package.
;; Central to EMPI is a framework which brokers the communication between user
;; interface code and backends communicating with a particular resource. The UI
;; code asks for information or requests action from the framework which
;; forwards the same to the appropriate backend. As a result, EMPI is totally
;; transparent towards how the backend operates, it could be through an external
;; process or even some other lisp package. This means that one could as well
;; drive the other media player packages through EMPI.
;; EMPI operates on a set of "players", each of which have a few "handlers". A
;; command or a query is passed to each of the handlers of the "active player"
;; chosen by the user, till a favourable response is obtained. For example, for
;; the "xmms" player, you could have a handler for the small command-line
;; interface provided by xmms itself, a handler using "xmms-shell" - a more
;; sophisticated command line interface to xmms, as well as a handler employing
;; lisp code to communicate with the control socket of xmms.
;; If you are now thinking that the entire headache is now transferred to the
;; backends for which one has to write lots of lisp code, there are a few
;; generic backends to chose from, like "empi-proc" for communicating through
;; the command-line, which reduces creating a backend for a specific player to
;; writing some tens of lines of rc file like (and perhaps cryptic) code.
;; EMPI is also indifferent towards what the command or query requested. This
;; means that the end user code could even ask for the
;; :kiss-the-butterfly-fluttering-through-the-next-street action provided the
;; backend supports it. This is significant for two aspects - One, EMPI doesn't
;; restrict its functionality to the common subset of all the features of its
;; backends. The end code could ask for some specialized action offered by one
;; odd program, and then gracefully degrade if that action is not
;; supported. Second, as I have been pretending all this while, this isn't just
;; an interface for *media players*, it could be so for anything else as
;; well. Only that instead of an `empi-play' or an `empi-pause', you would have
;; some other function using the framework. Of course, the framework isn't just
;; a dumb forwarder, it does a lot of other things as well...
;; Ok, if you are tired or lost reading this rant, here comes the concrete
;; part. As you would have known by now, just loading this file won't get you
;; anywhere. You would have all these nice looking interactive functions at your
;; disposal, and all would return an "Unsupported or failed action ..."
;; error. Get the backends for the players you have - there are a few shipped
;; for the most common ones, but you might have to get it from somewhere or
;; write one yourselves, or fall back on what has been the bane of other
;; packages - get a program for which the backend exists. You don't need to be a
;; lisp guru to write backends, if you know lisp just a bit beyond blindly
;; pasting that brackety stuff from the commentary of packages to your .emacs,
;; you should be through. And if you do happen to write a backend, do mail it to
;; me, so that I could include it in the distribution.
;; First get the EMPI and the backend files somewhere on the load path. From
;; there on, customizing the `empi' group should take you all the way. A vital
;; customization is the `empi-player-alist'. This is where you declare your
;; players and string together the handlers required. There should be a symbol
;; typically named as empi-playername-backendname provided by each backend
;; package. This is the handler symbol. You will typically need to know the
;; handler symbols and the files where they are declared.
;; Its a good idea, though not necessary, to keep empi-forward as the last
;; handler for each player. This is a generic handler which tries to convert an
;; unhandled command to something else, hoping that the new command would be
;; handled. For example, it would change an unsupported :voladd action,
;; requesting for a addition in volume, to two commands :qvolume, querying for
;; the current volume, and :volume asking for the volume to be set to some
;; value. But do ensure that this is the *last* handler in the list.
;; The order of handlers is important for the fact that this is the order in
;; which support for a specific command is queried. Typically, one should keep
;; the one that does the job well and does it fast, ahead in the list. It isn't
;; necessary for the one handling the most commands to come first, as if there
;; are commands in it which no other handler handles, control would anyway come
;; to it. If there is a handler which executes the only command it handles
;; extremely fast, you could position it higher up.
;; Use `empi-initial-backends' to load the backends which define the
;; backends. Also ensure that you select the default player. The default is to
;; select the first player in the list after telling you about that. Note that
;; there might be some initialisation required by the backends as well, like for
;; example, specifying the hostname and port number, if a backend operates
;; through a network connection. You can also get some of the modes, like the
;; `empi-caption-mode', to display a constantly updated media caption in the
;; title bar, started using the customization interface.
;;; Code:
(defconst empi-version "1.0")
;;;; User serviceable area
(defgroup empi nil
"The Emacs Media Player Interface"
:prefix "empi-"
:link '(emacs-commentary-link :tag "Introduction to EMPI" "empi-core")
:group 'multimedia :group 'external)
(defcustom empi-initial-backends nil
"The list of backends required at startup by EMPI.
This list is usually decided by the handlers in `empi-player-alist'.
Each element of the list needs to be feature to be provided by a file with a
similar filename on the load path. See `require' for more details.
Do not set this variable directly, use the customization interface instead."
:type '(repeat (symbol :tag "Feature"))
:group 'empi :set '(lambda (sym val)
(eval-after-load "empi" `(mapc 'require (quote ,val)))
(set sym val)))
(defun empi-player-alist-custom-friendly (val conv)
(let ((cur val) item)
(while cur
(setq item (cdr-safe (car-safe cur)))
(while item
(cond
((eq conv 'get)
(or (listp (car-safe item)) (setcar item (list (car item)))))
((eq conv 'set)
(and (listp (car-safe item)) (not (cdr-safe (car item)))
(setcar item (caar item)))))
(setq item (cdr-safe item)))
(setq cur (cdr-safe cur))) val))
(defcustom empi-player-alist nil
"Alist of players and their corresponding handlers for EMPI.
Each of the elements in the alist has the player name as the car and a list of
handlers as the cdr. Each handler is either the symbol containing the function
to call as its value, or a list. In the first case, the handler is given a
chance to handle any action. In the second case, the first element of the list
is the name of the symbol, and the elements following are action symbols for
which this handler is used. It is advised to keep `empi-forwarder' as the last
handler for all players."
:type
'(repeat
(list :format " %v"
(string :tag "Name")
(repeat :inline t :tag "Handler List"
:value (empi-forwarder)
(list :format "%v"
:value (empi-)
(symbol :tag "Symbol")
(set :inline t :format "%v"
(list :inline t :format "%v"
(const :format "" :restrict)
(repeat :tag "Selective Actions"
(symbol :format "%v" :value :))))))))
:get '(lambda (sym)
(empi-player-alist-custom-friendly (symbol-value sym) 'get))
:set '(lambda (sym val)
(set sym (empi-player-alist-custom-friendly val 'set)))
:group 'empi)
(put 'empi-player-alist 'custom-tag
(substitute-command-keys
"Empi Player Alist: This variable has no sane default.
This always needs to be specified. To know more about this variable, read the
package commentary using `\\[finder-commentary] empi-core'.
See {srcdir}/cust-eg.html for an example customization."))
(defcustom empi-default-player nil
"*The default player used for all EMPI actions.
Should be one of the values defined by `empi-player-alist'. The current player
used can be modified by a call to `empi-select-player'."
:type '(choice (const :tag "First in list" nil)
(string :tag "Player name")) :group 'empi)
;;;; Utility functions
(defmacro oconcat (&rest args)
(let (actual (str "") item)
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual)))))
(defalias 'oconcat 'concat)
(defun byte-compile-oconcat (form)
(let (actual (str "") item (args (cdr form)))
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(byte-compile-form
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual))))))
(put 'oconcat 'byte-compile 'byte-compile-oconcat)
(or (fboundp 'warn)
(defmacro warn (&rest args)
`(message (oconcat "Warning: " ,@args))))
(defmacro serror (str)
`(signal 'error (list ,str)))
(defmacro emperet (str)
`(serror (oconcat "Unexpected result on " ,str " query")))
(defmacro empuns (str)
`(serror (oconcat "Unsupported or failed action " ,str)))
(defmacro empuns-nf (str)
`(progn
(message (oconcat "Warning: Unsupported or failed action " ,str)) nil))
(defun list-alternate (l)
(if (listp l)
(if l
(append (list (list (symbol-name (car l))))
(list-alternate (cdr (cdr l)))))
(error "Argument is not a list")))
(defsubst plist-keys (sym)
(list-alternate (symbol-plist sym)))
(defun walk-white (str begin &optional rev)
(if (or (= (elt str begin) ? )
(= (elt str begin) ?\n)
(= (elt str begin) ?\t)
(= (elt str begin) ?\v))
(if (if rev (> begin 0) (< begin (1- (length str))))
(walk-white str (+ begin (if rev -1 1)) rev))
begin))
(defun trim-string (str)
(if (= (length str) 0) ""
(let ((nwbeg (walk-white str 0)))
(if nwbeg
(substring str nwbeg (1+ (walk-white str (1- (length str)) t))) ""))))
(eval-and-compile
(defmacro with-unlogged-message (&rest args)
`(let ,(list
(if (boundp 'log-message-filter-function)
'(log-message-filter-function #'ignore)
'(message-log-max nil))) ,@args))
(defmacro unlogged-message (&rest args)
`(with-unlogged-message
(message ,@args))))
(defun define-keys (map &rest args)
(while (cadr args)
(define-key map (car args) (cadr args))
(setq args (cddr args))))
(defun gcd-2 (a b)
(let (temp)
(while (not (= b 0))
(setq temp a a b b (mod temp a)))) a)
(defmacro with-critical-lock (lock &rest body)
"Lock the enclosing code with LOCK against re-entrancy.
LOCK is evaluated thrice in this process."
`(unless (intern-soft ,lock)
(intern ,lock)
(unwind-protect
(progn ,@body)
(unintern ,lock))))
(put 'with-critical-lock 'lisp-indent-function 1)
(def-edebug-spec with-critical-lock t)
;;;; Core commands
(defvar empi-current-player nil)
;;;###autoload
(defun empi-select-player (pname)
(interactive
(list
(if (and (listp empi-player-alist) (> (length empi-player-alist) 0))
(completing-read
(concat "Enter player name"
(if (and empi-current-player (listp empi-current-player))
(concat " (" (car empi-current-player) ")")) ": ")
empi-player-alist nil t nil nil (car empi-current-player))
(error "No players available"))))
(let ((newp (assoc pname empi-player-alist)))
(if newp
(if (listp (cdr newp))
(setq empi-current-player newp)
(error "The handler list for the player specified is invalid, \
please check your settings"))
(error "The player specified does not exist"))))
(defun empi-ensure-current-player ()
(when (not empi-current-player)
(if (stringp empi-default-player)
(empi-select-player empi-default-player)
(if (listp empi-player-alist)
(if (= (length empi-player-alist) 0)
(error "No players available")
(message "No default player, defaulting to first player in list")
(setq empi-current-player (car empi-player-alist)))
(error "Invalid player alist")))))
(defvar empi-forwarder-chain nil)
(defun empi-command (cmd &rest args)
(empi-ensure-current-player)
(if (not (listp (cdr empi-current-player)))
(error "Invalid player entry %s" (car empi-current-player))
(let ((htail (cdr empi-current-player)) ret func cur)
(setq empi-forwarder-chain (list cmd))
(while (and htail (not ret))
(setq cur (car htail))
(and (listp cur)
(setq cur (and (let ((restrict (plist-get (cdr cur) :restrict)))
(or (not restrict) (memq cmd restrict)))
(car cur))))
(when cur
(if (and (symbolp cur) (functionp (setq func (symbol-value cur))))
(setq ret (apply func cur cmd args))
(warn "Invalid handler found for player "
(car empi-current-player) ", ignoring")))
(setq htail (cdr htail)))
(setq empi-forwarder-chain nil) ret)))
(defun empi-forward (cmd command-func &rest args)
(or empi-forwarder-chain (error "No forwarder chain present"))
(unless (memq cmd empi-forwarder-chain)
(setq empi-forwarder-chain (cons cmd empi-forwarder-chain))
(let (retval)
(unwind-protect
(setq retval (apply command-func cmd args))
(setq empi-forwarder-chain (cdr-safe empi-forwarder-chain)))
retval)))
;;;; Cache support
(defvar empi-global-cache nil)
(defvar empi-cache-lock 0)
(defvar empi-query-dependencies nil)
(defun empi-add-dependency (query &rest actions)
(mapc '(lambda (item)
(let ((val (plist-get empi-query-dependencies item)))
(if val (or (memq query val) (setcdr val (cons query (cdr val))))
(setq empi-query-dependencies
(plist-put empi-query-dependencies item (list query))))))
actions))
(defalias 'empi-static-dep 'empi-add-dependency)
(defun empi-uncache (&rest keys)
(mapc
'(lambda (item)
(setq empi-global-cache (plist-put empi-global-cache item nil))) keys))
(defun empi-merge-command (cmd &rest args)
(setq args (apply 'empi-command cmd args))
(if (listp args)
(let ((ftail args) necdr
(necessary (plist-get empi-query-dependencies cmd)))
(if necessary
(setq necessary (append necessary (list cmd)))
(setq necessary (list cmd)))
(while ftail
(setq necessary (delq (car ftail) necessary))
(and (symbolp (car ftail)) (cadr ftail)
(setq empi-global-cache (plist-put empi-global-cache (car ftail)
(cadr ftail))))
(setq ftail (cddr ftail)))
(apply 'empi-uncache necessary)
(plist-get empi-global-cache cmd))
(apply 'empi-uncache (plist-get empi-query-dependencies cmd))
(setq empi-global-cache (plist-put empi-global-cache cmd args)) args))
(defun empi-cached-command (cmd &rest args)
(or (plist-get empi-global-cache cmd)
(apply 'empi-merge-command cmd args)))
(defsubst empi-clear-cache () (setq empi-global-cache nil))
(defmacro with-empi-cache-group-by (group &rest body)
`(unwind-protect
,`(,@group
(if (= empi-cache-lock 0) (empi-clear-cache))
(setq empi-cache-lock (1+ empi-cache-lock))
,@body)
(setq empi-cache-lock (1- empi-cache-lock))))
;;;; Convenience macros/aliases
(eval-when-compile (require 'edebug))
(defmacro with-empi-cache (&rest body)
`(with-empi-cache-group-by (progn) ,@body))
(put 'with-empi-cache 'lisp-indent-function 0)
(def-edebug-spec with-empi-cache (body))
(defmacro with-empi-cache-let (vars &rest body)
`(with-empi-cache-group-by ,`(let ,vars) ,@body))
(put 'with-empi-cache-let 'lisp-indent-function 1)
(def-edebug-spec with-empi-cache-let let)
(defalias 'empi-query 'empi-cached-command)
(defalias 'empi-action 'empi-merge-command)
(defmacro empi-forward-command (cmd &rest args)
`(empi-forward ,cmd 'empi-command ,@args))
(defmacro empi-forward-query (cmd &rest args)
`(empi-forward ,cmd 'empi-query ,@args))
(defmacro empi-forward-action (cmd &rest args)
`(empi-forward ,cmd 'empi-action ,@args))
(defmacro empi-symbol-name (sym)
(if (symbolp sym)
(symbol-name sym)
(list 'symbol-name sym)))
(defmacro empi-simple-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-recov-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
;;;; Display update support
(defvar empi-update-list nil)
(defvar empi-update-timer nil)
(defvar empi-update-disable nil)
(defvar empi-update-schedule nil)
(defvar empi-update-schedule-pos nil)
;; Redeclared with defcustom, this is to silence the compiler.
(defvar empi-update-reference-interval)
(defun empi-update-build-schedule (list)
(let* ((length (/ (aref empi-update-timer 2) (aref empi-update-timer 1)))
(ring (make-list length nil)) (ringpos 0) ringptr interval)
(while list
(setq ringptr ring interval (/ length (aref (car list) 1)))
(while ringptr
(and (zerop ringpos)
(setcar ringptr (cons (aref (car list) 0) (car ringptr))))
(if (= (setq ringpos (1+ ringpos)) interval) (setq ringpos 0))
(setq ringptr (cdr ringptr)))
(setq list (cdr list))) ring))
(defun empi-update-timer-handler ()
(with-critical-lock "empi-update-timer-handler-lock"
;; If there's a command already running, don't poke your nose in...
;; This is a bit paranoid, but nobody guarantees a timer event anyway :)
(unless empi-forwarder-chain
(with-empi-cache
(mapc
'(lambda (item)
(condition-case err
(funcall item)
(error
(message "empi-update: error in timer function%s: %s"
(if (symbolp item) (concat " " (symbol-name item)) "")
(error-message-string err))
;;; Disabling removal of handler on error...Undecided design issue.
;;; (setcar empi-update-schedule-pos
;;; (delete item (car empi-update-schedule-pos)))
)))
(car empi-update-schedule-pos)))
(setq empi-update-schedule-pos
(or (cdr empi-update-schedule-pos) empi-update-schedule)))))
(defun empi-update-stop ()
(when (aref empi-update-timer 0)
(cancel-timer (aref empi-update-timer 0))
(aset empi-update-timer 0 nil)))
(defun empi-update-start (&optional rebuild)
(when empi-update-timer
(empi-update-stop)
(and rebuild (setq empi-update-schedule
(empi-update-build-schedule empi-update-list)))
(setq empi-update-schedule-pos empi-update-schedule)
(aset empi-update-timer 0
(run-at-time nil
(/ empi-update-reference-interval
(float (aref empi-update-timer 2)))
'empi-update-timer-handler))))
(defvar empi-update-register-notrigger nil)
(defun empi-update-register (func scale deps)
(or (and (wholenump scale) (not (zerop scale)) (functionp func))
(error "Invalid scale value"))
(if empi-update-timer
(let ((olcm (aref empi-update-timer 2)))
(aset empi-update-timer 1 (gcd-2 (aref empi-update-timer 1) scale))
(aset empi-update-timer 2 (* (/ olcm (gcd-2 olcm scale)) scale)))
(setq empi-update-timer (vector nil scale scale)))
(setq empi-update-list (cons (vector func scale deps) empi-update-list))
(or empi-update-register-notrigger (empi-update-start t))
(car empi-update-list))
(defun empi-update-ref-p (obj)
(and (vectorp obj) (= (length obj) 3)))
(defmacro combine-empi-update-registers (&rest body)
`(let ((empi-update-register-notrigger t) res)
(unwind-protect
(setq res (progn ,@body))
(empi-update-start t) res)))
(defun gcd-lcm-n (a &rest args)
(setq a (aref a 1))
(let ((lcm a) item)
(while args
(setq item (aref (car args) 1)
a (gcd-2 a item)
lcm (* (/ lcm (gcd-2 lcm item)) item))
(setq args (cdr args)))
(cons a lcm)))
(defun empi-update-unregister (obj)
(setq empi-update-list (delq obj empi-update-list))
(if empi-update-list
;; Maybe merge gcd-lcm-n to use specifically here
(let ((gcd-lcm-n (apply 'gcd-lcm-n empi-update-list)))
(aset empi-update-timer 1 (car gcd-lcm-n))
(aset empi-update-timer 2 (cdr gcd-lcm-n))
(empi-update-start t))
(empi-update-stop)
(setq empi-update-timer nil)))
(define-widget 'wholenum 'restricted-sexp
"Whole number type"
:tag "Whole number" :value 0 :size 10
:type-error "This field should contain a whole number"
:match-alternatives '(wholenump))
(define-widget 'natnum 'restricted-sexp
"Natural number type"
:tag "Natural number" :match-alternatives '(natnump) :value 1 :size 10
:type-error "This field must contain a natural number")
(defun positive-nump (val) (> val 0))
(define-widget 'posnum 'restricted-sexp
"Positive number type"
:tag "Positive number" :match-alternatives '(positive-nump) :value 1 :size 10
:type-error "This field must contain a positive number")
(defcustom empi-update-reference-interval 1
"Reference interval for timed action in the EMPI system.
Various timed actions in EMPI use a factor of this value as the interval between
successive executions."
:type 'posnum :set '(lambda (var val)
(set var val)
(empi-update-start)) :group 'empi)
(provide 'empi-core)
;;; EMPI-CORE.EL ends here
| 40599 | ;;; EMPI-CORE.EL --- Generic portions of EMPI
;; Copyright (C) 2004, 2005 <NAME>
;; Author: <NAME> <<EMAIL>>
;; Created: 12 May 2004
;; Version: 1.0
;; Keywords: empi, music
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to <EMAIL>)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; This is EMPI, or The Emacs Media Player Interface, a generic package to
;; interface any media player with Emacs and make it offer its services through
;; an unified interface written in Emacs Lisp. An obvious question which comes
;; to one's mind is "why this package when there are plenty of packages around
;; enabling one to play music in emacs?". True, there are, but most of them have
;; their limitations. The most common limitation is that the interfacing is done
;; to a specific player, usually mpg123 or mpg321. This means that the user is
;; tied to that player, and believe me, people have strong preferences regarding
;; this. This indicates a clear lack of extensibility, as someone has to write a
;; few thousand lines of code everytime a new player comes up. Further,
;; obviously, there is no unified user interface for all these packages. Instead
;; of nitpicking at other packages, it would be better to see the features of
;; EMPI, they provide a good overview of the motivation behind this package.
;; Central to EMPI is a framework which brokers the communication between user
;; interface code and backends communicating with a particular resource. The UI
;; code asks for information or requests action from the framework which
;; forwards the same to the appropriate backend. As a result, EMPI is totally
;; transparent towards how the backend operates, it could be through an external
;; process or even some other lisp package. This means that one could as well
;; drive the other media player packages through EMPI.
;; EMPI operates on a set of "players", each of which have a few "handlers". A
;; command or a query is passed to each of the handlers of the "active player"
;; chosen by the user, till a favourable response is obtained. For example, for
;; the "xmms" player, you could have a handler for the small command-line
;; interface provided by xmms itself, a handler using "xmms-shell" - a more
;; sophisticated command line interface to xmms, as well as a handler employing
;; lisp code to communicate with the control socket of xmms.
;; If you are now thinking that the entire headache is now transferred to the
;; backends for which one has to write lots of lisp code, there are a few
;; generic backends to chose from, like "empi-proc" for communicating through
;; the command-line, which reduces creating a backend for a specific player to
;; writing some tens of lines of rc file like (and perhaps cryptic) code.
;; EMPI is also indifferent towards what the command or query requested. This
;; means that the end user code could even ask for the
;; :kiss-the-butterfly-fluttering-through-the-next-street action provided the
;; backend supports it. This is significant for two aspects - One, EMPI doesn't
;; restrict its functionality to the common subset of all the features of its
;; backends. The end code could ask for some specialized action offered by one
;; odd program, and then gracefully degrade if that action is not
;; supported. Second, as I have been pretending all this while, this isn't just
;; an interface for *media players*, it could be so for anything else as
;; well. Only that instead of an `empi-play' or an `empi-pause', you would have
;; some other function using the framework. Of course, the framework isn't just
;; a dumb forwarder, it does a lot of other things as well...
;; Ok, if you are tired or lost reading this rant, here comes the concrete
;; part. As you would have known by now, just loading this file won't get you
;; anywhere. You would have all these nice looking interactive functions at your
;; disposal, and all would return an "Unsupported or failed action ..."
;; error. Get the backends for the players you have - there are a few shipped
;; for the most common ones, but you might have to get it from somewhere or
;; write one yourselves, or fall back on what has been the bane of other
;; packages - get a program for which the backend exists. You don't need to be a
;; lisp guru to write backends, if you know lisp just a bit beyond blindly
;; pasting that brackety stuff from the commentary of packages to your .emacs,
;; you should be through. And if you do happen to write a backend, do mail it to
;; me, so that I could include it in the distribution.
;; First get the EMPI and the backend files somewhere on the load path. From
;; there on, customizing the `empi' group should take you all the way. A vital
;; customization is the `empi-player-alist'. This is where you declare your
;; players and string together the handlers required. There should be a symbol
;; typically named as empi-playername-backendname provided by each backend
;; package. This is the handler symbol. You will typically need to know the
;; handler symbols and the files where they are declared.
;; Its a good idea, though not necessary, to keep empi-forward as the last
;; handler for each player. This is a generic handler which tries to convert an
;; unhandled command to something else, hoping that the new command would be
;; handled. For example, it would change an unsupported :voladd action,
;; requesting for a addition in volume, to two commands :qvolume, querying for
;; the current volume, and :volume asking for the volume to be set to some
;; value. But do ensure that this is the *last* handler in the list.
;; The order of handlers is important for the fact that this is the order in
;; which support for a specific command is queried. Typically, one should keep
;; the one that does the job well and does it fast, ahead in the list. It isn't
;; necessary for the one handling the most commands to come first, as if there
;; are commands in it which no other handler handles, control would anyway come
;; to it. If there is a handler which executes the only command it handles
;; extremely fast, you could position it higher up.
;; Use `empi-initial-backends' to load the backends which define the
;; backends. Also ensure that you select the default player. The default is to
;; select the first player in the list after telling you about that. Note that
;; there might be some initialisation required by the backends as well, like for
;; example, specifying the hostname and port number, if a backend operates
;; through a network connection. You can also get some of the modes, like the
;; `empi-caption-mode', to display a constantly updated media caption in the
;; title bar, started using the customization interface.
;;; Code:
(defconst empi-version "1.0")
;;;; User serviceable area
(defgroup empi nil
"The Emacs Media Player Interface"
:prefix "empi-"
:link '(emacs-commentary-link :tag "Introduction to EMPI" "empi-core")
:group 'multimedia :group 'external)
(defcustom empi-initial-backends nil
"The list of backends required at startup by EMPI.
This list is usually decided by the handlers in `empi-player-alist'.
Each element of the list needs to be feature to be provided by a file with a
similar filename on the load path. See `require' for more details.
Do not set this variable directly, use the customization interface instead."
:type '(repeat (symbol :tag "Feature"))
:group 'empi :set '(lambda (sym val)
(eval-after-load "empi" `(mapc 'require (quote ,val)))
(set sym val)))
(defun empi-player-alist-custom-friendly (val conv)
(let ((cur val) item)
(while cur
(setq item (cdr-safe (car-safe cur)))
(while item
(cond
((eq conv 'get)
(or (listp (car-safe item)) (setcar item (list (car item)))))
((eq conv 'set)
(and (listp (car-safe item)) (not (cdr-safe (car item)))
(setcar item (caar item)))))
(setq item (cdr-safe item)))
(setq cur (cdr-safe cur))) val))
(defcustom empi-player-alist nil
"Alist of players and their corresponding handlers for EMPI.
Each of the elements in the alist has the player name as the car and a list of
handlers as the cdr. Each handler is either the symbol containing the function
to call as its value, or a list. In the first case, the handler is given a
chance to handle any action. In the second case, the first element of the list
is the name of the symbol, and the elements following are action symbols for
which this handler is used. It is advised to keep `empi-forwarder' as the last
handler for all players."
:type
'(repeat
(list :format " %v"
(string :tag "Name")
(repeat :inline t :tag "Handler List"
:value (empi-forwarder)
(list :format "%v"
:value (empi-)
(symbol :tag "Symbol")
(set :inline t :format "%v"
(list :inline t :format "%v"
(const :format "" :restrict)
(repeat :tag "Selective Actions"
(symbol :format "%v" :value :))))))))
:get '(lambda (sym)
(empi-player-alist-custom-friendly (symbol-value sym) 'get))
:set '(lambda (sym val)
(set sym (empi-player-alist-custom-friendly val 'set)))
:group 'empi)
(put 'empi-player-alist 'custom-tag
(substitute-command-keys
"Empi Player Alist: This variable has no sane default.
This always needs to be specified. To know more about this variable, read the
package commentary using `\\[finder-commentary] empi-core'.
See {srcdir}/cust-eg.html for an example customization."))
(defcustom empi-default-player nil
"*The default player used for all EMPI actions.
Should be one of the values defined by `empi-player-alist'. The current player
used can be modified by a call to `empi-select-player'."
:type '(choice (const :tag "First in list" nil)
(string :tag "Player name")) :group 'empi)
;;;; Utility functions
(defmacro oconcat (&rest args)
(let (actual (str "") item)
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual)))))
(defalias 'oconcat 'concat)
(defun byte-compile-oconcat (form)
(let (actual (str "") item (args (cdr form)))
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(byte-compile-form
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual))))))
(put 'oconcat 'byte-compile 'byte-compile-oconcat)
(or (fboundp 'warn)
(defmacro warn (&rest args)
`(message (oconcat "Warning: " ,@args))))
(defmacro serror (str)
`(signal 'error (list ,str)))
(defmacro emperet (str)
`(serror (oconcat "Unexpected result on " ,str " query")))
(defmacro empuns (str)
`(serror (oconcat "Unsupported or failed action " ,str)))
(defmacro empuns-nf (str)
`(progn
(message (oconcat "Warning: Unsupported or failed action " ,str)) nil))
(defun list-alternate (l)
(if (listp l)
(if l
(append (list (list (symbol-name (car l))))
(list-alternate (cdr (cdr l)))))
(error "Argument is not a list")))
(defsubst plist-keys (sym)
(list-alternate (symbol-plist sym)))
(defun walk-white (str begin &optional rev)
(if (or (= (elt str begin) ? )
(= (elt str begin) ?\n)
(= (elt str begin) ?\t)
(= (elt str begin) ?\v))
(if (if rev (> begin 0) (< begin (1- (length str))))
(walk-white str (+ begin (if rev -1 1)) rev))
begin))
(defun trim-string (str)
(if (= (length str) 0) ""
(let ((nwbeg (walk-white str 0)))
(if nwbeg
(substring str nwbeg (1+ (walk-white str (1- (length str)) t))) ""))))
(eval-and-compile
(defmacro with-unlogged-message (&rest args)
`(let ,(list
(if (boundp 'log-message-filter-function)
'(log-message-filter-function #'ignore)
'(message-log-max nil))) ,@args))
(defmacro unlogged-message (&rest args)
`(with-unlogged-message
(message ,@args))))
(defun define-keys (map &rest args)
(while (cadr args)
(define-key map (car args) (cadr args))
(setq args (cddr args))))
(defun gcd-2 (a b)
(let (temp)
(while (not (= b 0))
(setq temp a a b b (mod temp a)))) a)
(defmacro with-critical-lock (lock &rest body)
"Lock the enclosing code with LOCK against re-entrancy.
LOCK is evaluated thrice in this process."
`(unless (intern-soft ,lock)
(intern ,lock)
(unwind-protect
(progn ,@body)
(unintern ,lock))))
(put 'with-critical-lock 'lisp-indent-function 1)
(def-edebug-spec with-critical-lock t)
;;;; Core commands
(defvar empi-current-player nil)
;;;###autoload
(defun empi-select-player (pname)
(interactive
(list
(if (and (listp empi-player-alist) (> (length empi-player-alist) 0))
(completing-read
(concat "Enter player name"
(if (and empi-current-player (listp empi-current-player))
(concat " (" (car empi-current-player) ")")) ": ")
empi-player-alist nil t nil nil (car empi-current-player))
(error "No players available"))))
(let ((newp (assoc pname empi-player-alist)))
(if newp
(if (listp (cdr newp))
(setq empi-current-player newp)
(error "The handler list for the player specified is invalid, \
please check your settings"))
(error "The player specified does not exist"))))
(defun empi-ensure-current-player ()
(when (not empi-current-player)
(if (stringp empi-default-player)
(empi-select-player empi-default-player)
(if (listp empi-player-alist)
(if (= (length empi-player-alist) 0)
(error "No players available")
(message "No default player, defaulting to first player in list")
(setq empi-current-player (car empi-player-alist)))
(error "Invalid player alist")))))
(defvar empi-forwarder-chain nil)
(defun empi-command (cmd &rest args)
(empi-ensure-current-player)
(if (not (listp (cdr empi-current-player)))
(error "Invalid player entry %s" (car empi-current-player))
(let ((htail (cdr empi-current-player)) ret func cur)
(setq empi-forwarder-chain (list cmd))
(while (and htail (not ret))
(setq cur (car htail))
(and (listp cur)
(setq cur (and (let ((restrict (plist-get (cdr cur) :restrict)))
(or (not restrict) (memq cmd restrict)))
(car cur))))
(when cur
(if (and (symbolp cur) (functionp (setq func (symbol-value cur))))
(setq ret (apply func cur cmd args))
(warn "Invalid handler found for player "
(car empi-current-player) ", ignoring")))
(setq htail (cdr htail)))
(setq empi-forwarder-chain nil) ret)))
(defun empi-forward (cmd command-func &rest args)
(or empi-forwarder-chain (error "No forwarder chain present"))
(unless (memq cmd empi-forwarder-chain)
(setq empi-forwarder-chain (cons cmd empi-forwarder-chain))
(let (retval)
(unwind-protect
(setq retval (apply command-func cmd args))
(setq empi-forwarder-chain (cdr-safe empi-forwarder-chain)))
retval)))
;;;; Cache support
(defvar empi-global-cache nil)
(defvar empi-cache-lock 0)
(defvar empi-query-dependencies nil)
(defun empi-add-dependency (query &rest actions)
(mapc '(lambda (item)
(let ((val (plist-get empi-query-dependencies item)))
(if val (or (memq query val) (setcdr val (cons query (cdr val))))
(setq empi-query-dependencies
(plist-put empi-query-dependencies item (list query))))))
actions))
(defalias 'empi-static-dep 'empi-add-dependency)
(defun empi-uncache (&rest keys)
(mapc
'(lambda (item)
(setq empi-global-cache (plist-put empi-global-cache item nil))) keys))
(defun empi-merge-command (cmd &rest args)
(setq args (apply 'empi-command cmd args))
(if (listp args)
(let ((ftail args) necdr
(necessary (plist-get empi-query-dependencies cmd)))
(if necessary
(setq necessary (append necessary (list cmd)))
(setq necessary (list cmd)))
(while ftail
(setq necessary (delq (car ftail) necessary))
(and (symbolp (car ftail)) (cadr ftail)
(setq empi-global-cache (plist-put empi-global-cache (car ftail)
(cadr ftail))))
(setq ftail (cddr ftail)))
(apply 'empi-uncache necessary)
(plist-get empi-global-cache cmd))
(apply 'empi-uncache (plist-get empi-query-dependencies cmd))
(setq empi-global-cache (plist-put empi-global-cache cmd args)) args))
(defun empi-cached-command (cmd &rest args)
(or (plist-get empi-global-cache cmd)
(apply 'empi-merge-command cmd args)))
(defsubst empi-clear-cache () (setq empi-global-cache nil))
(defmacro with-empi-cache-group-by (group &rest body)
`(unwind-protect
,`(,@group
(if (= empi-cache-lock 0) (empi-clear-cache))
(setq empi-cache-lock (1+ empi-cache-lock))
,@body)
(setq empi-cache-lock (1- empi-cache-lock))))
;;;; Convenience macros/aliases
(eval-when-compile (require 'edebug))
(defmacro with-empi-cache (&rest body)
`(with-empi-cache-group-by (progn) ,@body))
(put 'with-empi-cache 'lisp-indent-function 0)
(def-edebug-spec with-empi-cache (body))
(defmacro with-empi-cache-let (vars &rest body)
`(with-empi-cache-group-by ,`(let ,vars) ,@body))
(put 'with-empi-cache-let 'lisp-indent-function 1)
(def-edebug-spec with-empi-cache-let let)
(defalias 'empi-query 'empi-cached-command)
(defalias 'empi-action 'empi-merge-command)
(defmacro empi-forward-command (cmd &rest args)
`(empi-forward ,cmd 'empi-command ,@args))
(defmacro empi-forward-query (cmd &rest args)
`(empi-forward ,cmd 'empi-query ,@args))
(defmacro empi-forward-action (cmd &rest args)
`(empi-forward ,cmd 'empi-action ,@args))
(defmacro empi-symbol-name (sym)
(if (symbolp sym)
(symbol-name sym)
(list 'symbol-name sym)))
(defmacro empi-simple-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-recov-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
;;;; Display update support
(defvar empi-update-list nil)
(defvar empi-update-timer nil)
(defvar empi-update-disable nil)
(defvar empi-update-schedule nil)
(defvar empi-update-schedule-pos nil)
;; Redeclared with defcustom, this is to silence the compiler.
(defvar empi-update-reference-interval)
(defun empi-update-build-schedule (list)
(let* ((length (/ (aref empi-update-timer 2) (aref empi-update-timer 1)))
(ring (make-list length nil)) (ringpos 0) ringptr interval)
(while list
(setq ringptr ring interval (/ length (aref (car list) 1)))
(while ringptr
(and (zerop ringpos)
(setcar ringptr (cons (aref (car list) 0) (car ringptr))))
(if (= (setq ringpos (1+ ringpos)) interval) (setq ringpos 0))
(setq ringptr (cdr ringptr)))
(setq list (cdr list))) ring))
(defun empi-update-timer-handler ()
(with-critical-lock "empi-update-timer-handler-lock"
;; If there's a command already running, don't poke your nose in...
;; This is a bit paranoid, but nobody guarantees a timer event anyway :)
(unless empi-forwarder-chain
(with-empi-cache
(mapc
'(lambda (item)
(condition-case err
(funcall item)
(error
(message "empi-update: error in timer function%s: %s"
(if (symbolp item) (concat " " (symbol-name item)) "")
(error-message-string err))
;;; Disabling removal of handler on error...Undecided design issue.
;;; (setcar empi-update-schedule-pos
;;; (delete item (car empi-update-schedule-pos)))
)))
(car empi-update-schedule-pos)))
(setq empi-update-schedule-pos
(or (cdr empi-update-schedule-pos) empi-update-schedule)))))
(defun empi-update-stop ()
(when (aref empi-update-timer 0)
(cancel-timer (aref empi-update-timer 0))
(aset empi-update-timer 0 nil)))
(defun empi-update-start (&optional rebuild)
(when empi-update-timer
(empi-update-stop)
(and rebuild (setq empi-update-schedule
(empi-update-build-schedule empi-update-list)))
(setq empi-update-schedule-pos empi-update-schedule)
(aset empi-update-timer 0
(run-at-time nil
(/ empi-update-reference-interval
(float (aref empi-update-timer 2)))
'empi-update-timer-handler))))
(defvar empi-update-register-notrigger nil)
(defun empi-update-register (func scale deps)
(or (and (wholenump scale) (not (zerop scale)) (functionp func))
(error "Invalid scale value"))
(if empi-update-timer
(let ((olcm (aref empi-update-timer 2)))
(aset empi-update-timer 1 (gcd-2 (aref empi-update-timer 1) scale))
(aset empi-update-timer 2 (* (/ olcm (gcd-2 olcm scale)) scale)))
(setq empi-update-timer (vector nil scale scale)))
(setq empi-update-list (cons (vector func scale deps) empi-update-list))
(or empi-update-register-notrigger (empi-update-start t))
(car empi-update-list))
(defun empi-update-ref-p (obj)
(and (vectorp obj) (= (length obj) 3)))
(defmacro combine-empi-update-registers (&rest body)
`(let ((empi-update-register-notrigger t) res)
(unwind-protect
(setq res (progn ,@body))
(empi-update-start t) res)))
(defun gcd-lcm-n (a &rest args)
(setq a (aref a 1))
(let ((lcm a) item)
(while args
(setq item (aref (car args) 1)
a (gcd-2 a item)
lcm (* (/ lcm (gcd-2 lcm item)) item))
(setq args (cdr args)))
(cons a lcm)))
(defun empi-update-unregister (obj)
(setq empi-update-list (delq obj empi-update-list))
(if empi-update-list
;; Maybe merge gcd-lcm-n to use specifically here
(let ((gcd-lcm-n (apply 'gcd-lcm-n empi-update-list)))
(aset empi-update-timer 1 (car gcd-lcm-n))
(aset empi-update-timer 2 (cdr gcd-lcm-n))
(empi-update-start t))
(empi-update-stop)
(setq empi-update-timer nil)))
(define-widget 'wholenum 'restricted-sexp
"Whole number type"
:tag "Whole number" :value 0 :size 10
:type-error "This field should contain a whole number"
:match-alternatives '(wholenump))
(define-widget 'natnum 'restricted-sexp
"Natural number type"
:tag "Natural number" :match-alternatives '(natnump) :value 1 :size 10
:type-error "This field must contain a natural number")
(defun positive-nump (val) (> val 0))
(define-widget 'posnum 'restricted-sexp
"Positive number type"
:tag "Positive number" :match-alternatives '(positive-nump) :value 1 :size 10
:type-error "This field must contain a positive number")
(defcustom empi-update-reference-interval 1
"Reference interval for timed action in the EMPI system.
Various timed actions in EMPI use a factor of this value as the interval between
successive executions."
:type 'posnum :set '(lambda (var val)
(set var val)
(empi-update-start)) :group 'empi)
(provide 'empi-core)
;;; EMPI-CORE.EL ends here
| true | ;;; EMPI-CORE.EL --- Generic portions of EMPI
;; Copyright (C) 2004, 2005 PI:NAME:<NAME>END_PI
;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Created: 12 May 2004
;; Version: 1.0
;; Keywords: empi, music
;; This file is (strangely) *NOT* part of GNU Emacs
;; 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.
;; A copy of the GNU General Public License can be obtained from this
;; program's author (send electronic mail to PI:EMAIL:<EMAIL>END_PI)
;; or from the Free Software Foundation, Inc.,
;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;; Commentary:
;; This is EMPI, or The Emacs Media Player Interface, a generic package to
;; interface any media player with Emacs and make it offer its services through
;; an unified interface written in Emacs Lisp. An obvious question which comes
;; to one's mind is "why this package when there are plenty of packages around
;; enabling one to play music in emacs?". True, there are, but most of them have
;; their limitations. The most common limitation is that the interfacing is done
;; to a specific player, usually mpg123 or mpg321. This means that the user is
;; tied to that player, and believe me, people have strong preferences regarding
;; this. This indicates a clear lack of extensibility, as someone has to write a
;; few thousand lines of code everytime a new player comes up. Further,
;; obviously, there is no unified user interface for all these packages. Instead
;; of nitpicking at other packages, it would be better to see the features of
;; EMPI, they provide a good overview of the motivation behind this package.
;; Central to EMPI is a framework which brokers the communication between user
;; interface code and backends communicating with a particular resource. The UI
;; code asks for information or requests action from the framework which
;; forwards the same to the appropriate backend. As a result, EMPI is totally
;; transparent towards how the backend operates, it could be through an external
;; process or even some other lisp package. This means that one could as well
;; drive the other media player packages through EMPI.
;; EMPI operates on a set of "players", each of which have a few "handlers". A
;; command or a query is passed to each of the handlers of the "active player"
;; chosen by the user, till a favourable response is obtained. For example, for
;; the "xmms" player, you could have a handler for the small command-line
;; interface provided by xmms itself, a handler using "xmms-shell" - a more
;; sophisticated command line interface to xmms, as well as a handler employing
;; lisp code to communicate with the control socket of xmms.
;; If you are now thinking that the entire headache is now transferred to the
;; backends for which one has to write lots of lisp code, there are a few
;; generic backends to chose from, like "empi-proc" for communicating through
;; the command-line, which reduces creating a backend for a specific player to
;; writing some tens of lines of rc file like (and perhaps cryptic) code.
;; EMPI is also indifferent towards what the command or query requested. This
;; means that the end user code could even ask for the
;; :kiss-the-butterfly-fluttering-through-the-next-street action provided the
;; backend supports it. This is significant for two aspects - One, EMPI doesn't
;; restrict its functionality to the common subset of all the features of its
;; backends. The end code could ask for some specialized action offered by one
;; odd program, and then gracefully degrade if that action is not
;; supported. Second, as I have been pretending all this while, this isn't just
;; an interface for *media players*, it could be so for anything else as
;; well. Only that instead of an `empi-play' or an `empi-pause', you would have
;; some other function using the framework. Of course, the framework isn't just
;; a dumb forwarder, it does a lot of other things as well...
;; Ok, if you are tired or lost reading this rant, here comes the concrete
;; part. As you would have known by now, just loading this file won't get you
;; anywhere. You would have all these nice looking interactive functions at your
;; disposal, and all would return an "Unsupported or failed action ..."
;; error. Get the backends for the players you have - there are a few shipped
;; for the most common ones, but you might have to get it from somewhere or
;; write one yourselves, or fall back on what has been the bane of other
;; packages - get a program for which the backend exists. You don't need to be a
;; lisp guru to write backends, if you know lisp just a bit beyond blindly
;; pasting that brackety stuff from the commentary of packages to your .emacs,
;; you should be through. And if you do happen to write a backend, do mail it to
;; me, so that I could include it in the distribution.
;; First get the EMPI and the backend files somewhere on the load path. From
;; there on, customizing the `empi' group should take you all the way. A vital
;; customization is the `empi-player-alist'. This is where you declare your
;; players and string together the handlers required. There should be a symbol
;; typically named as empi-playername-backendname provided by each backend
;; package. This is the handler symbol. You will typically need to know the
;; handler symbols and the files where they are declared.
;; Its a good idea, though not necessary, to keep empi-forward as the last
;; handler for each player. This is a generic handler which tries to convert an
;; unhandled command to something else, hoping that the new command would be
;; handled. For example, it would change an unsupported :voladd action,
;; requesting for a addition in volume, to two commands :qvolume, querying for
;; the current volume, and :volume asking for the volume to be set to some
;; value. But do ensure that this is the *last* handler in the list.
;; The order of handlers is important for the fact that this is the order in
;; which support for a specific command is queried. Typically, one should keep
;; the one that does the job well and does it fast, ahead in the list. It isn't
;; necessary for the one handling the most commands to come first, as if there
;; are commands in it which no other handler handles, control would anyway come
;; to it. If there is a handler which executes the only command it handles
;; extremely fast, you could position it higher up.
;; Use `empi-initial-backends' to load the backends which define the
;; backends. Also ensure that you select the default player. The default is to
;; select the first player in the list after telling you about that. Note that
;; there might be some initialisation required by the backends as well, like for
;; example, specifying the hostname and port number, if a backend operates
;; through a network connection. You can also get some of the modes, like the
;; `empi-caption-mode', to display a constantly updated media caption in the
;; title bar, started using the customization interface.
;;; Code:
(defconst empi-version "1.0")
;;;; User serviceable area
(defgroup empi nil
"The Emacs Media Player Interface"
:prefix "empi-"
:link '(emacs-commentary-link :tag "Introduction to EMPI" "empi-core")
:group 'multimedia :group 'external)
(defcustom empi-initial-backends nil
"The list of backends required at startup by EMPI.
This list is usually decided by the handlers in `empi-player-alist'.
Each element of the list needs to be feature to be provided by a file with a
similar filename on the load path. See `require' for more details.
Do not set this variable directly, use the customization interface instead."
:type '(repeat (symbol :tag "Feature"))
:group 'empi :set '(lambda (sym val)
(eval-after-load "empi" `(mapc 'require (quote ,val)))
(set sym val)))
(defun empi-player-alist-custom-friendly (val conv)
(let ((cur val) item)
(while cur
(setq item (cdr-safe (car-safe cur)))
(while item
(cond
((eq conv 'get)
(or (listp (car-safe item)) (setcar item (list (car item)))))
((eq conv 'set)
(and (listp (car-safe item)) (not (cdr-safe (car item)))
(setcar item (caar item)))))
(setq item (cdr-safe item)))
(setq cur (cdr-safe cur))) val))
(defcustom empi-player-alist nil
"Alist of players and their corresponding handlers for EMPI.
Each of the elements in the alist has the player name as the car and a list of
handlers as the cdr. Each handler is either the symbol containing the function
to call as its value, or a list. In the first case, the handler is given a
chance to handle any action. In the second case, the first element of the list
is the name of the symbol, and the elements following are action symbols for
which this handler is used. It is advised to keep `empi-forwarder' as the last
handler for all players."
:type
'(repeat
(list :format " %v"
(string :tag "Name")
(repeat :inline t :tag "Handler List"
:value (empi-forwarder)
(list :format "%v"
:value (empi-)
(symbol :tag "Symbol")
(set :inline t :format "%v"
(list :inline t :format "%v"
(const :format "" :restrict)
(repeat :tag "Selective Actions"
(symbol :format "%v" :value :))))))))
:get '(lambda (sym)
(empi-player-alist-custom-friendly (symbol-value sym) 'get))
:set '(lambda (sym val)
(set sym (empi-player-alist-custom-friendly val 'set)))
:group 'empi)
(put 'empi-player-alist 'custom-tag
(substitute-command-keys
"Empi Player Alist: This variable has no sane default.
This always needs to be specified. To know more about this variable, read the
package commentary using `\\[finder-commentary] empi-core'.
See {srcdir}/cust-eg.html for an example customization."))
(defcustom empi-default-player nil
"*The default player used for all EMPI actions.
Should be one of the values defined by `empi-player-alist'. The current player
used can be modified by a call to `empi-select-player'."
:type '(choice (const :tag "First in list" nil)
(string :tag "Player name")) :group 'empi)
;;;; Utility functions
(defmacro oconcat (&rest args)
(let (actual (str "") item)
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual)))))
(defalias 'oconcat 'concat)
(defun byte-compile-oconcat (form)
(let (actual (str "") item (args (cdr form)))
(while args
(setq item (car args))
(if (stringp item)
(setq str (concat str item))
(unless (string= str "")
(setq actual (cons str actual))
(setq str ""))
(setq actual (cons item actual)))
(setq args (cdr args)))
(or (string= str "") (setq actual (cons str actual)))
(byte-compile-form
(if (cdr actual)
(cons 'concat (nreverse actual))
(apply 'concat (nreverse actual))))))
(put 'oconcat 'byte-compile 'byte-compile-oconcat)
(or (fboundp 'warn)
(defmacro warn (&rest args)
`(message (oconcat "Warning: " ,@args))))
(defmacro serror (str)
`(signal 'error (list ,str)))
(defmacro emperet (str)
`(serror (oconcat "Unexpected result on " ,str " query")))
(defmacro empuns (str)
`(serror (oconcat "Unsupported or failed action " ,str)))
(defmacro empuns-nf (str)
`(progn
(message (oconcat "Warning: Unsupported or failed action " ,str)) nil))
(defun list-alternate (l)
(if (listp l)
(if l
(append (list (list (symbol-name (car l))))
(list-alternate (cdr (cdr l)))))
(error "Argument is not a list")))
(defsubst plist-keys (sym)
(list-alternate (symbol-plist sym)))
(defun walk-white (str begin &optional rev)
(if (or (= (elt str begin) ? )
(= (elt str begin) ?\n)
(= (elt str begin) ?\t)
(= (elt str begin) ?\v))
(if (if rev (> begin 0) (< begin (1- (length str))))
(walk-white str (+ begin (if rev -1 1)) rev))
begin))
(defun trim-string (str)
(if (= (length str) 0) ""
(let ((nwbeg (walk-white str 0)))
(if nwbeg
(substring str nwbeg (1+ (walk-white str (1- (length str)) t))) ""))))
(eval-and-compile
(defmacro with-unlogged-message (&rest args)
`(let ,(list
(if (boundp 'log-message-filter-function)
'(log-message-filter-function #'ignore)
'(message-log-max nil))) ,@args))
(defmacro unlogged-message (&rest args)
`(with-unlogged-message
(message ,@args))))
(defun define-keys (map &rest args)
(while (cadr args)
(define-key map (car args) (cadr args))
(setq args (cddr args))))
(defun gcd-2 (a b)
(let (temp)
(while (not (= b 0))
(setq temp a a b b (mod temp a)))) a)
(defmacro with-critical-lock (lock &rest body)
"Lock the enclosing code with LOCK against re-entrancy.
LOCK is evaluated thrice in this process."
`(unless (intern-soft ,lock)
(intern ,lock)
(unwind-protect
(progn ,@body)
(unintern ,lock))))
(put 'with-critical-lock 'lisp-indent-function 1)
(def-edebug-spec with-critical-lock t)
;;;; Core commands
(defvar empi-current-player nil)
;;;###autoload
(defun empi-select-player (pname)
(interactive
(list
(if (and (listp empi-player-alist) (> (length empi-player-alist) 0))
(completing-read
(concat "Enter player name"
(if (and empi-current-player (listp empi-current-player))
(concat " (" (car empi-current-player) ")")) ": ")
empi-player-alist nil t nil nil (car empi-current-player))
(error "No players available"))))
(let ((newp (assoc pname empi-player-alist)))
(if newp
(if (listp (cdr newp))
(setq empi-current-player newp)
(error "The handler list for the player specified is invalid, \
please check your settings"))
(error "The player specified does not exist"))))
(defun empi-ensure-current-player ()
(when (not empi-current-player)
(if (stringp empi-default-player)
(empi-select-player empi-default-player)
(if (listp empi-player-alist)
(if (= (length empi-player-alist) 0)
(error "No players available")
(message "No default player, defaulting to first player in list")
(setq empi-current-player (car empi-player-alist)))
(error "Invalid player alist")))))
(defvar empi-forwarder-chain nil)
(defun empi-command (cmd &rest args)
(empi-ensure-current-player)
(if (not (listp (cdr empi-current-player)))
(error "Invalid player entry %s" (car empi-current-player))
(let ((htail (cdr empi-current-player)) ret func cur)
(setq empi-forwarder-chain (list cmd))
(while (and htail (not ret))
(setq cur (car htail))
(and (listp cur)
(setq cur (and (let ((restrict (plist-get (cdr cur) :restrict)))
(or (not restrict) (memq cmd restrict)))
(car cur))))
(when cur
(if (and (symbolp cur) (functionp (setq func (symbol-value cur))))
(setq ret (apply func cur cmd args))
(warn "Invalid handler found for player "
(car empi-current-player) ", ignoring")))
(setq htail (cdr htail)))
(setq empi-forwarder-chain nil) ret)))
(defun empi-forward (cmd command-func &rest args)
(or empi-forwarder-chain (error "No forwarder chain present"))
(unless (memq cmd empi-forwarder-chain)
(setq empi-forwarder-chain (cons cmd empi-forwarder-chain))
(let (retval)
(unwind-protect
(setq retval (apply command-func cmd args))
(setq empi-forwarder-chain (cdr-safe empi-forwarder-chain)))
retval)))
;;;; Cache support
(defvar empi-global-cache nil)
(defvar empi-cache-lock 0)
(defvar empi-query-dependencies nil)
(defun empi-add-dependency (query &rest actions)
(mapc '(lambda (item)
(let ((val (plist-get empi-query-dependencies item)))
(if val (or (memq query val) (setcdr val (cons query (cdr val))))
(setq empi-query-dependencies
(plist-put empi-query-dependencies item (list query))))))
actions))
(defalias 'empi-static-dep 'empi-add-dependency)
(defun empi-uncache (&rest keys)
(mapc
'(lambda (item)
(setq empi-global-cache (plist-put empi-global-cache item nil))) keys))
(defun empi-merge-command (cmd &rest args)
(setq args (apply 'empi-command cmd args))
(if (listp args)
(let ((ftail args) necdr
(necessary (plist-get empi-query-dependencies cmd)))
(if necessary
(setq necessary (append necessary (list cmd)))
(setq necessary (list cmd)))
(while ftail
(setq necessary (delq (car ftail) necessary))
(and (symbolp (car ftail)) (cadr ftail)
(setq empi-global-cache (plist-put empi-global-cache (car ftail)
(cadr ftail))))
(setq ftail (cddr ftail)))
(apply 'empi-uncache necessary)
(plist-get empi-global-cache cmd))
(apply 'empi-uncache (plist-get empi-query-dependencies cmd))
(setq empi-global-cache (plist-put empi-global-cache cmd args)) args))
(defun empi-cached-command (cmd &rest args)
(or (plist-get empi-global-cache cmd)
(apply 'empi-merge-command cmd args)))
(defsubst empi-clear-cache () (setq empi-global-cache nil))
(defmacro with-empi-cache-group-by (group &rest body)
`(unwind-protect
,`(,@group
(if (= empi-cache-lock 0) (empi-clear-cache))
(setq empi-cache-lock (1+ empi-cache-lock))
,@body)
(setq empi-cache-lock (1- empi-cache-lock))))
;;;; Convenience macros/aliases
(eval-when-compile (require 'edebug))
(defmacro with-empi-cache (&rest body)
`(with-empi-cache-group-by (progn) ,@body))
(put 'with-empi-cache 'lisp-indent-function 0)
(def-edebug-spec with-empi-cache (body))
(defmacro with-empi-cache-let (vars &rest body)
`(with-empi-cache-group-by ,`(let ,vars) ,@body))
(put 'with-empi-cache-let 'lisp-indent-function 1)
(def-edebug-spec with-empi-cache-let let)
(defalias 'empi-query 'empi-cached-command)
(defalias 'empi-action 'empi-merge-command)
(defmacro empi-forward-command (cmd &rest args)
`(empi-forward ,cmd 'empi-command ,@args))
(defmacro empi-forward-query (cmd &rest args)
`(empi-forward ,cmd 'empi-query ,@args))
(defmacro empi-forward-action (cmd &rest args)
`(empi-forward ,cmd 'empi-action ,@args))
(defmacro empi-symbol-name (sym)
(if (symbolp sym)
(symbol-name sym)
(list 'symbol-name sym)))
(defmacro empi-simple-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-simple-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns (empi-symbol-name ,cmd))))
(defmacro empi-recov-command (cmd &rest args)
`(or (empi-command ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-query (cmd &rest args)
`(or (empi-query ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
(defmacro empi-recov-action (cmd &rest args)
`(or (empi-action ,cmd ,@args) (empuns-nf (empi-symbol-name ,cmd))))
;;;; Display update support
(defvar empi-update-list nil)
(defvar empi-update-timer nil)
(defvar empi-update-disable nil)
(defvar empi-update-schedule nil)
(defvar empi-update-schedule-pos nil)
;; Redeclared with defcustom, this is to silence the compiler.
(defvar empi-update-reference-interval)
(defun empi-update-build-schedule (list)
(let* ((length (/ (aref empi-update-timer 2) (aref empi-update-timer 1)))
(ring (make-list length nil)) (ringpos 0) ringptr interval)
(while list
(setq ringptr ring interval (/ length (aref (car list) 1)))
(while ringptr
(and (zerop ringpos)
(setcar ringptr (cons (aref (car list) 0) (car ringptr))))
(if (= (setq ringpos (1+ ringpos)) interval) (setq ringpos 0))
(setq ringptr (cdr ringptr)))
(setq list (cdr list))) ring))
(defun empi-update-timer-handler ()
(with-critical-lock "empi-update-timer-handler-lock"
;; If there's a command already running, don't poke your nose in...
;; This is a bit paranoid, but nobody guarantees a timer event anyway :)
(unless empi-forwarder-chain
(with-empi-cache
(mapc
'(lambda (item)
(condition-case err
(funcall item)
(error
(message "empi-update: error in timer function%s: %s"
(if (symbolp item) (concat " " (symbol-name item)) "")
(error-message-string err))
;;; Disabling removal of handler on error...Undecided design issue.
;;; (setcar empi-update-schedule-pos
;;; (delete item (car empi-update-schedule-pos)))
)))
(car empi-update-schedule-pos)))
(setq empi-update-schedule-pos
(or (cdr empi-update-schedule-pos) empi-update-schedule)))))
(defun empi-update-stop ()
(when (aref empi-update-timer 0)
(cancel-timer (aref empi-update-timer 0))
(aset empi-update-timer 0 nil)))
(defun empi-update-start (&optional rebuild)
(when empi-update-timer
(empi-update-stop)
(and rebuild (setq empi-update-schedule
(empi-update-build-schedule empi-update-list)))
(setq empi-update-schedule-pos empi-update-schedule)
(aset empi-update-timer 0
(run-at-time nil
(/ empi-update-reference-interval
(float (aref empi-update-timer 2)))
'empi-update-timer-handler))))
(defvar empi-update-register-notrigger nil)
(defun empi-update-register (func scale deps)
(or (and (wholenump scale) (not (zerop scale)) (functionp func))
(error "Invalid scale value"))
(if empi-update-timer
(let ((olcm (aref empi-update-timer 2)))
(aset empi-update-timer 1 (gcd-2 (aref empi-update-timer 1) scale))
(aset empi-update-timer 2 (* (/ olcm (gcd-2 olcm scale)) scale)))
(setq empi-update-timer (vector nil scale scale)))
(setq empi-update-list (cons (vector func scale deps) empi-update-list))
(or empi-update-register-notrigger (empi-update-start t))
(car empi-update-list))
(defun empi-update-ref-p (obj)
(and (vectorp obj) (= (length obj) 3)))
(defmacro combine-empi-update-registers (&rest body)
`(let ((empi-update-register-notrigger t) res)
(unwind-protect
(setq res (progn ,@body))
(empi-update-start t) res)))
(defun gcd-lcm-n (a &rest args)
(setq a (aref a 1))
(let ((lcm a) item)
(while args
(setq item (aref (car args) 1)
a (gcd-2 a item)
lcm (* (/ lcm (gcd-2 lcm item)) item))
(setq args (cdr args)))
(cons a lcm)))
(defun empi-update-unregister (obj)
(setq empi-update-list (delq obj empi-update-list))
(if empi-update-list
;; Maybe merge gcd-lcm-n to use specifically here
(let ((gcd-lcm-n (apply 'gcd-lcm-n empi-update-list)))
(aset empi-update-timer 1 (car gcd-lcm-n))
(aset empi-update-timer 2 (cdr gcd-lcm-n))
(empi-update-start t))
(empi-update-stop)
(setq empi-update-timer nil)))
(define-widget 'wholenum 'restricted-sexp
"Whole number type"
:tag "Whole number" :value 0 :size 10
:type-error "This field should contain a whole number"
:match-alternatives '(wholenump))
(define-widget 'natnum 'restricted-sexp
"Natural number type"
:tag "Natural number" :match-alternatives '(natnump) :value 1 :size 10
:type-error "This field must contain a natural number")
(defun positive-nump (val) (> val 0))
(define-widget 'posnum 'restricted-sexp
"Positive number type"
:tag "Positive number" :match-alternatives '(positive-nump) :value 1 :size 10
:type-error "This field must contain a positive number")
(defcustom empi-update-reference-interval 1
"Reference interval for timed action in the EMPI system.
Various timed actions in EMPI use a factor of this value as the interval between
successive executions."
:type 'posnum :set '(lambda (var val)
(set var val)
(empi-update-start)) :group 'empi)
(provide 'empi-core)
;;; EMPI-CORE.EL ends here
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.