├── .gitattributes
├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── Makefile
├── README.md
├── examples
├── README.md
├── binary.org
├── daas.org
├── foobar.org
├── hn.org
├── html.org
├── httpbin.org
├── ipify.org
├── multipart.org
├── open-library.org
├── postman-echo.org
├── prelude.el
├── prelude.org
├── req-res.org
└── scryfall.org
├── extra
├── curl2verb.py
└── logo
│ ├── logo.png
│ ├── logo.xcf
│ ├── logo2.png
│ └── logo2.xcf
├── ob-verb.el
├── test
├── checkdoc-batch.el
├── data
│ ├── test.bin
│ ├── test.el
│ ├── test.json
│ ├── test.org
│ ├── test.png
│ └── test.txt
├── init-check.el
├── init.el
├── server.go
└── verb-test.el
├── verb-util.el
└── verb.el
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.py linguist-vendored=true
2 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | paths-ignore:
5 | - '**.md'
6 | - 'examples/*'
7 | - 'extra/*'
8 | pull_request:
9 | schedule:
10 | - cron: '0 12 1 * *'
11 | jobs:
12 | test:
13 | name: Checks/Tests
14 | runs-on: ${{ matrix.os }}
15 | continue-on-error: true
16 | strategy:
17 | matrix:
18 | # Add 'snapshot' to test on Emacs master
19 | emacs_version:
20 | - '26.3'
21 | - '30.1'
22 | os:
23 | - ubuntu-latest
24 | - macos-latest
25 | exclude:
26 | - os: macos-latest
27 | emacs_version: '26.3'
28 | steps:
29 | - uses: purcell/setup-emacs@master
30 | with:
31 | version: ${{ matrix.emacs_version }}
32 | - uses: actions/checkout@v4
33 | - uses: actions/setup-go@v5
34 | with:
35 | go-version: 'stable'
36 | - name: Setup checks
37 | if: "!startsWith(matrix.emacs_version, '26')"
38 | run: 'make setup-check'
39 | - name: Run checks
40 | if: "!startsWith(matrix.emacs_version, '26')"
41 | run: 'make check'
42 | - name: Run unit tests
43 | env:
44 | WAIT_TIME: 3
45 | run: 'make test'
46 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled
2 | *.elc
3 |
4 | # Packaging
5 | .cask
6 |
7 | # Backup files
8 | *~
9 | \#*\#
10 |
11 | # Undo-tree save-files
12 | *.~undo-tree
13 |
14 | # Test server pidfile
15 | test/server.pid
16 |
17 | # linting packages installation directory
18 | /packages
19 |
20 | # autoloads
21 | verb-autoloads.el
22 |
23 | # Emacs binary
24 | /emacs
25 |
26 | # Testing server
27 | /server
28 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Verb Changelog
2 | ## **3.1.0** - 2025-03-18 (MELPA & MELPA Stable)
3 | - Added support for `Verb-Map-Response` heading property. This allows for calling functions automatically with the HTTP response data, when it is received.
4 | - Added the `verb-util-form-url-encode` helper function for use with `application/x-www-form-urlencoded`.
5 | - Fixed error occuring when maxium number of redirections set by `url-max-redirections` was reached.
6 | - Added support for `Verb-Max-Redirections` heading property.
7 | - The `verb-headers-get` function now accepts an instance of `verb-response` as first argument.
8 | - Added Verb-specific handler for Org's C-c C-c contextual key.
9 |
10 | ## **3.0.0** - 2024-12-23
11 | Breaking changes:
12 | - Updated behaviour for `verb-send-request-on-point-*` functions when dealing with one or more Babel source blocks under a heading. Now, the actual source block on point will be used to build the request, instead of simply the first one. See [issue #53](https://github.com/federicotdn/verb/issues/53).
13 | - Defining a URL origin (scheme + host + port) in a request specification will now make Verb ignore all parent headings when computing what request to send. In other words, defining a new URL origin effectively creates a new tree of request specifications.
14 | - Removed support for the `url-queue` backend.
15 | - Removed all Emacs 25-specific code.
16 | - Escape sequences ('\\') contained in strings resulting from evaluating code tags will not be interepreted, i.e. all contents will be taken as literal.
17 | - Removed `verb-view-log` alias.
18 | - Renamed `verb-show-log` to `verb-util-show-log`.
19 | - All `verb-log-*` variables containing faces are no longer part of the package's public API.
20 |
21 | New features / improvements:
22 | - Added support for `Verb-Proxy` heading property.
23 | - Improved `*Verb Log*` buffer formatting.
24 | - Headers can now contain code tags that expand to multiple lines.
25 | - URLs can now span multiple lines, place '\\' at the end of the URL line to continue it in the next one. Leading whitespace in the additional lines will be skipped.
26 | - Added new function `verb-body-lf-to-crlf` designed for use with requests sending multipart data.
27 | - Added new `Verb-Prelude` heading property, which can be used to specify Emacs Lisp or JSON contents to load variables from, before performing requests. Contents can come optionally from files, e.g. `.el` or `.json`.
28 | - Added `verb-shell`, `verb-url` and `verb-unix-epoch` utility functions.
29 | - Allow using Org [hyperlinks](https://orgmode.org/guide/Hyperlinks.html) in URLs, for example: `get [[http://example.com][my example]]`.
30 |
31 | ## **2.16.0** - 2024-03-02
32 | - Fixed LF being used instead of CRLF in multipart boundaries.
33 | - When sending a request, include the HTTP method and path in the message displayed on the minibuffer.
34 | - The `verb-json-get` function now accepts negative integer arguments for accessing list elements.
35 | - Changed default binding of `verb-send-request-on-point-no-window` to C-c C-r C-.
36 | - Allow using single- or multi-line lambda expressions for `Verb-Map-Request`.
37 | - The `verb-auto-kill-response-buffers` customizable variable can now be set to an integer. This will cause all response buffers to be killed when a request is sent, except the N most recent ones.
38 | - Calling `verb-set-var` interactively with a prefix argument (C-u) will copy the variable value to the kill ring.
39 | - The current value of a Verb variable will be shown in the minibuffer when the point is moved over a code tag containing only `(verb-var xyz)`.
40 | - `verb-set-var` now has its own input history.
41 | - Dropped support for Emacs 25. Emacs 26.3 is now the minimum supported version. Verb may still work partially or completely on Emacs 25, but this may change without prior warning.
42 | - Added default binding for `verb-show-vars`: C-c C-r C-x.
43 | - Added new export format `websocat`.
44 | - Added new function `verb-export-request-on-point-websocat`.
45 | - Removed default keybindings for all `verb-export-request-on-point-*` functions, and made export function querying faster in `verb-export-request-on-point`.
46 | - Added additional advice to url.el to prevent it from dropping the response body when the `Content-Encoding` is set to `gzip` but the contents themselves are not actually compressed.
47 | - Added support for using `org-babel-expand-src-block` on `verb` Babel source blocks.
48 |
49 | ## **2.15.0** - 2021-11-03
50 | - Fixed font locking on indented Babel source blocks.
51 | - Added `verb-part` and `verb-boundary` functions, to facilitate building requests using `multipart/form-data`.
52 |
53 | ## **2.14.0** - 2021-04-29
54 | - Fixed error when receiving JSON responses that include `"t"` as a key.
55 | - Allow underscores (`_`) in HTTP header names.
56 | - Fixed C-u C-c C-r C-r and C-u C-c C-r C-s not displaying the response buffer when a response is received.
57 | - Fixed Verb not reading parent headings when buffer has been narrowed (e.g. with `org-narrow-to-subtree`).
58 | - When using Babel `verb` source blocks, arguments specified via the `:var` keyword can now be read using `verb-var`.
59 | - Added new export function `verb-export-request-on-point-eww`, which uses EWW to display `GET` requests.
60 | - Added new function `verb-re-send-request-eww` (see above).
61 |
62 | ## **2.13.1** - 2021-01-12
63 | - Heading properties (e.g. `Verb-Store`, `Verb-Map-Request`) can now be inherited from parent headings by setting `org-use-property-inheritance` to `t`.
64 |
65 | ## **2.13.0** - 2020-11-16
66 | - Added the `verb-default-content-type-handler` customizable variable.
67 | - Verb will now display response buffer immediately after the request is sent to avoid window/buffer configuration being changed after the response is received, which can happen after an indeterminate amount of time. Note that this only applies to commands that display the response buffer. This change makes the behaviour of Verb more predictable.
68 | - Made the minibuffer response status message more descriptive.
69 |
70 | ## **2.12.0** - 2020-08-02
71 | - Added the `verb-show-vars` command. It allows users to see a listing of all currently defined variables.
72 | - Added the `verb-unset-vars` command. It allows users to unset all currently defined variables. This implies that if the DEFAULT argument was specified for `verb-var`, that value will be used the next time the variable's value is retrieved.
73 | - Added the `verb-show-request` command. It allows users to quickly see the corresponding request that was sent for an already received HTTP response.
74 | - Renamed `verb-view-log` to `verb-show-log`.
75 | - Added `verb-version` constant.
76 |
77 | ## **2.11.0** - 2020-05-27
78 | - If a (non-Verb) Babel source block is found inside a request body, its corresponding `#+begin_src` and `#+end_src` delimiters are erased before sending the request.
79 | - Enabled code completion for code tags by default.
80 | - Added support for the `Verb-Map-Request` heading property. This allows specifying a function per request, that can modify the request before it's sent.
81 | - Properly clean up font locking and completion at point functions when `verb-mode` is disabled.
82 | - Added `verb-send-request-on-point-no-window` to `verb-mode` mouse menu.
83 |
84 | ## **2.10.0** - 2020-05-01
85 | - Added the `verb-json-use-mode` customizable variable. It allows users to change what mode is enabled on JSON responses.
86 | - Renamed `verb--handler-json` to `verb-handler-json`.
87 | - Added code completion for code tags via `completion-at-point-functions`.
88 |
89 | ## **2.9.0** - 2020-03-27
90 | - Added support for Emacs 25.
91 | - Removed human-readable export format as it was too similar to Verb format.
92 | - Search for `:verb:` tag now respects the `org-use-tag-inheritance` variable.
93 |
94 | ## **2.8.2** - 2020-03-16
95 | - Fixed error signaled when receiving a response with an unknown content type.
96 |
97 | ## **2.8.1** - 2020-03-12
98 | - Use standard `switch-to-buffer`/`display-buffer` functions to show side buffers and pop-up buffers.
99 | - Added `verb-send-request-on-point-no-window` command. By default, it is bound to C-c C-r C-m.
100 | - Fixed error signaled when specifying an `Accept` header and using a non-ascii body at the same time.
101 |
102 | ## **2.8.0** - 2020-02-23
103 | - All the `verb-send-request-on-point-*` commands now accept a prefix argument (C-u). When it is specified, the user can modify the request that was extracted from the headings hierarchy before it is sent, in a temporary buffer.
104 | - The `verb-set-var` command can now set variable values for variables that haven't been used before.
105 | - Changed type of `verb-content-type-handlers` elements (to lists).
106 |
107 | ## **2.7.2** - 2020-02-17
108 | - Fixed code tags not being fontified when having more than one of them on a single line.
109 | - Log a warning when sending a request with a body present on GET, HEAD, DELETE, etc.
110 |
111 | ## **2.7.1** - 2020-02-12
112 | - Use `file-size-human-readable` to format response body sizes in header lines.
113 | - Fixed error on responses with no content type.
114 |
115 | ## **2.7.0** - 2020-02-09
116 | - Bound `verb-export-request-on-point-verb` to `C-b` in the Verb command map.
117 | - Bound `verb-export-request-on-point-human` to `C-n` in the Verb command map.
118 | - Variables created with `verb-var` are now buffer-local, and are not defined as global values.
119 | - Code tags are now evaluated with the current `.org` buffer as the current buffer.
120 | - Added `verb-headers-get` function.
121 | - Regular expressions can now be used as keys in `verb-content-type-handlers`, to easily assign one handler to one or more content types.
122 |
123 | ## **2.6.0** - 2020-02-03
124 | - Removed `verb-max-redirections` variable, as it wasn't working as intended. Use `url-max-redirections` instead.
125 | - Added `default` argument to `verb-var`.
126 | - Removed automatic addition of `charset=` value in `Content-Type` request headers.
127 | - Added optional `coding-system` argument to `verb-read-file`.
128 |
129 | ## **2.5.0** - 2020-01-30
130 | - Added `verb-trim-body-end` variable.
131 | - Extended `:op send` so that it now accepts an optional, additional `get-headers` or `get-body` argument.
132 | - Added "Customize Verb" button to the `verb-mode` mouse menu.
133 | - Removed `verb-using-proxy` variable, as it wasn't working as intended.
134 | - Combined `verb-binary-content-type-handlers` and `verb-text-content-type-handlers` variables into a unified one, `verb-content-type-handlers`.
135 |
136 | ## **2.4.0** - 2020-01-29
137 | - Heading properties starting with `Verb-` will now be added to request and response objects automatically as metadata. Metadata is not included in outgoing HTTP requests.
138 | - Added mechanism for automatically storing responses by key.
139 | - Added the `verb-stored-response` function.
140 | - Added the `verb-json-get` function.
141 |
142 | ## **2.3.0** - 2020-01-26
143 | - Do not automatically add `Accept-Charset` header to requests anymore.
144 | - Fixed `Accept` header being sent duplicated if included in a request specification.
145 | - Log a warning to `*Verb Log*` buffer when headers might get duplicated by url.el.
146 | - Overriding HTTP headers now ignores case (e.g. it is now possible to override `content-type` using `Content-Type`).
147 | - Added customizable option `verb-base-headers`.
148 |
149 | ## **2.2.0** - 2020-01-24
150 | - Renamed `verb-mode-prefix-map` to `verb-command-map` (existing `init.el` configs must be updated).
151 | - Signal an error when using `verb-set-var` if no variables have been previously set with `verb-var`.
152 | - Fixed `verb-re-send-request` not showing response buffer.
153 | - Added mouse menus for `verb-mode` and `verb-response-body-mode`.
154 |
155 | ## **2.1.0** - 2020-01-24
156 | - Verb can now be used from Babel source blocks.
157 | - Added customizable option `verb-babel-timeout`.
158 | - Added new major mode: `ob-verb-response-mode`.
159 | - Verb now requires at least one heading to be defined for reading request specifications.
160 |
161 | ## **2.0.0** - 2020-01-21
162 | - Verb is now based on Org mode instead of Outline mode.
163 | - Verb is now a minor mode (to be enabled with Org) instead of a major mode.
164 | - Because Verb now works on Org mode buffers, the preferred file extension is `.org` (the old `.verb` extension is no longer used).
165 | - Added package autoloads for most user-facing commands (e.g. `verb-send-request-on-point`).
166 | - Verb now only processes headings which have been tagged as `verb`. All other headings are ignored.
167 | - Fixed small detail in HTTP method parsing - leaving a space between the method and the URL was optional before but now it's required.
168 | - Fixed error when receiving an empty body marked as content type JSON.
169 | - HTTP headers in request specifications now accept empty values.
170 | - Fixed error when receiving HTTP headers with empty values.
171 |
172 | ## **1.4.1** - 2020-01-19
173 | - Added new logging system, logs will be shown in the `*Verb Log*` buffer.
174 | - Added a `verb-enable-log` customizable option.
175 |
176 | ## **1.4.0** - 2020-01-18
177 | - Fixed Lisp code tags being evaluated in comments.
178 | - Rebound `verb-send-request-on-point-other-window` to C-c C-r C-s in Verb mode.
179 | - Added new command `verb-send-request-on-point-other-window-stay`, bound to C-c C-r C-r in Verb mode.
180 | - Added new command `verb-kill-all-response-buffers`, bound to C-c C-r C-k in Verb mode.
181 | - Added new command `verb-re-send-request`, bound to C-c C-r C-f in Verb response body mode.
182 | - Removed `verb-headers-to-string` function.
183 | - A blank line must now be present between request headers and body.
184 | - Added user error messages for invalid HTTP headers.
185 | - Allow using code tags in HTTP header names.
186 |
187 | ## **1.3.0** - 2020-01-17
188 | - Request headers can now be commented out using `#`.
189 | - Surrounding whitespace is now automatically removed from header names and values.
190 | - Changed `curl` export format slightly:
191 | - URL is now the first argument.
192 | - Arguments are now separated by (escaped) newlines.
193 | - Added `verb-export-request-on-point-curl`, `verb-export-request-on-point-verb` and `verb-export-request-on-point-human` commands.
194 | - Bound C-c C-r C-u to `verb-export-request-on-point-curl` in Verb mode.
195 | - Added `verb-set-var` command, bound to C-c C-r C-v in Verb mode.
196 |
197 | ## **1.2.0** - 2020-01-16
198 | - Request specifications can now be exported to `curl`.
199 |
200 | ## **1.1.0** - 2020-01-15
201 | - Made Lisp code tags more useful: the HTTP method for a request spec can now be determined by the result of a code tag.
202 | - Renamed customizable variable `verb-show-headers-buffer` to `verb-auto-show-headers-buffer`.
203 | - Added `verb-last` variable.
204 | - Added `verb-headers-to-string` function.
205 | - Added `verb-post-response-hook` hook.
206 |
207 | ## **1.0.0** - 2020-01-13
208 | - Initial release.
209 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SHELL = bash
2 | EMACS ?= emacs
3 | PORT ?= 8000
4 | PACKAGES = packages
5 | FONT_SIZE ?= 180
6 | MAX_LINE_LEN = 80
7 | WAIT_TIME ?= 0.5
8 | S ?= t
9 | SELECTOR ?= $S
10 |
11 | .PHONY: test server
12 |
13 | help: ## Display this help message.
14 | @printf 'Summary of available Makefile recipes:\n\n'
15 | @grep '##' Makefile | grep -v grep | column -t -s '##'
16 | @echo
17 |
18 | test: ## Run all ERT tests (set SELECTOR to specify only one).
19 | test: clean server-bg
20 | sleep $(WAIT_TIME)
21 | $(EMACS) --batch -L . \
22 | -l test/verb-test.el \
23 | --eval "(ert-run-tests-batch-and-exit '$(SELECTOR))"; \
24 | ret=$$?; \
25 | make server-kill; \
26 | exit $$ret
27 |
28 | test-noserver:
29 | $(EMACS) --batch -L . \
30 | -l test/verb-test.el \
31 | --eval "(ert-run-tests-batch-and-exit '$(SELECTOR))"; \
32 |
33 | server: ## Run a testing HTTP server on port 8000 (default).
34 | go build test/server.go
35 | SKIP_PIDFILE=1 PORT=$(PORT) ./server
36 |
37 | server-bg:
38 | go build test/server.go
39 | PORT=$(PORT) ./server &
40 |
41 | server-kill:
42 | kill $$(cat test/server.pid)
43 | sleep 1
44 |
45 | clean: ## Clean up all temporary files created during testing/runtime.
46 | rm -f verb-autoloads.el test/server.pid server
47 | find . -name "*.elc" -type f -delete
48 |
49 | setup-check: ## Install packages required for linting.
50 | rm -rf $(PACKAGES)
51 | $(EMACS) --batch \
52 | --eval "(setq package-user-dir \"$$PWD/$(PACKAGES)\")" \
53 | -l test/init-check.el
54 |
55 | lint-file:
56 | @printf "\n<<<------------ Lint file: $(filename) ------------>>>\n"
57 | @printf "\n--> Step: Byte-compile file\n\n"
58 | $(EMACS) --batch -L . \
59 | --eval "(setq byte-compile-error-on-warn t)" \
60 | -f batch-byte-compile "$(filename)"
61 | @printf "\n--> Step: Run checkdoc\n\n"
62 | yes n | $(EMACS) --batch \
63 | -l test/checkdoc-batch.el \
64 | -f checkdoc-batch-and-exit "$(filename)"
65 | @printf "\n--> Step: Run package-lint\n\n"
66 | $(EMACS) --batch --eval "(setq package-user-dir \"$$PWD/$(PACKAGES)\")" \
67 | --eval "(package-initialize)" \
68 | --eval "(require 'package-lint)" \
69 | -f package-lint-batch-and-exit "$(filename)"
70 | @printf "\n--> Step: Run relint\n\n"
71 | $(EMACS) --batch --eval "(setq package-user-dir \"$$PWD/$(PACKAGES)\")" \
72 | --eval "(package-initialize)" \
73 | --eval "(require 'relint)" \
74 | -f relint-batch "$(filename)"
75 | @printf "\n--> Step: Ensure maximum line length\n\n"
76 | ! grep -n '.\{$(MAX_LINE_LEN)\}' "$(filename)"
77 |
78 | check: ## Lint all Emacs Lisp files in the package.
79 | check: clean
80 | make lint-file filename=verb.el
81 | make lint-file filename=verb-util.el
82 | make lint-file filename=ob-verb.el
83 | test $$(cat *.el | grep Package-Version | uniq | wc -l) -eq 1
84 |
85 | update: ## Update the package version number (version=X.Y.Z).
86 | update:
87 | @test -n "$(version)" || (echo "version not set!" && exit 1)
88 | @grep -q "$(version)" CHANGELOG.md || (echo "Update changelog first!" && exit 1)
89 | sed -i -e "s/^;; Package-Version: .*/;; Package-Version: $(version)/g" verb.el ob-verb.el verb-util.el
90 | sed -i -e "s/defconst verb-version .*/defconst verb-version \"$(version)\"/g" verb.el
91 |
92 | run: ## Run emacs -Q with the working version of verb.el loaded.
93 | run: clean server-bg
94 | make run-noserver; \
95 | make server-kill
96 |
97 | run-noserver: ## Same as "run", but without the test HTTP server running.
98 | FONT_SIZE=$(FONT_SIZE) $(EMACS) -Q -L . --load test/init.el
99 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | **Verb** is an HTTP client for Emacs.
7 |
8 | The package introduces a new minor mode, **Verb mode**, which works as an extension to [Org mode](https://orgmode.org/). The core idea is to structure specifications for HTTP requests using Org's tree structure. Properties defined in the child headings extend or override properties defined in the parent headings - this way, it is possible to author HTTP requests without having to repeat things such as URL hosts, headers, ports, etc. Knowledge of Org mode is not required in order to use Verb.
9 |
10 | Verb requires at least Emacs version 26 to work.
11 |
12 | [](https://github.com/federicotdn/verb/actions)
13 | [](https://melpa.org/#/verb)
14 | [](https://stable.melpa.org/#/verb)
15 | 
16 |
17 | ## Features
18 |
19 | - Send HTTP and HTTPS requests from Emacs.
20 | - Organize request specifications into trees using Org mode.
21 | - Easily define common attributes (URLs, query strings, headers, etc.) for many requests.
22 | - Correctly handle text encodings (charsets) for requests and responses.
23 | - Display PDF, PNG, JPEG, BMP, GIF and SVG responses.
24 | - Embed Emacs Lisp expressions in specifications (with code completion!).
25 | - Can export requests to `curl` and other external tools.
26 | - Integrates with Babel and EWW.
27 | - Includes mouse support (menu bar and mode line).
28 | - Supports file uploads.
29 | - Has 200+ unit tests written for it.
30 | - Tested against Go's `net/http` server implementation.
31 | - Has no dependencies!
32 | - Easy to use! (hopefully).
33 |
34 | ## Installation
35 | ### Emacs 26+
36 |
37 | You can install Verb by using the `package-install` command (make sure either [MELPA](https://melpa.org/) or [MELPA Stable](https://stable.melpa.org/) are included in your package sources):
38 |
39 | M-x `package-install` RET `verb` RET
40 |
41 | Once Verb has been installed and loaded, add the following to your `init.el`:
42 | ```elisp
43 | (with-eval-after-load 'org
44 | (define-key org-mode-map (kbd "C-c C-r") verb-command-map))
45 | ```
46 |
47 | If you're using [use-package](https://github.com/jwiegley/use-package), you'll need to modify your entry for `org` instead. Create one if you don't have one already, and under the `:config` key, add the code necessary to bind the Verb command map to a key. The end result should look something like this:
48 | ```elisp
49 | (use-package org
50 | :mode ("\\.org\\'" . org-mode)
51 | :config (define-key org-mode-map (kbd "C-c C-r") verb-command-map))
52 | ```
53 |
54 | Both cases will set C-c C-r as the prefix key for all Verb commands in Org mode. Feel free to use another key if you prefer that.
55 |
56 | If you do not want to use a package manager, you can just add all `.el` files to your `load-path` instead of installing it as a package.
57 |
58 | ### Spacemacs
59 |
60 | Verb is available on the `develop` branch of Spacemacs. To enable it, read the [documentation on enabling Verb support](https://github.com/syl20bnr/spacemacs/blob/develop/layers/%2Bemacs/org/README.org#verb-support). To view the default keybindings, see the [Verb mode bindings](https://github.com/syl20bnr/spacemacs/blob/develop/layers/%2Bemacs/org/README.org#verb) tables.
61 |
62 | ## Quick Start
63 |
64 | Here's a minimal example in case you want to get started without reading the [Usage Guide](#usage-guide). Place the following on an Org mode buffer:
65 | ```
66 | * Quick Start :verb:
67 | get https://api.ipify.org?format=json
68 | Accept: application/json
69 | ```
70 |
71 | Then, press C-c C-r C-r to send the HTTP request.
72 |
73 | Here's a more complete example that includes defines two requests, both of which share the same base URL and `Accept` header:
74 |
75 | ```
76 | * Extended Quick Start :verb:
77 | # Comments start with '#'. You can only place
78 | # comments before the URL and in the headers.
79 |
80 | template https://reqres.in/api
81 | Accept: application/json
82 |
83 | ** Create a new user
84 | # Because the base URL is defined in the parent
85 | # heading, there's no need to repeat it here.
86 | # We can also add more headers here, or override
87 | # ones defined in parents.
88 |
89 | post /users
90 | Content-Type: application/json; charset=utf-8
91 |
92 | {
93 | "name": "Jane Smith",
94 | "city": "Berlin"
95 | }
96 |
97 | ** Fetch a product
98 | # Use Emacs Lisp code tags to make the request
99 | # content dynamic. Code tags can be used anywhere
100 | # in the request specification.
101 |
102 | get /products/{{(read-number "Product ID: ")}}
103 | ```
104 |
105 | You can send any of the two requests by moving the point to one of the level 2 headings (marked with `**`), and then pressing C-c C-r C-r.
106 |
107 | ## Screenshots
108 |
109 | 
110 | 
111 | 
112 |
113 | ## Usage Guide
114 |
115 | This guide, and other Verb-related documentation, assume that you're using C-c C-r as the prefix key for all Verb commands, and that you're also getting started with Org mode.
116 |
117 | All public (and private) variables and functions in the Verb package are documented. If you wish to know more about one of them, use C-h v and C-h f respectively.
118 |
119 | ### Writing Request Specifications
120 | After setting up Verb, begin by creating a new `guide.org` file. In the example file, add the following contents:
121 |
122 | ```
123 | * Get users list :verb:
124 | get https://reqres.in/api/users
125 | ```
126 |
127 | This defines a minimal HTTP request specification under the "Get users list" heading, composed of a method (`GET`) and a URL (`https://reqres.in/api/users`). The heading is prefixed with only one `*`, which makes it a level 1 heading. The number of `*`s determines a heading's level. All the text under a heading corresponds to the HTTP request it is describing. It is not possible to write request specifications without adding a heading at the top.
128 |
129 | Note that the heading has a `:verb:` tag. **Verb functions only process headings that contain this tag, and ignore the rest.** This allows you to create documents that may have a combination of HTTP request specifications and other information types. To tag a heading, simply move the point to it and press C-c C-c, and then type in `verb` RET. Note that in Org mode, by default, headings inherit their parents' tags (see the `org-use-tag-inheritance` variable). This implies that once you've tagged one of the parent headings, all its child headings will have that tag as well.
130 |
131 | To easily add the `:verb:` tag to all headings in an Org document, add the following [in-buffer setting](https://orgmode.org/manual/In_002dbuffer-Settings.html) at the top of your file:
132 | ```
133 | #+FILETAGS: :verb:
134 | ```
135 |
136 | You may tweak the text value of the tag used by modifying the `verb-tag` variable. Note that if you modify it, you'll need to update your files as well.
137 |
138 | ### Enabling Verb in Org Buffers
139 | When you open an `.org` file with HTTP request specifications in it, Verb mode won't be enabled by default. To enable it, you can choose from these different options:
140 | - Run one of the commands that enable Verb automatically (e.g. `verb-send-request-on-point-other-window-stay`). You may use the keybinding set up in your `init.el` file (i.e. C-c C-r C-r, see [Installation](#installation)).
141 | - Run M-x`verb-mode`RET.
142 | - Add a file-local variable at the bottom of your file:
143 | ```
144 | # Local Variables:
145 | # eval: (verb-mode)
146 | # End:
147 | ```
148 |
149 | In general, the first option should be useful enough for most cases. Once Verb mode has been enabled, `Verb` should appear on the modeline. To disable Verb mode, run M-x`verb-mode`RET.
150 |
151 | ### Sending Requests
152 |
153 | To actually send the HTTP request, use one of the `verb-send-request-on-point` commands. They are the following:
154 | - C-c C-r C-r: `verb-send-request-on-point-other-window-stay` sends the request and shows the response on a buffer in another window, but doesn't switch to that window.
155 | - C-c C-r C-s: `verb-send-request-on-point-other-window` sends the request, shows the response on a buffer in another window, and switches to it.
156 | - C-c C-r C-f: `verb-send-request-on-point` sends the request, and shows the response on a buffer in the currently selected window.
157 | - C-c C-r C-: `verb-send-request-on-point-no-window` sends the request, but does not show the response buffer anywhere. The response status (e.g. `HTTP/1.1 200 OK | GET http://example.com`) will be shown on the minibuffer. This is useful for cases where one is only interested in the request's side effects.
158 |
159 | Request sending is asynchronous - you can do other stuff while Emacs waits for the server's response. If the response is taking too long to be received, a warning will be displayed in the minibuffer. You can modify this behaviour by modifying the `verb-show-timeout-warning` variable's value.
160 |
161 | ### The Response Body Buffer
162 |
163 | After you have sent the request and the server has answered back successfully, you should now be seeing the populated response body buffer. The response body buffer always has the `verb-response-body-mode` minor mode activated (indicated by `Verb[Body]` in the modeline).
164 |
165 | The buffer will have an active [header line](https://www.gnu.org/software/emacs/manual/html_node/elisp/Header-Lines.html), showing something similar to:
166 |
167 | ```
168 | HTTP/1.1 200 OK | 0.754s | application/json | 1020 bytes | /foo
169 | ```
170 |
171 | This text indicates the status of the HTTP response, the time in seconds it took for it to be completed, the type of the contents received (or `-` if the content type is unknown), and the number of bytes in the response body (read from the `Content-Length` header, when possible, otherwise from the local buffer size).
172 |
173 | The contents of the response body will be shown on the buffer. To choose how they will be actually shown, the following steps are followed:
174 |
175 | 1. The content type is extracted from the `Content-Type` header. If the header is not present, the content type is defined as `nil`.
176 | 2. A content handler is chosen for this content type. There are two types of handlers: handlers for text content types (such as JSON, XML, etc.) and handlers for binary content types (such as PNG, PDF, etc.). These handlers are listed in the `verb-content-type-handlers` variable. If no handler matched the content type (or if the content type is `nil`), choose `fundamental-mode` by default (as a text content type handler).
177 | 3. Depending on the content type handler chosen: \
178 | **Text:** If the chosen handler is for text, decode the response body using the charset described in the `Content-Type` header. If no charset was specified, use the one specified by `verb-default-response-charset` (default: `utf-8`). After that is done, call the handler (e.g. `xml-mode`). \
179 | **Binary:** If the chosen handler is for a binary type, call the handler directly after loading the raw bytes into the buffer (e.g. `doc-view-mode`).
180 | 4. The handler will have set an appropriate major mode to display and/or edit the received content.
181 |
182 | There's two recommended ways of closing response buffers:
183 | - If the response buffer is the current buffer, you can use the `verb-kill-response-buffer-and-window` command, which is bound by default to C-c C-r C-k. This command will also kill the associated response headers buffer (see the [Response Headers Buffer](https://github.com/federicotdn/verb#the-response-headers-buffer) section).
184 | - If the response buffer is not the current buffer (e.g. you are still on your `guide.org` buffer), you can kill **all** response buffers by using the `verb-kill-all-response-buffers`, which is bound to C-c C-r C-k by default. Response headers buffers will also be killed automatically.
185 |
186 | As you send more HTTP requests, more response buffers will be created, with `` at the end of their name to distinguish between them. If you wish to automatically have old response buffers killed when making a new request, set the `verb-auto-kill-response-buffers` variable to `t`. If wish for old response buffers to be killed, with the exception of the N most recent ones, then set `verb-auto-kill-response-buffers` to that integer number. This is useful for keeping track of the history of responses received, without creating too many buffers.
187 |
188 | ### Re-sending Requests
189 |
190 | If you wish to re-send the request that generated the current response buffer, select the window showing it and use the `verb-re-send-request` command, which is bound to C-c C-r C-f by default. Note that the exact same request will be sent, even if the originating `.org` file was modified. To instead re-send the request using EWW, use C-c C-r C-w instead (this only works for `GET` requests).
191 |
192 | ### Show Corresponding Request
193 |
194 | While viewing the contents of an HTTP response, you can use the `verb-show-request` command in order to show the corresponding request that generated this response. By default, the command is bound to C-c C-r C-s.
195 |
196 | ### The Response Headers Buffer
197 |
198 | If you wish to see the HTTP response headers, use the `verb-toggle-show-headers` command while the response body buffer is selected. By default, it is bound to C-c C-r C-r.
199 |
200 | The response headers buffer will be opened on a new window. The new window will be generated by splitting the window displaying the response body buffer into two parts using `split-window`. The response headers buffer will have the `verb-response-headers-mode` major mode activated, indicated by `Verb[Headers]` in the modeline. The buffer will also have a header line showing the number of headers received.
201 |
202 | The contents of the response headers buffer will be the actual HTTP headers received, for example:
203 | ```
204 | Content-Encoding: gzip
205 | Content-Type: application/json; charset=utf-8
206 | Date: Thu, 02 Jan 2020 23:29:19 GMT
207 | Server: nginx
208 | Vary: Accept-Encoding
209 | Content-Length: 619
210 | Connection: keep-alive
211 | ```
212 |
213 | To close the response headers buffer, use the `verb-toggle-show-headers` command again (C-c C-r C-r) while the response body buffer is selected.
214 |
215 | ### Specifying HTTP Headers
216 |
217 | You can add headers to your request specifications. To do this, simply write them below the request method and URL. Following from our first example:
218 | ```
219 | * Get users list :verb:
220 | get https://reqres.in/api/users
221 | Accept: application/json
222 | Content-Language: de-DE
223 | ```
224 |
225 | All headers must be written immediately after the method + URL line, without any blank lines in between. It is also possible to comment out headers. To do this, simply add `#` at the beginning of the line.
226 |
227 | A certain set of headers will **always** be included in sent requests, even if they haven't been specified. Some of them are due to requirements of the HTTP standard, and others due to limitations of the `url` Emacs library. They are the following:
228 | - `MIME-Version`: `1.0`
229 | - `Connection`: `close` or `keep-alive`
230 | - `Content-Length`: *number of bytes in request body* (only when body is present)
231 | - `Host`: *URL host*
232 | - `Accept`: `*/*` (default value, but may be overwritten by the user)
233 | - `Accept-Encoding`: `gzip` (sent when `url-mime-encoding-string` is set)
234 |
235 | If you include one of these headers in one of your requests (except `Accept`), Verb will add a warning to the [log](#verb-log).
236 |
237 | > [!IMPORTANT]
238 | > **"header" != "heading"**: "header" is used to refer to HTTP headers, and "heading" is used to refer to the elements Org mode uses to separate sections of text. Sometimes, "headlines" or "outlines" are used to refer to headings as well.
239 |
240 | ### Adding a Body
241 |
242 | To add a body to your HTTP request, simply insert it below the method, URL and headers. A blank line **must** be left between the headers and the body. Continuing with our previous example, add the following contents at the end of the file:
243 |
244 | ```
245 | * Create a user :verb:
246 | post https://reqres.in/api/users
247 | Accept: application/json
248 | Content-Type: application/json; charset=utf-8
249 |
250 | {
251 | "name": "John",
252 | "age": 42
253 | }
254 | ```
255 |
256 | The body will include everything starting from the line next to the blank line after the headers, up to the buffer's ending or the next heading (i.e. the next line starting with `*`).
257 |
258 | > [!TIP]
259 | > By default, all whitespace present will be included in the request body. You can control this behaviour with the `verb-trim-body-end` variable, for example, set it to `"[ \t\n\r]+"` to trim all trailing whitespace. This is useful if you wish to leave some blank lines between request specifications for increased readability.
260 |
261 | To encode the request body, Verb will use the `charset` value defined in the `Content-Type` header of the request. If the header is present but `charset` is not defined, or if the header is not present, the charset `verb-default-request-charset` will be used (default: `utf-8`). Note that the current buffer's file encoding has no effect on how the request body is encoded.
262 |
263 | If your body contains binary data (i.e. raw bytes that do not correspond to any particular character), that data will be sent without any encoding.
264 |
265 | The request body can also be wrapped inside a Babel source block. If this is the case, the lines containing the `#+begin_src` and `#+end_src` delimiters will be automatically erased before the request is sent. For example, the request body above could be wrapped with a `javascript` source block for better font locking:
266 |
267 | ```
268 | * Create a user :verb:
269 | post https://reqres.in/api/users
270 | Accept: application/json
271 | Content-Type: application/json; charset=utf-8
272 |
273 | #+begin_src javascript
274 | {
275 | "name": "John",
276 | "age": 42
277 | }
278 | #+end_src
279 | ```
280 |
281 | > [!IMPORTANT]
282 | > This feature is **not** related with Verb's [Babel Integration](#babel-integration), which only applies to Babel source blocks with `verb` specified as language, and takes into consideration the whole request specification (not just the body).
283 |
284 | ### Extend and Override Requests
285 |
286 | This section explains the **most interesting aspect of Verb: extending and overriding properties of requests**.
287 |
288 | Our example file should now look like the following:
289 |
290 | ```
291 | * Get users list :verb:
292 | get https://reqres.in/api/users
293 | Accept: application/json
294 | Content-Language: de-DE
295 |
296 | * Create a user :verb:
297 | post https://reqres.in/api/users
298 | Accept: application/json
299 | Content-Type: application/json; charset=utf-8
300 |
301 | {
302 | "name": "John",
303 | "age": 42
304 | }
305 | ```
306 |
307 | Notice that the two request specifications share many things in common: the URL host, path and one header. In order to avoid repeating all this information, we can actually define a `template` request, establishing all the common attributes among requests, and then extend this template request with different values. Using `template` allows you to avoid specifying an HTTP method at a points in your file where you only want to establish shared attributes for other requests. To use it, create a new level 1 heading, and move the already existing headings below it, making them level 2 child headings:
308 |
309 | ```
310 | * User management :verb:
311 | template https://reqres.in/api/users
312 | Accept: application/json
313 |
314 | ** Get users list
315 | get
316 | Content-Language: de-DE
317 |
318 | ** Create a user
319 | post
320 | Content-Type: application/json; charset=utf-8
321 |
322 | {
323 | "name": "John",
324 | "age": 42
325 | }
326 | ```
327 |
328 | Now, when we send the request under "Get users list", Verb will collect all the properties defined in all the parent headings tagged with `:verb:` (in this case, a URL and one header), and then extend/override them with the attributes under this specific heading. Any number of levels can be traversed this way. This is how each attribute of an HTTP request specification is extended/overridden:
329 |
330 | - **Method:** The last heading's (i.e. the one with no children) method will be used. The value `template` does not count as a method and will be ignored.
331 | - **URL:**
332 | - **Path**: All paths will be concatenated, starting with the first heading (i.e. the topmost parent).
333 | - **Query**: Query string arguments will be merged. Values from child headings have higher priority.
334 | - **Fragment**: The last defined heading's URL fragment will be used.
335 | - **Headers**: All headers will be merged. Values from child headings have higher priority.
336 | - **Body**: The last request body present in a heading will be used (if no heading defines a body, none will be used).
337 |
338 | For the **URL Scheme**, **Host** and **Port** (i.e. the URL origin), the values of the last heading to define them will be used. **Important**: defining a new URL origin will make Verb ignore all properties defined in all parent headings, thus effectively starting a new headings tree of request definitions. In most cases URL origins should be defined in the topmost parent headings.
339 |
340 | If you try to send a request from the level 1 header, you'll get an error, as at that level there's no specified HTTP method.
341 |
342 | Finally, you can create hierarchies with any number of headings, with many levels of nesting. A good idea is to create a single `.org` file to describe, for example, a single HTTP API. This file will contain a level 1 heading defining some common attributes, such as the URL scheme, host and root path, along with an `Authentication` header. The level 2 headings will specify different resources (e.g. `users`, `products`, etc.), and the level 3 headings will specify actions to run on those resources (e.g. `post`, `put`, etc.). An example of this can be seen in [examples/foobar.org](examples/foobar.org).
343 |
344 | ### Modifying Requests before Sending
345 |
346 | As you add more and more headings with different properties, it can get hard to track what will actually be sent once you use one of the `verb-send-request-on-point-*` commands. To review a request before it is sent, use the keyboard prefix argument C-u before invoking one of the send commands. This will open a temporary buffer which will contain only the request that is about to be sent. In this buffer, you can actually modify the contents of the request in whatever way you like. By doing this, you can try different variations of one request, without having to edit your `.org` file.
347 |
348 | Once you have finished reviewing/modifying the request, press C-c C-c to send it. If you don't want to send the request, press C-c C-k to kill the buffer.
349 |
350 | > [!WARNING]
351 | > Any changes done in the temporary buffer will not be saved.
352 |
353 | ### Emacs Lisp Code Tags
354 |
355 | You can embed Emacs Lisp code inside request specifications by using code tags. When sending the request, Verb will evaluate all code tags, and replace them with the results of the evaluations. Code tags may appear anywhere in the request specification: the URL, method, headers and body. By default, code tags are delimited with `{{` and `}}` (see the customizable variable `verb-code-tag-delimiters`). Note that code tags are in no way related to [Org mode macros](https://orgmode.org/manual/Macro-Replacement.html).
356 |
357 | Depending on the type of the resulting value for a code tag, Verb will do the following:
358 | - `string`: The value will be inserted as-is into the request contents.
359 | - `buffer`: The buffer's contents will be inserted into the request using `insert-buffer-substring`. If the buffer's `verb-kill-this-buffer` variable is set to non-`nil`, the buffer will be killed after its contents have been read. The variable's default value is `nil`.
360 | - Other types: The value will be converted to a string using `(format "%s" result)` and inserted into the request contents.
361 |
362 | Let's extend the previous example so that it now uses code tags:
363 | ```
364 | * User management :verb:
365 | template https://reqres.in/api/users
366 | Accept: application/json
367 |
368 | ** Get users list
369 | get
370 | Content-Language: de-DE
371 |
372 | ** Create a user
373 | post
374 | Content-Type: application/json; charset=utf-8
375 |
376 | {
377 | "name": "{{(user-full-name)}}",
378 | "age": "{{(read-string "Age: ")}}"
379 | }
380 | ```
381 |
382 | Notice that interactive functions like `read-string` can be used inside code tags as well - they will be evaluated before the request is sent, and the resulting value will be inserted into the content.
383 |
384 | ### Code Completion
385 |
386 | You can enable completion for Emacs Lisp inside code tags. To do this, set the `verb-enable-elisp-completion` variable to `t` (the default value). Code completion will work automatically with [`company-mode`](https://github.com/company-mode/company-mode), if it is installed.
387 |
388 | Note that the point must be surrounded by the code tag delimiters (e.g. `{{` and `}}`) in the same line for completion to work. If you're using `electric-pair-mode`, matching tag delimiters will be inserted automatically, so this won't be a problem. `verb-mode` should also be enabled, as enabling it will load the completion function itself.
389 |
390 | ### Utility Functions
391 |
392 | Verb offers some utility functions to be used within code tags, such as:
393 | - `verb-shell`: Returns output of `shell-command-to-string`, optionally trimming it.
394 | - `verb-url`: Currently, just an alias to `url-encode-url`.
395 | - `verb-unix-epoch`: Returns the current UNIX epoch (seconds) as an integer.
396 | - `verb-json-get`: Retrieves a value from within a JSON value.
397 | - `verb-read-file`: Reads the contents of a file (following some additional Verb-specific behaviour).
398 | - `verb-headers-get`: Retrieves the value of an HTTP header.
399 |
400 | ### Verb Variables
401 |
402 | Let's suppose that the two endpoints from the previous example now require authentication to be used. We could then modify the example to look like this:
403 | ```
404 | * User management :verb:
405 | template https://reqres.in/api/users
406 | Accept: application/json
407 | Authentication: {{(verb-var token)}}
408 |
409 | ** Get users list
410 | get
411 | Content-Language: de-DE
412 |
413 | ** Create a user
414 | post
415 | Content-Type: application/json; charset=utf-8
416 |
417 | {
418 | "name": "{{(user-full-name)}}",
419 | "age": "{{(read-string "Age: ")}}"
420 | }
421 | ```
422 |
423 | The example now uses the `verb-var` macro in the first code tag. This macro essentially returns the value associated with the specified symbol - in this case, `token`. If the symbol does not have any associated value yet, the user is prompted for one using `read-string`. The value is then associated with the symbol and returned. If you don't wish to be prompted for a value, you can specify a second parameter, which will be used as the default value. That value will be associated to the symbol the first time `verb-var` is invoked.
424 |
425 | If you wish to explicitly re-set the value of a variable set with `verb-var`, use the `verb-set-var` interactive command. The command is bound to C-c C-r C-v by default, and works similarly to the built-in `set-variable` command. You will be prompted for a variable that has been previously set with `verb-var`. You may also specify a completely new variable name, in which case it will be created and its value set. To see the current value of all variables, use the `verb-show-vars` command. To unset all variable values, use the `verb-unset-vars` command.
426 |
427 | To quickly copy the value of a variable into the clipboard, use the keyboard prefix argument C-u before invoking `verb-set-var`.
428 |
429 | `verb-var` and `verb-set-var` are useful for writing requests that include sensitive information (such as passwords or tokens), or for writing requests that can be parameterized with different values (such as IDs or search terms).
430 |
431 | > [!WARNING]
432 | > Values set with `verb-var` and `verb-set-var` will be lost if the buffer is killed.
433 |
434 | ### Verb Heading properties
435 |
436 | When writing a request specification, you may add [properties](https://orgmode.org/manual/Property-Syntax.html) via the Org special `:properties:`/`:end:` drawer to its heading. Any properties starting with `Verb-` (case insensitive) will be added to the request as metadata. Other properties will be ignored.
437 |
438 | Some aspects of Verb can be controlled via these properties, such as:
439 |
440 | - `Verb-Prelude`
441 | - `Verb-Store`
442 | - `Verb-Map-Request`
443 | - `Verb-Map-Response`
444 | - `Verb-Proxy`
445 | - `Verb-Max-Redirections`
446 |
447 | All of these are explained in later sections of this guide.
448 |
449 | > [!NOTE]
450 | > When reading Org heading properties, properties defined in parent headings are ignored by default (i.e. they are not inherited or passed down). This can be controlled using the `org-use-property-inheritance` variable (default: `nil`).
451 |
452 | ### Verb Variables from Preludes
453 |
454 | To further keep sensitive information safe and separate from Verb `.org` files, Verb variables can also be defined from either JSON or Emacs Lisp external files. Use the `Verb-Prelude` property followed by the path (relative to the current Org file, or absolute) of the external file to load. The file will loaded and applied as a prelude before requests are sent. See the next section to learn how to load preludes directly from the `.org` file as well (inline).
455 |
456 | > [!NOTE]
457 | > Files that are GPG or EasyPG encrypted can opened and decrypted automatically by Emacs if configured appropriately. See [Emacs Auth-source manual](https://www.gnu.org/software/emacs/manual/auth.html) for more information. It is strongly recommended to use GPG or EasyPG when storing credentials in files.
458 |
459 | The value for `Verb-Prelude` may be set globally as an [in-buffer setting](https://orgmode.org/manual/In_002dbuffer-Settings.html), or on each heading level as a property. When a request is sent, Verb will first load the global `Verb-Prelude` external file, and then will load all `Verb-Prelude`s starting from the topmost parent heading, down to the one being sent. This implies that lower-level headings can re-define variables set in upper headings, if needed.
460 |
461 | Below is an example of `Verb-Prelude` as an in-buffer setting, plus an additional definition in the `Blog API` heading.
462 |
463 | ``` org
464 | #+Verb-Prelude: prod-foobar-env.el
465 |
466 | * Blog API :verb:
467 | :properties:
468 | :Verb-Prelude: dev-foobar-env.el
469 | :end:
470 | template https://foobar-blog-api.org/api/v1
471 | Accept: application/json
472 |
473 | ** Users
474 | get /users
475 |
476 | ** Posts
477 | get /posts
478 | ```
479 |
480 | In the scenario, when sending the `get /users` request under `Users`, `prod-foobar-env.el` is loaded first from the `#+Verb-Prelude:` in-buffer setting. Then, `dev-foobar-env.el` is loaded from the property defined under the `Blog API` header. The `dev-` file would override any variables having the same key name between the two environment files. A common example would be an `api_token` Verb variable that would likely be different between the two environments, but on the other hand `user_name` could be the same for both environments. It would be logical to then have an `api_token` variable specified in both, depending on environments of requests. One could switch between one environment and the other by removing the `:properties:` block, or via some custom code in the Emacs Lisp file.
481 |
482 | Here's an example of what an Emacs Lisp file loaded via `Verb-Prelude` could look like:
483 |
484 | ``` elisp
485 | ;; Shared
486 | (verb-set-var "user" "max_mustermann")
487 | (verb-set-var "email" user-mail-address)
488 |
489 | ;; Production
490 | (verb-set-var "token" "abcdef123456")
491 |
492 | (message "Variables loaded")
493 | ```
494 |
495 | In above, a couple of advantages to using Emacs Lisp prelude files is shown, such as having comments; dynamically getting email address from the Emacs `user-mail-address` variable; and outputting messages, which can be useful for logging and debugging.
496 |
497 | For JSON prelude files, values (and first level sub-values) are set using `verb-set-var` for each key-value pair. For example:
498 |
499 | ```json
500 | {
501 | "user": "max_mustermann",
502 | "email": "email@example.com",
503 | "token": "abcdef123456",
504 | "env_ids": {
505 | "prod": "aaa111",
506 | "dev": "zzz999"
507 | }
508 | }
509 | ```
510 |
511 | Would result in the following Verb variables being set:
512 |
513 | ```text
514 | user: max_musterman
515 | email: email@example.com
516 | token: abcdef123456
517 | env_ids: (:prod aaa111 :dev zzz999) ; this is a plist
518 | prod: aaa111
519 | dev: zzz999
520 | ```
521 |
522 | ### Inline Preludes
523 |
524 | If you do not with to keep your Verb `.org` file separate from your variable declarations, it is also possible to specify either Emacs Lisp or JSON content directly in the `Verb-Prelude` property. For example, for Emacs Lisp:
525 |
526 | ```text
527 | :properties:
528 | :Verb-Prelude+: (verb-set-var "user" "max_mustermann")
529 | :Verb-Prelude+: (verb-set-var "email" user-mail-address)
530 | :end:
531 | ```
532 |
533 | And for JSON:
534 |
535 | ```text
536 | :properties:
537 | :Verb-Prelude+: {
538 | :Verb-Prelude+: "user": "max_mustermann",
539 | :Verb-Prelude+: "email": "email@example.com"
540 | :Verb-Prelude+: }
541 | :end:
542 | ```
543 |
544 | > [!IMPORTANT]
545 | > Note the `+` suffix for the `Verb-Prelude` property; this tells Org mode to collect every line of the property into a multiline string, instead of just one.
546 |
547 | ### Last Response
548 |
549 | If you wish to access the last response's attributes, use the `verb-last` variable (type: `verb-response`). The following example does this; add it to the ending of your `guide.org` file:
550 |
551 | ```
552 | (...)
553 |
554 | ** Get last created user
555 | # Extract the "id" value from the previous
556 | # JSON response body.
557 |
558 | get /{{(verb-json-get (oref verb-last body) "id")}}
559 | Accept: application/json
560 | ```
561 |
562 | The `verb-json-get` (mentioned earlier in this guide) function takes a JSON-formatted text as its first argument and a list of keys as the rest, and returns the value under those keys in the JSON text (similar to how [JSONPath](https://goessner.net/articles/JsonPath/) works). This function is useful for using previous responses' contents, check its documentation for more details.
563 |
564 | If you wish to use the last response's headers instead, you can use the `verb-headers-get` function. An example call may look like: `(verb-headers-get verb-last "Content-Type")`, which will return the string contents of the `Content-Type` response header.
565 |
566 | ### Storing Responses by Key
567 |
568 | The `Verb-Store` Org property is used by Verb. When this property is set, Verb will automatically store the request's response under the specified value. To retrieve the response later, use the `verb-stored-response` function. It takes as an argument the same string key used previously.
569 |
570 | So, for example, we could modify our create/retrieve user endpoints like so:
571 |
572 | ```
573 | (...)
574 |
575 | ** Create a user
576 | :properties:
577 | :Verb-Store: new-user
578 | :end:
579 |
580 | post
581 | Content-Type: application/json; charset=utf-8
582 |
583 | {
584 | "name": "{{(user-full-name)}}",
585 | "age": "{{(read-string "Age: ")}}"
586 | }
587 |
588 | ** Get last created user
589 | get /{{(verb-json-get (oref (verb-stored-response "new-user") body) "id")}}
590 | Accept: application/json
591 | ```
592 |
593 | After the "Create a user" request has been sent at least once, the result will be stored internally under "new-user". It can then be used later at any time. Sending the request again will overwrite the previous value, and killing the response buffer will not erase the stored response. The `Verb-Store` mechanism is a bit more robust than using just `verb-last`, as sending any (unrelated) request will always re-set `verb-last` globally.
594 |
595 | ### Request Mapping Functions
596 |
597 | The `Verb-Map-Request` Org property is used by Verb as well. When present, it can be used to specify a mapping function than will be called right before the corresponding request is sent or exported, with the request itself as its sole argument. The function must return the same request specification object (type `verb-request-spec`), or a new one. With this, it is possible to apply custom transformations to requests before they are sent or exported.
598 |
599 | So, for example, having the following function:
600 | ```elisp
601 | (defun remove-body-newlines (rs)
602 | ;; RS is of type `verb-request-spec'
603 | (oset rs body (replace-regexp-in-string "\n" " " (oref rs body)))
604 | rs)
605 | ```
606 |
607 | We could add the following level 2 heading to the example in the previous section:
608 |
609 | ```
610 | (...)
611 |
612 | ** Upload file to user storage
613 | :properties:
614 | :Verb-Map-Request: remove-body-newlines
615 | :end:
616 |
617 | post /{{(verb-var user-id)}}/upload
618 | Content-Type: text/plain; charset=utf-8
619 |
620 | foo,
621 | bar,
622 | baz
623 | ```
624 |
625 | When sent or exported, the request's body will by modified by `remove-body-newlines`, and the resulting body content will be a single line, `foo,bar,baz`.
626 |
627 | The function to be mapped can also be a `lambda` expression, like so:
628 |
629 | ```
630 | (...)
631 |
632 | ** Upload file to user storage
633 | :properties:
634 | :Verb-Map-Request+: (lambda (rs)
635 | :Verb-Map-Request+: (thread-last
636 | :Verb-Map-Request+: (oref rs body)
637 | :Verb-Map-Request+: (replace-regexp-in-string "\n" " ")
638 | :Verb-Map-Request+: (oset rs body))
639 | :Verb-Map-Request+: rs)
640 | :end:
641 |
642 | post /{{(verb-var user-id)}}/upload
643 | Content-Type: text/plain; charset=utf-8
644 |
645 | foo,
646 | bar,
647 | baz
648 | ```
649 |
650 | This has the same effect as the previous example. Note also how we've used the feature of adding to a propertie's value. The final `lambda` expression will be equivalent to:
651 |
652 | ```elisp
653 | (lambda (rs) (thread-last (oref rs body) (replace-regexp-in-string "\n" " ") (oset rs body)) rs)
654 | ```
655 |
656 | > [!NOTE]
657 | > The mapping function will be called after evaluating code tags, and the request specification passed will already have its inherited/overridden values from parent headings.
658 |
659 | ### Response Mapping Functions
660 |
661 | Similar to `Verb-Map-Request`, it is also possible to apply functions to HTTP responses by using the `Verb-Map-Response` Org property. The value of this property must be either a symbol pointing to a function, or a function itself (using `lambda`). The function must take exactly one parameter (the response as a `verb-response` object) and must return a `verb-response` object as well. The function will be called with `(current-buffer)` taking the value of the buffer where the HTTP response will be displayed in. It is perfectly valid to include code within the function that has side effects, e.g. calling `setq` to set a global variable.
662 |
663 | Here's an example of a response mapping function that makes the body contents upper case:
664 |
665 | ```elisp
666 | (defun uppercase-body (resp)
667 | ;; RESP is of type `verb-response'.
668 | (oset resp body (upcase (resp body)))
669 | resp)
670 | ```
671 |
672 | And applying it:
673 |
674 | ```
675 | (...)
676 |
677 | ** Fetch from user storage
678 | :properties:
679 | :Verb-Map-Response: uppercase-body
680 | :end:
681 | get /{{(verb-var user-id)}}/storage/{{(verb-var file-id)}}
682 | ```
683 |
684 | Notice how updating the response's body (which is a string) will automatically update the contents of the response buffer.
685 |
686 | Here's an example of a response mapping function being applied for side effects only:
687 |
688 | ```
689 | (...)
690 |
691 | ** Fetch the user token
692 | :properties:
693 | :Verb-Map-Response+: (lambda (resp)
694 | :Verb-Map-Response+: (setq global-token (verb-json-get (oref resp body) "id"))
695 | :Verb-Map-Response+: resp)
696 | :end:
697 | post /{{(verb-var user-id)}}/token-auth
698 |
699 | {
700 | "user": "johnsmith",
701 | "password": "mypassword"
702 | }
703 | ```
704 |
705 | ### Body Lines starting with `*`
706 |
707 | You may have noticed that because headings start with `*`, you cannot include lines starting with `*` in your request bodies, because Org will interpret them as a new heading. To get around this, you can prefix request body lines starting with `*` with an empty code tag, `{{}}`. The empty code tag will evaluate to the empty string, so it won't modify the content of your request body. Following from our previous example, we can modify it like so:
708 |
709 | ```
710 | (...)
711 |
712 | ** Upload file to user storage
713 | post /{{(verb-var user-id)}}/upload
714 | Content-Type: text/markdown; charset=utf-8
715 |
716 | # Sample Markdown file
717 |
718 | {{}}**This text is bold.**
719 | {{}}*This text is italicized.*
720 | ```
721 |
722 | ### File Uploads
723 |
724 | To upload a file, you can use the included `verb-read-file` function. This function reads a file into a buffer and sets its `verb-kill-this-buffer` variable to `t`, and then returns the buffer. Use it from inside code tags to insert the contents of a local file in a request. To test this, we can modify the previous example so that instead of manually writing a Markdown file, we now read one from disk:
725 |
726 | ```
727 | (...)
728 |
729 | ** Upload file to user storage
730 | post /{{(verb-var user-id)}}/upload
731 | Content-Type: text/markdown; charset=utf-8
732 |
733 | {{(verb-read-file "documents/myfile.md")}}
734 | ```
735 |
736 | Remember to specify `Content-Type` in your HTTP headers, as Verb won't do this for you. This will let the server know how to interpret the contents of the request.
737 |
738 | > [!TIP]
739 | > If uploading binary files (e.g. a PNG image), it's a good idea to set `verb-read-file`'s second argument (`coding-system`) to `'binary`. This will instruct Emacs to insert the file contents into the request buffer as raw bytes.
740 |
741 | ### URL-encoded Form Submission
742 |
743 | Verb includes a utility function in order to use the [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#url-encoded_form_submission) content type in your requests: `verb-util-form-url-encode`. This function takes an alist of `(KEY . VALUE)`, where `KEY` and `VALUE` are strings. Use this in your request specification body, along with the correct `Content-Type` header value, in order to perform a URL-encoded form submission:
744 |
745 | ```
746 | (...)
747 |
748 | ** Fetch the user token (login)
749 | post /{{(verb-var user-id)}}/token-auth
750 | Content-Type: application/x-www-form-urlencoded
751 |
752 | {{(verb-util-form-url-encode '(("user" . "johnsmith") ("password" . "mypassword")))}}
753 | ```
754 |
755 | > [!NOTE]
756 | > The `verb-util-form-url-encode` function will take each key-value pair, URL-encode them and join them with `=`, and then join all the elements with `&` to produce the final string. This can also be achieved by manually typing out the key-values in the request body in a single line (e.g. `user=johnsmith&password=mypassword`).
757 |
758 | ### Multipart Form Submission
759 |
760 | Verb also includes some utility functions in order to use the [`multipart/form-data`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#multipart_form_submission) content type in your requests. Two are currently provided: `verb-boundary` and `verb-part`.
761 |
762 | When `verb-boundary` is called using code tags within a request specification, it will return a string containing a valid randomly-generated multipart boundary. This function must be called at least once in order to establish the boundary value when a request is being constructed from request specifications.
763 |
764 | On the other hand, the `verb-part` function can be used in code tags to start new parts (when called with at least one argument), and also to insert the final boundary delimiter (when called with no arguments). The first argument will correspond to the `name` attribute of the `Content-Disposition` header, and the second to the `filename` attribute of the same header.
765 |
766 | The following is an example that combines these two functions, along with `verb-read-file`:
767 |
768 | ```
769 | (...)
770 |
771 | ** Upload two files to user storage
772 | :properties:
773 | :Verb-Map-Request: verb-body-lf-to-crlf
774 | :end:
775 |
776 | post /{{(verb-var user-id)}}/upload
777 | Content-Type: multipart/form-data; boundary={{(verb-boundary)}}
778 |
779 | {{(verb-part "file" "file1.txt")}}
780 | Content-Type: text/plain
781 |
782 | {{(verb-read-file "documents/file1.txt")}}
783 | {{(verb-part "file" "file2.xml")}}
784 | Content-Type: application/xml
785 |
786 | {{(verb-read-file "documents/file2.xml")}}
787 | {{(verb-part)}}
788 | ```
789 |
790 | > [!IMPORTANT]
791 | > In most cases, you will also need to apply the `verb-body-lf-to-crlf` function to your request before it is sent. This is needed to ensure that all line endings in the request body use CRLF instead of just LF. This is also shown in the example above.
792 |
793 | > [!NOTE]
794 | > `verb-body-lf-to-crlf` will automatically ignore content specifically inserted with `verb-read-file`, so it will not break your requests if the file read contained newlines. This feature only works on Emacs 28.1 and newer.
795 |
796 | ### Base Headers
797 |
798 | You can define a set of base headers for all your HTTP requests in all `.org` files via the `verb-base-headers` variable. These headers will be defined globally, but may still be overridden by re-specifying them somewhere in the headings hierarchy. The variable must be set to an alist of `(KEY . VALUE)` elements, where `KEY` and `VALUE` are strings. For example, here's how to add a `User-Agent` header to all requests in all files from your `init.el`:
799 |
800 | ```elisp
801 | (setq verb-base-headers '(("User-Agent" . "my-user-agent")))
802 | ```
803 |
804 | ### Export Requests
805 |
806 | You can export request specifications to other formats or tools by using the `verb-export-request-on-point` command, by default bound to C-c C-r C-e. When used, you will be prompted for an export function. The ones currently available are:
807 | - `curl`: Convert the request specification into a [curl](https://curl.haxx.se/) command and add it to the kill ring (clipboard).
808 | - `verb`: Display the request specification in the same format Verb uses. This is still useful as the request displayed will be the one generated by combining the properties of the parent headings as well.
809 | - `eww`: Perform the request described by the specification using EWW (Emacs Web Wowser). This will only work on `GET` requests.
810 | - `websocat`: Convert the request specification into a [websocat](https://github.com/vi/websocat) command and add it to the kill ring.
811 |
812 | > [!NOTE]
813 | > Code tags will be evaluated when exporting a request.
814 |
815 | ### Long Lines
816 |
817 | Sometimes, lines containing URLs of your request specifications may become so long, that they may become difficult to read. You can break up these lines by using `\` followed by a newline character, like so:
818 |
819 | ```
820 | * Make a request to an API :verb:
821 |
822 | get https://example.com/api/users?fields=id,name,age\
823 | &orderby=name,descending\
824 | &filter=id>1000\
825 | &count=false
826 | ```
827 |
828 | The `\` character, the newline, and all the leading whitespace in the next line will be ignored. This behaviour only applies to the URL lines, not for the headers, nor the body.
829 |
830 | ### Cookies
831 |
832 | The Emacs `url` library (which Verb uses) has [support for cookies](https://www.gnu.org/software/emacs/manual/html_node/url/Cookies.html). This means that responses with the `Set-Cookie` header present will create cookies locally, that will later be sent back via the `Cookie` header.
833 |
834 | ### Babel Integration
835 | Verb also works on Org [Babel](https://orgmode.org/worg/org-contrib/babel/) source blocks. This feature allows you to send an HTTP request, and view the results in the same `.org` buffer where the request was read from. You can also export requests to different formats (like `curl`) and view the results in the same buffer as well.
836 |
837 | To enable this feature, remember to add `verb` to the `org-babel-load-languages` list. To do this, you may add the following to your `init.el`:
838 | ```elisp
839 | (org-babel-do-load-languages
840 | 'org-babel-load-languages
841 | '((verb . t)))
842 | ```
843 |
844 | Once that's done, simply wrap your HTTP request specification (excluding the Org heading) with `#+begin_src`/`#+end_src` using `verb` as the source block language. For example, given the following request:
845 | ```
846 | * Make a request to an API :verb:
847 |
848 | post https://example.com/api/users
849 | Content-Type: application/json; charset=utf-8
850 |
851 | {
852 | "name": "Jane Smith",
853 | "age": "35"
854 | }
855 | ```
856 |
857 | The Babel-compatible version would be:
858 | ```
859 | * Make a request to an API :verb:
860 |
861 | #+begin_src verb :wrap src ob-verb-response
862 | post https://example.com/api/users
863 | Content-Type: application/json; charset=utf-8
864 |
865 | {
866 | "name": "Jane Smith",
867 | "age": "35"
868 | }
869 | #+end_src
870 | ```
871 |
872 | Babel source blocks with `verb` as a language accept a header argument called `:op`. Depending on the value that appears after this argument, Verb will execute different actions when C-c C-c is pressed.
873 |
874 | > [!TIP]
875 | > It is possible to specify arguments for a `verb` source block by using the [`:var` keyword](https://orgmode.org/manual/Environment-of-a-Code-Block.html). To read the arguments, use `(verb-var )` inside a code block.
876 |
877 | #### Sending Requests (`:op send`)
878 |
879 | By default, if `:op` is not specified, Verb will assume `:op send` was intended.
880 |
881 | To send the request, move the point to its `verb` source block and press C-c C-c. The result of the request will appear below. Adding the `:wrap src ob-verb-response` argument tells Babel to wrap the response in another source block, using `ob-verb-response-mode` as major mode for font locking.
882 |
883 | As opposed to requests sent with the `verb-send-request-on-point-*` commands, requests sent with Babel will block Emacs until they are complete. There's a configurable timeout for this, see the `verb-babel-timeout` variable for more details.
884 |
885 | > [!IMPORTANT]
886 | > When Verb operates on a Babel source block, **it still takes into consideration the whole headings hierarchy**. This means that any attributes defined in parent headings will be brought over and potentially overridden by the current source block's. The request specifications in the parent headings may be defined in Babel source blocks as well, Verb will read them anyways. In other words, you can freely mix between regular request specifications and request specification written inside Babel source blocks within the hierarchy.
887 |
888 | > [!TIP]
889 | > The heading containing the source block where C-c C-c is pressed does not need to be tagged with `:verb:`.
890 |
891 | > [!TIP]
892 | > It is still possible to send requests defined within Babel source blocks using the `verb-send-request-on-point-*` commands, as if they were defined without a source block. If more than one source blocks are found under an Org heading, then the one on point will be used.
893 |
894 | #### Send with Partial Retrieval (`:op send ...`)
895 |
896 | Instead of specifying just `:op send`, you may add an additional argument: `get-headers` or `get-body`. Using the former will change the result of executing the source block to just the response headers. Using the latter will do the same, but for the response body. Here's an example:
897 |
898 | ```
899 | * Make a request to an API (get body only) :verb:
900 | #+begin_src verb :wrap src ob-verb-response :op send get-body
901 | post https://example.com/api/users
902 | Content-Type: application/json; charset=utf-8
903 |
904 | {
905 | "name": "Jane Smith",
906 | "age": "35"
907 | }
908 | #+end_src
909 | ```
910 |
911 | #### Exporting Requests (`:op export ...`)
912 |
913 | If you wish to export the request to a particular format instead, use the `:op export ...` header argument on your source block. These are the values it can be used with:
914 | - `:op export curl`: Export this request to `curl` format and insert the results below.
915 | - `:op export verb`: Export this request to Verb format and insert the results below.
916 | - `:op export websocat`: Export this request to `websocat` format and insert the results below.
917 |
918 | So for example, if you wanted to export the previous example to `curl`, you would need to write:
919 | ```
920 | * Export request to curl :verb:
921 | #+begin_src verb :op export curl
922 | post https://example.com/api/users
923 | Content-Type: application/json; charset=utf-8
924 |
925 | {
926 | "name": "Jane Smith",
927 | "age": "35"
928 | }
929 | #+end_src
930 | ```
931 |
932 | And then execute the source block again with C-c C-c, which will execute the export and insert the results below.
933 |
934 | ### Redirections
935 |
936 | Behaviour for redirections is configured via the `url` library variable `url-max-redirections`. Its default value is 30. To disable redirections, set this variable to 0 using `setq`.
937 |
938 | If the maximum number of redirections has been reached and the last HTTP response received had a `3XX` status, then Verb will return the contents of this last response. It is then usually possible to access the value of the `Location` header for information on the last redirection:
939 |
940 | ```elisp
941 | (verb-headers-get verb-http-response "Location")
942 | ```
943 |
944 | If wish to set the `url-max-redirections` only for a specific request, setting `url-max-redirections` as a buffer-local will not work due to how the `url` library is designed. Instead, use the `Verb-Max-Redirections` Org property:
945 |
946 | ```
947 | ** Make a request with 0 redirections :verb:
948 | :properties:
949 | :Verb-Max-Redirections: 0
950 | :end:
951 |
952 | get http://example.com
953 | ```
954 |
955 | ### Proxies
956 | There's two ways of using HTTP proxies in Verb. The first one is to manually configure the `url-proxy-services` variable like explained in [Proxies and Gatewaying](https://www.gnu.org/software/emacs/manual/html_node/url/Proxies.html). The second one is to specify a proxy address by using the `Verb-Proxy` heading property:
957 |
958 | ```
959 | ** Make a request using an HTTP proxy :verb:
960 | :properties:
961 | :Verb-Proxy: my-proxy:5050
962 | :end:
963 |
964 | get http://internal-api/users
965 | ```
966 |
967 | When the request is sent, the value of `Verb-Proxy` will automatically be added to `url-proxy-services`, and then automatically removed.
968 |
969 | ### Customization
970 |
971 | To see all aspects of Verb that may be customized, use M-x `customize-group` RET `verb` RET.
972 |
973 | ### Verb Log
974 |
975 | When you send a request or receive a response, some information is logged in the `*Verb Log*` buffer. You can use this log to get some more details on any errors that might have happened and other internal stuff. You can disable logging by setting the `verb-enable-log` variable to `nil`. To read the log, you can use the `verb-show-log` command. While reading the log, you can press q to go back to the previous buffer.
976 |
977 | The Emacs `url` library also keeps its own internal log - it can be useful for debugging requests that are not working as expected. To enable `url` logging, set `url-debug` to `t` (by default, it's disabled). After sending a request, switch to the `*URL-DEBUG*` buffer to read any logged information.
978 |
979 | ## Examples
980 |
981 | The [examples/](examples) directory contains various `.org` files which showcase different features of the package.
982 |
983 | ## Troubleshooting
984 | **Problem**: When trying to send a request, an error is shown: "No request specifications found".
985 |
986 | **Fix**: Tag the headings containing request specifications with `:verb:`. Tags are inherited by default, so in most cases you can just tag the topmost parent heading.
987 |
988 | ---
989 |
990 | **Problem**: URL elements containing underscores such as `page_size` are shown as subscripts ([Issue #3](https://github.com/federicotdn/verb/issues/3)).
991 |
992 | **Fix**: Set the `org-use-sub-superscripts` variable to `{}` or `nil`. You can do this file-locally by adding the following at the end of the file:
993 | ```
994 | # Local Variables:
995 | # org-use-sub-superscripts: {}
996 | # End:
997 | ```
998 |
999 | ## Changelog
1000 |
1001 | The changelog for this project can be found in [CHANGELOG.md](CHANGELOG.md).
1002 |
1003 | ## Contributing
1004 |
1005 | > [!IMPORTANT]
1006 | > Though this package is actively maintained, I am currently not accepting pull requests, as I do not have enough time to review them properly. Please open an issue instead. However, the below instructions may still be useful for other use cases.
1007 |
1008 | Ideally, new features and functions should include tests, see file `test/verb-test.el`. To run the tests locally, you will need to have Go 1.22+ installed. Once you do, you can run the tests:
1009 | ```bash
1010 | $ make test
1011 | ```
1012 |
1013 | To run only one test, set the `SELECTOR` environment variable to the tests's name:
1014 | ```bash
1015 | $ SELECTOR=test-nonempty-string make test
1016 | ```
1017 |
1018 | `S` works as well:
1019 | ```bash
1020 | $ S=test-nonempty-string make test
1021 | ```
1022 |
1023 | You can also check for byte-compilation warnings and documentation/package issues. First, run (needed only once):
1024 | ```bash
1025 | $ make setup-check
1026 | ```
1027 |
1028 | After that, run the checks:
1029 | ```bash
1030 | $ make check
1031 | ```
1032 |
1033 | It's a good idea to test your changes on a vanilla Emacs instance (`-q` flag). To easily do this, use the `run` recipe:
1034 | ```bash
1035 | $ make run
1036 | ```
1037 |
1038 | Finally, a list of all recipes and their descriptions can be obtained using `make help` or simply `make`.
1039 |
1040 | A PR will need to successfully go through all the checks mentioned above in order to be reviewed first. Please remember to target your PR against the `main` branch (not `master`).
1041 |
1042 | ## Related Packages
1043 |
1044 | Verb's functionality can be extended via some related packages, such as:
1045 | - [impostman](https://github.com/flashcode/impostman): Can be used to import [Postman](https://www.postman.com/) collections into Verb.
1046 |
1047 | ## Similar Packages
1048 |
1049 | - [restclient](https://github.com/pashky/restclient.el): Verb is an attempt to improve upon the core idea of the `restclient` package: writing request specifications on a buffer, and receiving the responses on another. As of April 17, 2024 `restclient` has been archived and is no longer maintained.
1050 | - [walkman](https://github.com/abrochard/walkman): Write HTTP requests in Org mode and send them using `curl`.
1051 | - [plz-see.el](https://github.com/astoff/plz-see.el): An interactive HTTP client for Emacs based on the [plz.el](https://github.com/alphapapa/plz.el) library.
1052 | - [hurl-mode](https://github.com/JasZhe/hurl-mode): Emacs mode for `hurl`, a CLI HTTP tool.
1053 |
1054 | ## Contributors
1055 | These are the users that have contributed to developing Verb, via code and/or documentation (in order of date of first contribution):
1056 | - [stig](https://github.com/stig)
1057 | - [flashcode](https://github.com/flashcode)
1058 | - [ananthakumaran](https://github.com/ananthakumaran)
1059 | - [prashantvithani](https://github.com/prashantvithani)
1060 | - [c4710n](https://github.com/c4710n)
1061 | - [bigodel](https://github.com/bigodel)
1062 | - [agzam](https://github.com/agzam)
1063 | - [isamert](https://github.com/isamert)
1064 | - [jeff-phil](https://github.com/jeff-phil)
1065 | - [ahungry](https://github.com/ahungry)
1066 |
1067 | Thank you!
1068 |
1069 | ## License
1070 |
1071 | Distributed under the GNU General Public License, version 3.
1072 |
1073 | See [LICENSE](LICENSE) for more information.
1074 |
--------------------------------------------------------------------------------
/examples/README.md:
--------------------------------------------------------------------------------
1 | # Examples
2 |
3 | This directory contains various example `.org` files that can be used to interact with different real-world HTTP APIs. When reading from GitHub, make sure to use the "Raw" view of the files, as the generated preview won't include comments and other components of the text file.
4 |
--------------------------------------------------------------------------------
/examples/binary.org:
--------------------------------------------------------------------------------
1 | * Binary content type tests :verb:
2 | # Each subheading specifies a request for a binary content type
3 | # (non-text), like PDF documents, images, etc.
4 | template https://www.gnu.org
5 |
6 | ** PDF
7 | # Read a PDF document using doc-view-mode.
8 | get /licenses/quick-guide-gplv3.pdf
9 |
10 | ** Images
11 | template /graphics
12 |
13 | *** PNG image
14 | # Get a PNG image
15 | get /gnu-head.png
16 |
17 | *** JPG image
18 | # Get a JPG image
19 | get /bokma-gnu.jpg
20 |
21 | *** SVG image
22 | # Get a SVG image
23 | get /logo-fsf.org.svg
24 |
--------------------------------------------------------------------------------
/examples/daas.org:
--------------------------------------------------------------------------------
1 | * /dev/null as a Service :verb:
2 | # In modern days everything is a service. You create documents, upload
3 | # photos, deploy computers, but what’s happening to your trash? That’s
4 | # why we’re launching /dev/null to the cloud.
5 | #
6 | # https://devnull-as-a-service.com/home/
7 |
8 | post https://devnull-as-a-service.com/dev/null
9 | Content-Type: text/plain; charset=utf-8
10 |
11 | Hello!
12 |
--------------------------------------------------------------------------------
/examples/foobar.org:
--------------------------------------------------------------------------------
1 | * Foobar Blog API :verb:
2 | # Note: this API does not actually exist!
3 | # This is just for documentation purposes.
4 | # See README.md for more details.
5 | template https://foobar-blog-api.org/api/v1
6 | Accept: application/json
7 |
8 | ** Users
9 | template /users
10 |
11 | *** Create a user
12 | post
13 | Content-Type: application/json; charset=utf-8
14 |
15 | {
16 | "name": "John",
17 | "posts": []
18 | }
19 |
20 | *** Search users
21 | get ?name=John
22 |
23 | *** Delete all users
24 | delete
25 |
26 | ** Posts
27 | template /posts?lang=en
28 |
29 | *** Search posts
30 | get ?text=example
31 |
32 | *** Delete all posts
33 | delete
34 |
--------------------------------------------------------------------------------
/examples/hn.org:
--------------------------------------------------------------------------------
1 | * Hacker News API :verb:
2 | # Documentation and Samples for the Official HN API
3 | # https://github.com/HackerNews/API
4 |
5 | template https://hacker-news.firebaseio.com/v0
6 | Accept: application/json
7 |
8 | ** Item
9 | # Stories, comments, jobs, Ask HNs and even polls are just
10 | # items. They're identified by their ids, which are unique integers,
11 | # and live under /v0/item/.
12 |
13 | get /item/{{(read-string "Item ID: ")}}.json?print=pretty
14 |
15 | ** User
16 | # Users are identified by case-sensitive ids, and live under
17 | # /v0/user/. Only users that have public activity (comments or story
18 | # submissions) on the site are available through the API.
19 |
20 | get /user/{{(read-string "User ID: ")}}.json
21 |
22 | ** Live Data
23 | # The coolest part of Firebase is its support for change
24 | # notifications. While you can subscribe to individual items and
25 | # profiles, you'll need to use the following to observe front page
26 | # ranking, new items, and new profiles.
27 |
28 | *** Max Item ID
29 | # The current largest item id is at /v0/maxitem. You can walk backward
30 | # from here to discover all items.
31 | get /maxitem.json
32 |
33 | *** Top Stories
34 | get /topstories.json
35 |
36 | *** New Stories
37 | get /newstories.json
38 |
39 | *** Best Stories
40 | get /beststories.json
41 |
--------------------------------------------------------------------------------
/examples/html.org:
--------------------------------------------------------------------------------
1 | * Export to EWW example :verb:
2 | # Use C-c C-r C-w to perform the request using EWW
3 | get http://neverssl.com
4 | Accept: text/html
5 |
--------------------------------------------------------------------------------
/examples/httpbin.org:
--------------------------------------------------------------------------------
1 | * HTTPBin :verb:
2 | # A simple HTTP Request & Response Service.
3 |
4 | template https://httpbin.org
5 |
6 | ** Headers
7 | get /headers
8 |
--------------------------------------------------------------------------------
/examples/ipify.org:
--------------------------------------------------------------------------------
1 | * ipify API :verb:
2 | # A Simple Public IP Address API
3 | # https://www.ipify.org/
4 | # https://github.com/rdegges/ipify-api
5 |
6 | ** IPv4
7 | template https://api.ipify.org
8 |
9 | *** JSON
10 | get ?format=json
11 |
12 | *** Text
13 | get ?format=text
14 |
15 | ** IPv6
16 | template https://api6.ipify.org
17 |
18 | *** JSON
19 | get ?format=json
20 |
21 | *** Text
22 | get ?format=text
23 |
--------------------------------------------------------------------------------
/examples/multipart.org:
--------------------------------------------------------------------------------
1 | * ConvertAPI Multipart example :verb:
2 | # https://www.convertapi.com/doc/upload
3 | #
4 | # When source files must be converted multiple times, conversion
5 | # performance can be increased by uploading files once and converting
6 | # it multiple times without uploading it again. The uploaded file will
7 | # be stored in convertapi.com server for maximum period of 3 hours and
8 | # will be accessible by secret URL with UUID.
9 | post https://v2.convertapi.com/upload
10 |
11 | Content-Type: multipart/form-data; boundary={{(verb-boundary)}}
12 |
13 | {{(verb-part "file" "myfile.txt")}}
14 | Content-Type: text/plain
15 |
16 | {{(verb-read-file (read-file-name "Text file: "))}}
17 |
--------------------------------------------------------------------------------
/examples/open-library.org:
--------------------------------------------------------------------------------
1 | * Open Library API :verb:
2 | # Open Library has developed a suite of APIs to help developers get up
3 | # and running with our data. We encourage interested developers to
4 | # join the ol-tech mailing list to stay up-to-date with the latest
5 | # news, or dive in with our own development team at our bug tracker or
6 | # our GitHub source code repository.
7 |
8 | # Open Library has a RESTful API, best used to link into Open Library
9 | # data in JSON, YAML and RDF/XML. There's also an earlier JSON API,
10 | # which is deprecated now. This is only retained for backward
11 | # compatibility.
12 |
13 | # From: https://openlibrary.org/developers/api
14 |
15 | template https://openlibrary.org
16 | User-Agent: Verb/Emacs Emacs/{{emacs-version}}
17 | Accept: application/json
18 |
19 | ** Search
20 | # Open Library provides an experimental API to search.
21 | template /search.json
22 |
23 | *** By Title
24 | #+BEGIN_SRC verb :wrap src ob-verb-response
25 | get ?title={{(verb-var title)}}
26 | #+END_SRC
27 |
28 | *** By Author
29 | get ?author={{(verb-var author "Frank Herbert")}}
30 |
31 | ** Subjects
32 | # This API is experimental. Please be aware that this may change in future.
33 | get /subjects/{{(verb-var subject)}}.json
34 |
35 | ** Books
36 | :properties:
37 | :Verb-Store: book
38 | :end:
39 | # The API allows requesting information on one or more books using
40 | # ISBNs, OCLC Numbers, LCCNs and OLIDs (Open Library IDs).
41 |
42 | get /api/books?bibkeys=ISBN:{{(verb-var isbn)}}&format=json
43 |
44 | ** Book Cover
45 | # Get a book's cover based on the value of (verb-var isbn) and the
46 | # "book" stored response. To set those, make sure to execute "Books"
47 | # request at least once.
48 | get {{(verb-json-get (oref (verb-stored-response "book") body) (concat "ISBN:" (verb-var isbn)) "thumbnail_url")}}
49 | Accept: image/jpeg
50 |
--------------------------------------------------------------------------------
/examples/postman-echo.org:
--------------------------------------------------------------------------------
1 | * Postman Echo API :verb:
2 | # Postman Echo is service you can use to test your REST clients and
3 | # make sample API calls. It provides endpoints for GET, POST, PUT,
4 | # various auth mechanisms and other utility endpoints.
5 |
6 | # The documentation for the endpoints as well as example responses can
7 | # be found at https://postman-echo.com.
8 |
9 | template https://postman-echo.com
10 |
11 | ** GZIP test
12 | # This endpoint returns the response using gzip compression
13 | # algorithm. The uncompressed response is a JSON string containing the
14 | # details of the request sent by the client.
15 | get /gzip
16 | Accept-Encoding: gzip
17 |
18 | ** Stream test
19 | # This endpoint allows one to receive streaming http response using
20 | # chunked transfer encoding of a configurable length.
21 | get /stream/5
22 |
23 | ** Post
24 | # This endpoint echoes the HTTP headers, request parameters, the
25 | # contents of the request body and the complete URI requested when data
26 | # is sent as a form parameter.
27 | post /post
28 | Content-Type: application/json
29 |
30 | {
31 | "hello": 1, "bye": {}
32 | }
33 |
34 | *** Post (raw text)
35 | # Send some plain text instead of JSON. Get the text itself from a
36 | # local file.
37 | template
38 | Content-Type: text/plain
39 |
40 | {{(verb-read-file "../test/test.txt")}}
41 | ** Status code
42 | # This endpoint allows one to instruct the server which status code to
43 | # respond with.
44 | get /status/{{(read-number "Status: ")}}
45 |
--------------------------------------------------------------------------------
/examples/prelude.el:
--------------------------------------------------------------------------------
1 | (setq my-variable "some value")
2 |
--------------------------------------------------------------------------------
/examples/prelude.org:
--------------------------------------------------------------------------------
1 | * Prelude File Test :verb:
2 | :properties:
3 | :Verb-Prelude: prelude.el
4 | :end:
5 | post https://postman-echo.com/post
6 | Content-Type: text/plain
7 |
8 | {{my-variable}}
9 |
--------------------------------------------------------------------------------
/examples/req-res.org:
--------------------------------------------------------------------------------
1 | * REQ|RES :verb:
2 | # Test your front-end against a real API
3 | # A hosted REST-API ready to respond to your AJAX requests.
4 | # https://reqres.in/
5 |
6 | template https://reqres.in/api?delay=0
7 | Content-Type: application/json
8 |
9 | ** Users
10 |
11 | template /users
12 |
13 | *** Get endpoint headers
14 | head
15 |
16 | *** Get endpoint options
17 | options
18 |
19 | *** List users
20 |
21 | get ?page=1
22 |
23 | *** Create user
24 | post
25 | Content-Type: application/json
26 |
27 | {
28 | "name": "{{(user-login-name)}}",
29 | "age": 55
30 | }
31 |
32 | *** Operate on a single user
33 |
34 | template /2
35 |
36 | **** Get a single user
37 | get
38 |
39 | **** Replace a user
40 | put
41 |
42 | {
43 | "name": "Bob"
44 | }
45 |
46 | **** Update a user
47 | patch
48 |
49 | {
50 | "name": "Bob"
51 | }
52 |
53 | **** Delete a user
54 | delete
55 |
56 | ** Login
57 |
58 | post /login
59 |
60 | #+BEGIN_SRC javascript
61 | {
62 | "email": "eve.holt@reqres.in",
63 | "password": "hello"
64 | }
65 | #+END_SRC
66 |
--------------------------------------------------------------------------------
/examples/scryfall.org:
--------------------------------------------------------------------------------
1 | * Scryfall REST API :verb:
2 | # Scryfall is a powerful Magic: The Gathering card search.
3 |
4 | # Scryfall provides a REST-like API for ingesting our card data
5 | # programmatically. The API exposes information available on the
6 | # regular site in easy-to-consume formats.
7 | # https://scryfall.com/docs/api
8 |
9 | template https://api.scryfall.com
10 |
11 | ** Cards list
12 | # Returns a List object that contains all cards in Scryfall’s
13 | # database. This method is paginated, returning 175 cards at a
14 | # time. The cards are ordered roughly newest to oldest. Review the
15 | # documentation for paginating the List type.
16 |
17 | # Every card type in every language is returned, including planar
18 | # cards, schemes, Vanguard cards, tokens, emblems, and funny
19 | # cards. Make sure you’ve reviewed documentation for the Card type.
20 |
21 | # Scryfall currently has 267,162 cards, and this endpoint has 1527
22 | # pages. This represents more than 400 MB of JSON data: beware your
23 | # memory and storage limits if you are downloading the entire
24 | # database.
25 |
26 | get /cards
27 |
28 | *** Single card by ID
29 | # Returns a single card with the given Scryfall ID.
30 |
31 | get /{{(read-string "Card ID: " "4b332e3d-dcf4-4f62-8130-124ec5d23b90")}}?format=text
32 |
33 | *** Get a random card image
34 | # Returns a single random Card object.
35 |
36 | get /random?format=image
37 |
38 | ** Sets
39 | # Returns a List object of all Sets on Scryfall.
40 |
41 | get /sets
42 |
43 | *** Single set by ID
44 | # Returns a Set with the given Scryfall ID.
45 |
46 | get /{{(read-string "Set ID: " "914a6c6d-cb3b-45e8-a2db-9978a2339faf")}}
47 |
--------------------------------------------------------------------------------
/extra/curl2verb.py:
--------------------------------------------------------------------------------
1 | # Tested on: Python 3.10.6
2 |
3 | import argparse
4 | import sys
5 |
6 |
7 | def main() -> None:
8 | if len(sys.argv) < 2 or sys.argv[1] != "curl":
9 | print("usage: python3 curl2verb.py curl ", file=sys.stderr)
10 | exit(1)
11 |
12 | cmd = sys.argv[2:]
13 |
14 | parser = argparse.ArgumentParser()
15 | parser.add_argument("url")
16 | parser.add_argument("-H", action="append", dest="headers")
17 | parser.add_argument("-X", dest="verb", default="GET")
18 | parser.add_argument("--compressed", action="store_true")
19 |
20 | args = parser.parse_args(cmd)
21 |
22 | print(f"{args.verb.lower()} {args.url}")
23 | for header in args.headers:
24 | print(header)
25 |
26 | print()
27 |
28 |
29 | if __name__ == "__main__":
30 | main()
31 |
--------------------------------------------------------------------------------
/extra/logo/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/extra/logo/logo.png
--------------------------------------------------------------------------------
/extra/logo/logo.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/extra/logo/logo.xcf
--------------------------------------------------------------------------------
/extra/logo/logo2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/extra/logo/logo2.png
--------------------------------------------------------------------------------
/extra/logo/logo2.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/extra/logo/logo2.xcf
--------------------------------------------------------------------------------
/ob-verb.el:
--------------------------------------------------------------------------------
1 | ;;; ob-verb.el --- Babel integration for Verb -*- lexical-binding: t -*-
2 |
3 | ;; Copyright (C) 2023 Federico Tedin
4 |
5 | ;; Author: Federico Tedin
6 | ;; Maintainer: Federico Tedin
7 | ;; Homepage: https://github.com/federicotdn/verb
8 | ;; Keywords: tools
9 | ;; Package-Version: 3.1.0
10 | ;; Package-Requires: ((emacs "26.3"))
11 |
12 | ;; This file is NOT part of GNU Emacs.
13 |
14 | ;; verb is free software; you can redistribute it and/or modify it
15 | ;; under the terms of the GNU General Public License as published by
16 | ;; the Free Software Foundation; either version 3, or (at your option)
17 | ;; any later version.
18 | ;;
19 | ;; verb is distributed in the hope that it will be useful, but WITHOUT
20 | ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 | ;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
22 | ;; License for more details.
23 | ;;
24 | ;; You should have received a copy of the GNU General Public License
25 | ;; along with verb. If not, see http://www.gnu.org/licenses.
26 |
27 | ;;; Commentary:
28 |
29 | ;; This file contains the necessary functions to integrate Verb with
30 | ;; Org mode's Babel.
31 |
32 | ;;; Code:
33 | (require 'verb)
34 |
35 | (defun org-babel-execute:verb (body params)
36 | "Execute an action on the selected Babel source block.
37 | BODY should contain the body of the source block, and PARAMS any
38 | header arguments passed to it. This function is called by
39 | `org-babel-execute-src-block'.
40 |
41 | PARAMS may contain an (:op . OPERATION) element. If it does, use
42 | string OPERATION to decide what to do with the code block. Valid
43 | options are:
44 |
45 | \"send\": Send the HTTP request specified in the source block.
46 | \"send get-headers\": Send the HTTP request specified in the source
47 | block, but only return the response headers.
48 | \"send get-body\": Send the HTTP request specified in the source
49 | block, but only return the response body.
50 | \"export curl\": Export request spec to curl format.
51 | \"export verb\": Export request spec to verb format.
52 |
53 | The default value for OPERATION is \"send\"."
54 | (let* ((processed-params (org-babel-process-params params))
55 | (vars (mapcar #'cdr (seq-filter (lambda (x) (eq (car x) :var))
56 | processed-params)))
57 | (rs (verb--request-spec-from-babel-src-block (point) body vars))
58 | (op (or (cdr (assoc :op processed-params))
59 | "send")))
60 | (pcase op
61 | ((guard (or (string-prefix-p "send " op)
62 | (string= "send" op)))
63 | (ob-verb--send-request rs (nth 1 (split-string op))))
64 | ((guard (string-prefix-p "export " op))
65 | (ob-verb--export-request rs (nth 1 (split-string op))))
66 | (_
67 | (user-error "Invalid value for :op argument: %s" op)))))
68 |
69 | (defun ob-verb-expand-body (body params)
70 | "Expand BODY according to PARAMS, return the expanded body.
71 | This simply exports the block as verb and returns it.
72 |
73 | This function is called by `org-babel-expand-src-block'.
74 |
75 | See `org-babel-execute:verb' for details of PARAMS."
76 | (let* ((processed-params (org-babel-process-params params))
77 | (vars (mapcar #'cdr (seq-filter (lambda (x) (eq (car x) :var))
78 | processed-params)))
79 | (rs (verb--request-spec-from-babel-src-block (point) body vars)))
80 | (ob-verb--export-to-verb rs)))
81 |
82 | ;; Added to ensure linter succeeds.
83 | (define-obsolete-function-alias
84 | 'org-babel-expand-body:verb
85 | 'ob-verb-expand-body
86 | "2024-02-10")
87 |
88 | (defun ob-verb--export-to-verb (rs)
89 | "Export a request spec RS to Verb format.
90 | Like `verb--export-to-verb' but returns string instead of a
91 | buffer."
92 | (save-window-excursion
93 | (with-current-buffer (verb--export-to-verb rs t)
94 | (let ((result (verb--buffer-string-no-properties)))
95 | (kill-buffer)
96 | result))))
97 |
98 | (defun ob-verb--export-request (rs name)
99 | "Export the request specified by the selected Babel source block.
100 | RS should contain the request spec extracted from the source block.
101 | NAME should be the name of a request export function. Return a string
102 | with the contents of the exported request.
103 |
104 | Called when :op `export' is passed to `org-babel-execute:verb'."
105 | (pcase name
106 | ("verb"
107 | (ob-verb--export-to-verb rs))
108 | ("curl"
109 | (verb--export-to-curl rs t t))
110 | ("websocat"
111 | (verb--export-to-websocat rs t t))
112 | (_
113 | (user-error "Invalid export function: %s" name))))
114 |
115 | (defun ob-verb--send-request (rs &optional part)
116 | "Send the request specified by the selected Babel source block.
117 | RS should contain the request spec extracted from the source block.
118 |
119 | PART should describe what part of the response should be returned. If
120 | set to nil, return the whole response, if set to \"get-body\", return
121 | only the response body and if set to \"get-headers\", return only the
122 | response headers. In any case, the value returned will be a string.
123 | Note that the status line (containing HTTP/1.X and the status code) will
124 | only be returned when PART is nil.
125 |
126 | Note that Emacs will be blocked while waiting for a response. The
127 | timeout for this can be configured via the `verb-babel-timeout'
128 | variable.
129 |
130 | Called when :op `send' is passed to `org-babel-execute:verb'. An
131 | optional argument may follow `send'."
132 | (when (and part (not (member part '("get-body" "get-headers"))))
133 | (user-error "Invalid send argument: %s" part))
134 | (let* ((start (time-to-seconds))
135 | (buf (verb--request-spec-send rs nil)))
136 | (while (and (eq (buffer-local-value 'verb-http-response buf) t)
137 | (< (- (time-to-seconds) start) verb-babel-timeout))
138 | (sleep-for 0.1))
139 | (with-current-buffer buf
140 | (if (eq verb-http-response t)
141 | (format "(Request timed out after %.4g seconds)"
142 | (- (time-to-seconds) start))
143 | (pcase part
144 | ('nil (verb-response-to-string verb-http-response buf))
145 | ("get-body" (verb--buffer-string-no-properties))
146 | ("get-headers" (let ((headers (oref verb-http-response headers)))
147 | (with-temp-buffer
148 | (verb--insert-header-contents headers)
149 | (verb--buffer-string-no-properties)))))))))
150 |
151 | ;;;###autoload
152 | (define-derived-mode ob-verb-response-mode special-mode "ob-verb"
153 | "Major mode for displaying HTTP responses with Babel."
154 | (font-lock-add-keywords
155 | nil `(;; HTTP/1.1 200 OK
156 | ("^\\s-*HTTP/1\\.[01]\\s-+[[:digit:]]\\{3\\}.*$"
157 | (0 'verb-http-keyword))
158 | ;; Key: Value
159 | (,verb--http-header-regexp
160 | (1 'verb-header)))))
161 |
162 | (provide 'ob-verb)
163 | ;;; ob-verb.el ends here
164 |
--------------------------------------------------------------------------------
/test/checkdoc-batch.el:
--------------------------------------------------------------------------------
1 | ;; checkdoc-batch.el --- Batch mode for checkdoc -*- lexical-binding: t; -*-
2 |
3 | (defun checkdoc-batch-and-exit ()
4 | ;; Skip in Emacs 26 and older
5 | (when (< 26 emacs-major-version)
6 | (checkdoc-batch-and-exit-1)))
7 |
8 | (defun checkdoc-batch-and-exit-1 ()
9 | "Run checkdoc in batch mode for a set of files.
10 | Exit with 1 if one or more warnings were emitted, otherwise with 0."
11 | (unless noninteractive
12 | (error "`checkdoc-batch-and-exit' is to be used only with -batch"))
13 | (let ((status 0)
14 | path)
15 | (while command-line-args-left
16 | (setq path (car command-line-args-left))
17 | (with-current-buffer (find-file-noselect path)
18 | (checkdoc-current-buffer t))
19 | (with-current-buffer "*Style Warnings*"
20 | (goto-char (point-min))
21 | (while (not (eobp))
22 | (let* ((rule "[ \t\n\r\f]+")
23 | (line (string-trim (buffer-substring-no-properties
24 | (line-beginning-position)
25 | (line-end-position))
26 | rule rule)))
27 | (when (and (not (string= line ""))
28 | (not (string-prefix-p "*" line)))
29 | (princ (concat line "\n"))
30 | (setq status 1)))
31 | (ignore-errors (next-line))))
32 | (setq command-line-args-left (cdr command-line-args-left)))
33 | (kill-emacs status)))
34 |
--------------------------------------------------------------------------------
/test/data/test.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/test/data/test.bin
--------------------------------------------------------------------------------
/test/data/test.el:
--------------------------------------------------------------------------------
1 | (verb-set-var "foo" "hello")
2 | (verb-set-var "bar" "world")
3 |
--------------------------------------------------------------------------------
/test/data/test.json:
--------------------------------------------------------------------------------
1 | {
2 | "foo": "hello",
3 | "bar": "world-json"
4 | }
5 |
--------------------------------------------------------------------------------
/test/data/test.org:
--------------------------------------------------------------------------------
1 | #+FILETAGS: :verb:
2 |
3 | * Testing Endpoints
4 | # Make some requests against the test server (server.py) The requests
5 | # are executed programatically by loading this file, moving to a
6 | # heading and executing verb-execute-request-on-point. See verb-test.el
7 | # for more details (`server-test' macro).
8 |
9 | template http://localhost:8000
10 |
11 | ** org-hyperlink
12 | get [[http://localhost:8000/basic][some hyperlink description]]
13 |
14 | ** basic
15 | get /basic
16 |
17 | ** basic-json
18 | get /basic-json
19 | ** keywords-json
20 | get /keywords-json
21 | ** stored
22 | :properties:
23 | :Verb-Store: foobar
24 | :end:
25 | get /basic
26 | ** error-400
27 | get /error-400
28 |
29 | ** error-401
30 | get /error-401
31 |
32 | ** headers
33 | get /headers-test
34 |
35 | ** error-404
36 | get /this-endpoint-doesnt-exist
37 |
38 | ** error-405
39 | put /basic-json
40 |
41 | ** response-latin-1
42 | get /response-latin-1
43 |
44 | ** request-latin-1
45 | post /request-latin-1
46 | Content-Type: text/plain; charset=latin1
47 |
48 | áéíóúñü
49 | ** request-utf-8-default
50 | # No set charset=
51 | post /request-utf-8-default
52 | Content-Type: text/plain
53 |
54 | áéíóúñü
55 | ** request-utf-8-default-2
56 | # No set Content-Type
57 | post /request-utf-8-default-2
58 |
59 | áéíóúñü
60 | ** response-utf-8-default
61 | get /response-utf-8-default
62 |
63 | ** response-big5
64 | get /response-big5
65 |
66 | ** root-with-args
67 | get ?foo=bar
68 |
69 | ** redirect-302
70 | get /redirect-302
71 |
72 | ** redirect-302-max-redirections-0
73 | :properties:
74 | :Verb-Max-Redirections: 0
75 | :end:
76 | get /redirect-302
77 |
78 | ** redirect-301
79 | get /redirect-301
80 |
81 | ** redirect-308
82 | post /redirect-308
83 |
84 | ** no-user-agent
85 | get /no-user-agent
86 |
87 | ** content-length-1
88 | post /content-length
89 |
90 | hello
91 | ** content-length-2
92 | post /content-length
93 |
94 | áéíóú
95 | test
96 | ** zero-bytes-json
97 | get /zero-bytes-json
98 | ** sorted-headers
99 | post /sorted-headers
100 |
101 | foobar
102 | *** accept-sorted-headers
103 | template
104 | accept: hello-world
105 | ACCEPT: hello-world2
106 | *** repeated-sorted-headers
107 | template
108 | MIME-Version: foobar
109 | ** image
110 | get /image.png
111 | ** upload-image
112 | post /body-md5
113 | Content-Type: image/png
114 |
115 | {{(verb-read-file "test.png" 'binary)}}
116 | ** upload-binary
117 | post /body-md5
118 |
119 | {{(verb-read-file "test.bin" 'binary)}}
120 | ** not-compressed
121 | get /not-compressed
122 | ** set-cookies
123 | get /set-cookies?foo=bar&abc=123
124 | ** get-cookies
125 | get /get-cookies
126 | ** delete-cookies
127 | get /delete-cookies?foo=t&abc=t
128 | ** get-with-body
129 | get /basic
130 | Content-Type: text/plain
131 |
132 | Foobar
133 | ** repeated-args
134 | get /echo-args?a=1&a=2&a=3&b=42
135 | ** utf-8-request-with-accept
136 | post /echo
137 | Accept: application/json
138 | Content-Type: application/json; charset=utf-8
139 |
140 | 語
141 | ** form-urlencoded
142 | post /form-urlencoded
143 | Content-Type: application/x-www-form-urlencoded
144 |
145 | hello=world&foo=%7B%22test%22%3A123%7D
146 | ** form-urlencoded-with-helper
147 | post /form-urlencoded
148 | Content-Type: application/x-www-form-urlencoded
149 |
150 | {{(verb-util-form-url-encode '(("hello" . "world") ("foo" . "{\"test\":123}")))}}
151 | ** multipart
152 | :properties:
153 | :Verb-Map-Request: verb-body-lf-to-crlf
154 | :end:
155 | post /multipart
156 | Content-Type: multipart/form-data; boundary={{(verb-boundary)}}
157 |
158 | {{(verb-part "foo1")}}
159 | Content-Type: text/plain
160 |
161 | bar1
162 | {{(verb-part "foo2")}}
163 | Content-Type: application/xml
164 |
165 | bar2
166 | {{(verb-part)}}
167 | ** prelude-elisp
168 | :properties:
169 | :Verb-Prelude: test.el
170 | :end:
171 | get /echo-args?{{(verb-var foo)}}={{(verb-var bar)}}
172 | ** prelude-elisp-inline
173 | :properties:
174 | :Verb-Prelude+: (setq prelude-inline-1 "abc")
175 | :Verb-Prelude+: (setq prelude-inline-2 "321")
176 | :end:
177 | get /echo-args?{{prelude-inline-1}}={{prelude-inline-2}}
178 | ** prelude-json
179 | :properties:
180 | :Verb-Prelude: test.json
181 | :end:
182 | get /echo-args?{{(verb-var foo)}}={{(verb-var bar)}}
183 | ** prelude-json-inline
184 | :properties:
185 | :Verb-Prelude+: {
186 | :Verb-Prelude+: "json-inline-var": "jsoninline"
187 | :Verb-Prelude+: }
188 | :end:
189 | get /echo-args?value={{(verb-var json-inline-var)}}
190 | ** map-response
191 | :properties:
192 | :Verb-Map-Response: (lambda (r) (oset r body "xyz") (setq some-global-var-mp 101010) r)
193 | :end:
194 | get /basic-json
195 | ** map-response-upcase
196 | :properties:
197 | :Verb-Map-Response: map-response-upcase-fn
198 | :end:
199 | get /basic
200 | ** map-response-error
201 | :properties:
202 | :Verb-Map-Response: (lambda (r) 1)
203 | :end:
204 | get /basic-json
205 | * connection-fail-port
206 | # (Do not add request specs under this heading!)
207 | # Valid host but invalid port
208 | get http://localhost:1234/test
209 | * connection-fail-host
210 | # (Do not add request specs under this heading!)
211 | # Invalid host
212 | get http://foobarfoobarfoobarfoobarabcdefg/test
213 |
--------------------------------------------------------------------------------
/test/data/test.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/federicotdn/verb/cc1d05d8890a98f576632632f38da2875c5f8a84/test/data/test.png
--------------------------------------------------------------------------------
/test/data/test.txt:
--------------------------------------------------------------------------------
1 | Example text!
2 |
--------------------------------------------------------------------------------
/test/init-check.el:
--------------------------------------------------------------------------------
1 | ;; init-check.el --- Init for Verb linting/checks -*- lexical-binding: t; -*-
2 |
3 | (require 'package)
4 |
5 | (push '("melpa" . "https://melpa.org/packages/") package-archives)
6 | (package-initialize)
7 | (unless package-archive-contents
8 | (package-refresh-contents))
9 |
10 | ;; Update this if CI breaks for older Emacs versions
11 | (when (= emacs-major-version 26)
12 | (setq package-check-signature nil))
13 |
14 | (dolist (pkg '(cl-lib let-alist compat package-lint xr relint))
15 | (unless (package-installed-p pkg)
16 | (package-install pkg)))
17 |
--------------------------------------------------------------------------------
/test/init.el:
--------------------------------------------------------------------------------
1 | ;; init.el --- Manual testing setup for Verb -*- lexical-binding: t; -*-
2 |
3 | ;; Build Verb autoloads and load them
4 | (require 'package)
5 | (package-generate-autoloads "verb" ".")
6 | (load "verb-autoloads.el")
7 |
8 | ;; Set up misc. Emacs config
9 | (add-to-list 'default-frame-alist '(fullscreen . maximized))
10 | (set-face-attribute 'default nil :height (string-to-number (getenv "FONT_SIZE")))
11 | (setq initial-scratch-message nil)
12 | (load-theme 'wombat)
13 | (setq url-debug t)
14 | (toggle-debug-on-error)
15 |
16 | ;; Set up Org and Babel
17 | (org-babel-do-load-languages
18 | 'org-babel-load-languages
19 | '((verb . t)))
20 | (setq org-confirm-babel-evaluate nil)
21 |
22 | ;; Set up Verb
23 | (setq verb-auto-kill-response-buffers 3)
24 |
25 | ;; Keybindings
26 | (with-eval-after-load 'org (define-key org-mode-map (kbd "C-c C-r") verb-command-map))
27 | (global-set-key (kbd "M-l") 'switch-to-buffer)
28 | (global-set-key (kbd "M-o") 'other-window)
29 |
30 | ;; Create a useful initial window/buffer setup
31 | (with-current-buffer (get-buffer "*scratch*")
32 | (org-mode)
33 | (verb-mode)
34 | (insert "* Test :verb:")
35 | (newline)
36 | (insert "get http://localhost:8000/endpoints"))
37 | (let ((inhibit-message t))
38 | (dired "examples"))
39 | (delete-other-windows)
40 |
--------------------------------------------------------------------------------
/test/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "crypto/md5"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "os"
9 | "slices"
10 | "sort"
11 | "strconv"
12 | "strings"
13 | )
14 |
15 | func basicHandler(w http.ResponseWriter, r *http.Request) {
16 | fmt.Fprintf(w, "Hello, World!")
17 | }
18 |
19 | func headersTestHandler(w http.ResponseWriter, r *http.Request) {
20 | w.Header().Set("x-test-1", "foo")
21 | w.Header().Set("OTHER-TEST", "bar")
22 | fmt.Fprintf(w, "HeadersTest")
23 | }
24 |
25 | func basicJSONHandler(w http.ResponseWriter, r *http.Request) {
26 | w.Header()["Date"] = nil
27 | w.Header().Set("Content-Type", "application/json")
28 | fmt.Fprintf(w, `{"hello": "world", "foo": true}`)
29 | }
30 |
31 | func keywordsJSONHandler(w http.ResponseWriter, r *http.Request) {
32 | w.Header().Set("Content-Type", "application/json")
33 | fmt.Fprintf(w, `{"t": true}`)
34 | }
35 |
36 | func error400Handler(w http.ResponseWriter, r *http.Request) {
37 | w.WriteHeader(http.StatusBadRequest)
38 | }
39 |
40 | func error401Handler(w http.ResponseWriter, r *http.Request) {
41 | http.Error(w, "", http.StatusUnauthorized)
42 | }
43 |
44 | func responseLatin1Handler(w http.ResponseWriter, r *http.Request) {
45 | w.Header().Set("Content-Type", "text/plain; charset=latin1")
46 | // "ñáéíóúß" encoded in latin-1:
47 | w.Write([]byte("\xf1\xe1\xe9\xed\xf3\xfa\xdf"))
48 | }
49 |
50 | func requestLatin1Handler(w http.ResponseWriter, r *http.Request) {
51 | if r.Header.Get("Content-Type") != "text/plain; charset=latin1" {
52 | http.Error(w, "FAIL", http.StatusBadRequest)
53 | return
54 | }
55 | body, err := io.ReadAll(r.Body)
56 | if err != nil {
57 | panic(err)
58 | }
59 |
60 | // "áéíóúñü" encoded in latin-1:
61 | if string(body) != "\xe1\xe9\xed\xf3\xfa\xf1\xfc" {
62 | http.Error(w, "FAIL", http.StatusBadRequest)
63 | return
64 | }
65 | fmt.Fprintf(w, "OK")
66 | }
67 |
68 | func requestUTF8DefaultHandler(w http.ResponseWriter, r *http.Request) {
69 | if r.Header.Get("Content-Type") != "text/plain" {
70 | http.Error(w, "FAIL", http.StatusBadRequest)
71 | return
72 | }
73 | body, err := io.ReadAll(r.Body)
74 | if err != nil {
75 | panic(err)
76 | }
77 |
78 | if string(body) != "áéíóúñü" {
79 | http.Error(w, "FAIL", http.StatusBadRequest)
80 | return
81 | }
82 | fmt.Fprintf(w, "OK")
83 | }
84 |
85 | func requestUTF8Default2Handler(w http.ResponseWriter, r *http.Request) {
86 | body, err := io.ReadAll(r.Body)
87 | if err != nil {
88 | panic(err)
89 | }
90 |
91 | if string(body) != "áéíóúñü" {
92 | http.Error(w, "FAIL", http.StatusBadRequest)
93 | return
94 | }
95 | fmt.Fprintf(w, "OK")
96 | }
97 |
98 | func responseUTF8DefaultHandler(w http.ResponseWriter, r *http.Request) {
99 | w.Header().Set("Content-Type", "text/plain")
100 | w.Write([]byte("ñáéíóúß")) // Go source code is UTF-8 encoded
101 | }
102 |
103 | func responseBig5Handler(w http.ResponseWriter, r *http.Request) {
104 | w.Header().Set("Content-Type", "text/plain; charset=big5")
105 | resp := "\xb1`\xa5\xce\xa6r" // "常用字" encoded in Big5
106 | w.Write([]byte(resp))
107 | }
108 |
109 | func rootHandler(w http.ResponseWriter, r *http.Request) {
110 | if r.URL.Path != "/" {
111 | http.NotFound(w, r)
112 | return
113 | }
114 | if r.URL.Query().Get("foo") == "bar" {
115 | fmt.Fprintf(w, "OK")
116 | return
117 | }
118 | fmt.Fprintf(w, "FAIL")
119 | }
120 |
121 | func redirect301Handler(w http.ResponseWriter, r *http.Request) {
122 | http.Redirect(w, r, "/basic", http.StatusMovedPermanently)
123 | }
124 |
125 | func redirect302Handler(w http.ResponseWriter, r *http.Request) {
126 | w.Header()["Content-Type"] = nil
127 | http.Redirect(w, r, "/basic", http.StatusFound)
128 | }
129 |
130 | func redirect308Handler(w http.ResponseWriter, r *http.Request) {
131 | http.Redirect(w, r, "/redirect-308-2", http.StatusPermanentRedirect)
132 | }
133 |
134 | func redirect3082Handler(w http.ResponseWriter, r *http.Request) {
135 | fmt.Fprintf(w, "Redirect successful")
136 | }
137 |
138 | func noUserAgentHandler(w http.ResponseWriter, r *http.Request) {
139 | if r.UserAgent() != "" {
140 | http.Error(w, "FAIL", http.StatusBadRequest)
141 | return
142 | }
143 | fmt.Fprintf(w, "OK")
144 | }
145 |
146 | func contentLengthHandler(w http.ResponseWriter, r *http.Request) {
147 | if r.Header.Get("Content-Length") == "" {
148 | http.Error(w, "FAIL", http.StatusBadRequest)
149 | return
150 | }
151 | body, err := io.ReadAll(r.Body)
152 | if err != nil {
153 | panic(err)
154 | }
155 |
156 | if len(body) != int(r.ContentLength) {
157 | http.Error(w, "FAIL", http.StatusBadRequest)
158 | return
159 | }
160 | fmt.Fprintf(w, "OK")
161 | }
162 |
163 | func bodyMD5Handler(w http.ResponseWriter, r *http.Request) {
164 | body, err := io.ReadAll(r.Body)
165 | if err != nil {
166 | panic(err)
167 | }
168 |
169 | md5Hash := fmt.Sprintf("%x", md5.Sum(body))
170 | fmt.Fprintf(w, "%v", md5Hash)
171 | }
172 |
173 | func echoHandler(w http.ResponseWriter, r *http.Request) {
174 | io.Copy(w, r.Body)
175 | }
176 |
177 | func echoArgsHandler(w http.ResponseWriter, r *http.Request) {
178 | values := []string{}
179 | for key, val := range r.URL.Query() {
180 | for _, v := range val {
181 | values = append(values, fmt.Sprintf("%s=%s", key, v))
182 | }
183 | }
184 | sort.Strings(values)
185 | fmt.Fprintf(w, "%v", strings.Join(values, "\n"))
186 | }
187 |
188 | func zeroBytesJSONHandler(w http.ResponseWriter, r *http.Request) {
189 | w.Header().Set("Content-Type", "application/json")
190 | fmt.Fprintf(w, "")
191 | }
192 |
193 | func sortedHeadersHandler(w http.ResponseWriter, r *http.Request) {
194 | if r.URL.Query().Get("dropcookies") != "" {
195 | r.Header.Del("Cookie")
196 | }
197 |
198 | headers := []string{}
199 | for k, v := range r.Header {
200 | headers = append(headers, fmt.Sprintf("%s: %s", strings.ToLower(k), v[0]))
201 | }
202 | headers = append(headers, fmt.Sprintf("host: %s", r.Host))
203 | if r.UserAgent() != "" {
204 | headers = append(headers, fmt.Sprintf("user-agent: %s", r.UserAgent()))
205 | }
206 |
207 | sort.Strings(headers)
208 | fmt.Fprintf(w, "%v", strings.Join(headers, "\n"))
209 | }
210 |
211 | func notCompressedHandler(w http.ResponseWriter, r *http.Request) {
212 | w.Header().Set("Content-Encoding", "gzip")
213 | fmt.Fprintf(w, "hello, world!")
214 | }
215 |
216 | func setCookiesHandler(w http.ResponseWriter, r *http.Request) {
217 | err := r.ParseForm()
218 | if err != nil {
219 | panic(err)
220 | }
221 |
222 | for key, val := range r.Form {
223 | cookie := http.Cookie{Name: key, Value: val[0], Path: "/"}
224 | http.SetCookie(w, &cookie)
225 | }
226 | fmt.Fprintf(w, "OK")
227 | }
228 |
229 | func getCookiesHandler(w http.ResponseWriter, r *http.Request) {
230 | cookies := r.Cookies()
231 | slices.SortFunc(cookies, func(a, b *http.Cookie) int {
232 | if a.Name < b.Name {
233 | return -1
234 | }
235 | return 1
236 | })
237 | for _, cookie := range cookies {
238 | fmt.Fprintf(w, "%s=%s\n", cookie.Name, cookie.Value)
239 | }
240 | }
241 |
242 | func deleteCookiesHandler(w http.ResponseWriter, r *http.Request) {
243 | err := r.ParseForm()
244 | if err != nil {
245 | panic(err)
246 | }
247 |
248 | for key := range r.Form {
249 | cookie := http.Cookie{Name: key, Value: "", Path: "/", MaxAge: -1}
250 | http.SetCookie(w, &cookie)
251 | }
252 | fmt.Fprintf(w, "OK")
253 | }
254 |
255 | func formUrlencodedHandler(w http.ResponseWriter, r *http.Request) {
256 | err := r.ParseForm()
257 | if err != nil {
258 | panic(err)
259 | }
260 |
261 | if r.Form.Get("hello") != "world" || r.Form.Get("foo") != `{"test":123}` {
262 | http.Error(w, "FAIL", http.StatusBadRequest)
263 | return
264 | }
265 | fmt.Fprintf(w, "OK")
266 | }
267 |
268 | func multipartHandler(w http.ResponseWriter, r *http.Request) {
269 | err := r.ParseMultipartForm(10 << 20) // 10 MB limit
270 | if err != nil {
271 | panic(err)
272 | }
273 |
274 | if r.FormValue("foo1") != "bar1" || r.FormValue("foo2") != "bar2" {
275 | http.Error(w, "FAIL", http.StatusBadRequest)
276 | return
277 | }
278 | fmt.Fprintf(w, "OK")
279 | }
280 |
281 | func imageHandler(w http.ResponseWriter, r *http.Request) {
282 | http.ServeFile(w, r, "test/data/test.png")
283 | }
284 |
285 | func main() {
286 | http.HandleFunc("GET /basic", basicHandler)
287 | http.HandleFunc("GET /headers-test", headersTestHandler)
288 | http.HandleFunc("GET /basic-json", basicJSONHandler)
289 | http.HandleFunc("GET /keywords-json", keywordsJSONHandler)
290 | http.HandleFunc("GET /error-400", error400Handler)
291 | http.HandleFunc("GET /error-401", error401Handler)
292 | http.HandleFunc("GET /response-latin-1", responseLatin1Handler)
293 | http.HandleFunc("POST /request-latin-1", requestLatin1Handler)
294 | http.HandleFunc("POST /request-utf-8-default", requestUTF8DefaultHandler)
295 | http.HandleFunc("POST /request-utf-8-default-2", requestUTF8Default2Handler)
296 | http.HandleFunc("GET /response-utf-8-default", responseUTF8DefaultHandler)
297 | http.HandleFunc("GET /response-big5", responseBig5Handler)
298 | http.HandleFunc("GET /", rootHandler)
299 | http.HandleFunc("GET /redirect-301", redirect301Handler)
300 | http.HandleFunc("GET /redirect-302", redirect302Handler)
301 | http.HandleFunc("POST /redirect-308", redirect308Handler)
302 | http.HandleFunc("POST /redirect-308-2", redirect3082Handler)
303 | http.HandleFunc("GET /no-user-agent", noUserAgentHandler)
304 | http.HandleFunc("POST /content-length", contentLengthHandler)
305 | http.HandleFunc("POST /body-md5", bodyMD5Handler)
306 | http.HandleFunc("POST /echo", echoHandler)
307 | http.HandleFunc("GET /echo-args", echoArgsHandler)
308 | http.HandleFunc("GET /zero-bytes-json", zeroBytesJSONHandler)
309 | http.HandleFunc("POST /sorted-headers", sortedHeadersHandler)
310 | http.HandleFunc("GET /sorted-headers", sortedHeadersHandler)
311 | http.HandleFunc("GET /not-compressed", notCompressedHandler)
312 | http.HandleFunc("GET /set-cookies", setCookiesHandler)
313 | http.HandleFunc("GET /get-cookies", getCookiesHandler)
314 | http.HandleFunc("GET /delete-cookies", deleteCookiesHandler)
315 | http.HandleFunc("POST /form-urlencoded", formUrlencodedHandler)
316 | http.HandleFunc("POST /multipart", multipartHandler)
317 | http.HandleFunc("GET /image.png", imageHandler)
318 |
319 | port, err := strconv.Atoi(os.Getenv("PORT"))
320 | if err != nil {
321 | port = 8000
322 | }
323 |
324 | if _, found := os.LookupEnv("SKIP_PIDFILE"); !found {
325 | pidfile := "test/server.pid"
326 | pid := os.Getpid()
327 | os.WriteFile(pidfile, []byte(strconv.Itoa(pid)), 0644)
328 | fmt.Printf("server pid: %v\n", pid)
329 | }
330 | addr := fmt.Sprintf("localhost:%v", port)
331 | fmt.Printf("running server at: %v\n", addr)
332 | http.ListenAndServe(addr, nil)
333 | }
334 |
--------------------------------------------------------------------------------
/verb-util.el:
--------------------------------------------------------------------------------
1 | ;;; verb-util.el --- Utilities for Verb -*- lexical-binding: t -*-
2 |
3 | ;; Copyright (C) 2024 Federico Tedin
4 |
5 | ;; Author: Federico Tedin
6 | ;; Maintainer: Federico Tedin
7 | ;; Homepage: https://github.com/federicotdn/verb
8 | ;; Keywords: tools
9 | ;; Package-Version: 3.1.0
10 | ;; Package-Requires: ((emacs "26.3"))
11 |
12 | ;; This file is NOT part of GNU Emacs.
13 |
14 | ;; verb is free software; you can redistribute it and/or modify it
15 | ;; under the terms of the GNU General Public License as published by
16 | ;; the Free Software Foundation; either version 3, or (at your option)
17 | ;; any later version.
18 | ;;
19 | ;; verb is distributed in the hope that it will be useful, but WITHOUT
20 | ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 | ;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
22 | ;; License for more details.
23 | ;;
24 | ;; You should have received a copy of the GNU General Public License
25 | ;; along with verb. If not, see http://www.gnu.org/licenses.
26 |
27 | ;;; Commentary:
28 |
29 | ;; General utility variables and functions for Verb.
30 |
31 | ;;; Code:
32 |
33 | (defconst verb-util--log-buffer-name "*Verb Log*"
34 | "Default name for log buffer.")
35 |
36 | (defconst verb-util--log-levels '(D I W E)
37 | "Log levels for the log buffer.
38 | D = Debug.
39 | I = Information.
40 | W = Warning.
41 | E = Error.")
42 |
43 | (defface verb-util--log-debug '((t :inherit font-lock-constant-face))
44 | "Face for highlighting D entries in the log buffer."
45 | :group 'verb)
46 |
47 | (defface verb-util--log-info '((t :inherit homoglyph))
48 | "Face for highlighting I entries in the log buffer."
49 | :group 'verb)
50 |
51 | (defface verb-util--log-warning '((t :inherit warning))
52 | "Face for highlighting W entries in the log buffer."
53 | :group 'verb)
54 |
55 | (defface verb-util--log-error '((t :inherit error))
56 | "Face for highlighting E entries in the log buffer."
57 | :group 'verb)
58 |
59 | (defconst verb-util--http-header-parse-regexp
60 | "^\\s-*\\([[:alnum:]_-]+\\)\\s-*:\\(.*\\)$"
61 | "Regexp for parsing HTTP headers.")
62 |
63 | (defconst verb-util--org-hyperlink-regexp
64 | "\\[\\[\\(.+?\\)\\]\\(\\[.*?\\]\\)?\\]"
65 | "Regexp for parsing Org mode hyperlinks.")
66 |
67 | (define-derived-mode verb-util-log-mode special-mode "Verb[Log]"
68 | "Major mode for displaying Verb logs.
69 |
70 | Each line contains a short message representing an event that has been
71 | logged:
72 |
73 | The first part of each line is a number that represents what
74 | request has generated this event (the number identifies the request).
75 | If an event does not correspond to any request, \"-\" is used instead.
76 | If the first part of the line is empty, then the event corresponds to
77 | the same request from the previous line.
78 |
79 | The second part of each line represents the level at which this event
80 | has been logged, I for information, W for warnings and E for errors.
81 |
82 | The third part of each line is the message itself.
83 |
84 | If this buffer is killed, it will be created again when the next
85 | message is logged. To turn off logging, set `verb-enable-log' to nil."
86 | (font-lock-add-keywords
87 | nil '(;; Request number, e.g. 10.
88 | ("^[[:digit:]-]+\\s-"
89 | (0 'bold))
90 | ;; Log level D after request number.
91 | ("^[[:digit:]-]*\\s-+\\(D\\)"
92 | (1 'verb-util--log-debug))
93 | ;; Log level I after request number.
94 | ("^[[:digit:]-]*\\s-+\\(I\\)"
95 | (1 'verb-util--log-info))
96 | ;; Log level W after request number.
97 | ("^[[:digit:]-]*\\s-+\\(W\\)"
98 | (1 'verb-util--log-warning))
99 | ;; Log level E after request number.
100 | ("^[[:digit:]-]*\\s-+\\(E\\)"
101 | (1 'verb-util--log-error)))))
102 |
103 | (defun verb-util--log (request level &rest args)
104 | "Log a message in the *Verb Log* buffer.
105 | REQUEST must be a number corresponding to an HTTP request made. LEVEL
106 | must be a value in `verb-util--log-levels'. Use the remaining ARGS to call
107 | `format', and then log the result in the log buffer.
108 |
109 | If `verb-enable-log' is nil, do not log anything."
110 | (setq request (if request (number-to-string request) "-"))
111 | (unless (member level verb-util--log-levels)
112 | (user-error "Invalid log level: \"%s\"" level))
113 | (when (bound-and-true-p verb-enable-log) ; Var is defined in verb.el.
114 | (with-current-buffer (get-buffer-create verb-util--log-buffer-name)
115 | (unless (derived-mode-p 'verb-util-log-mode)
116 | (verb-util-log-mode))
117 | (let ((inhibit-read-only t)
118 | (last "")
119 | (msg (apply #'format args)))
120 | (unless (= (buffer-size) 0)
121 | (insert "\n"))
122 | ;; Get last logged request number.
123 | (when (re-search-backward "^\\(-\\|[[:digit:]]+\\)\\s-"
124 | nil t)
125 | (setq last (match-string 1)))
126 | (goto-char (point-max))
127 | ;; Log new message.
128 | (insert (format "%-5s %s "
129 | (if (string= last request)
130 | (make-string (length request) ? )
131 | request)
132 | level)
133 | msg)
134 | ;; If logged messaged contained newlines, add a blank line
135 | ;; to make things more readable.
136 | (when (string-match-p "\n" msg)
137 | (newline)))
138 | (dolist (w (get-buffer-window-list (current-buffer) nil t))
139 | (set-window-point w (point-max))))))
140 |
141 | (defun verb-util-show-log ()
142 | "Switch to the *Verb Log* buffer."
143 | (interactive)
144 | (switch-to-buffer (get-buffer-create verb-util--log-buffer-name)))
145 |
146 | (defun verb-util--nonempty-string (s)
147 | "Return S. If S is the empty string, return nil."
148 | (if (string= s "")
149 | nil
150 | s))
151 |
152 | (defun verb-util--string= (s1 s2)
153 | "Return non-nil if strings S1 and S2 are equal, ignoring case."
154 | (string= (downcase s1) (downcase s2)))
155 |
156 | (defun verb-util--object-intervals (object)
157 | "Call function `object-intervals' on OBJECT if possible.
158 | Otherwise, or if calling the function returns nil, return a single
159 | interval covering the whole object, with no properties."
160 | ;; TODO: Update once Verb depends on Emacs 28.1+.
161 | (let ((default (list (list 0 (length object) nil))))
162 | (if (fboundp 'object-intervals)
163 | (or (funcall #'object-intervals object)
164 | default)
165 | default)))
166 |
167 | (defun verb-util--remove-org-hyperlinks (s)
168 | "Remove Org hyperlinks from string S and return the result.
169 | All hyperlinks are replaced with the link they contain."
170 | (replace-regexp-in-string verb-util--org-hyperlink-regexp
171 | "\\1" s t))
172 |
173 |
174 | (defun verb-util-form-url-encode (values)
175 | "URL-encode VALUES for a form submission (x-www-form-urlencoded).
176 | VALUES must be an alist of (KEY . VALUE) elements, with KEY and VALUE
177 | being strings."
178 | (mapconcat (lambda (elem)
179 | (concat (url-hexify-string (car elem))
180 | "="
181 | (url-hexify-string (cdr elem))))
182 | values "&"))
183 |
184 | (provide 'verb-util)
185 | ;;; verb-util.el ends here
186 |
--------------------------------------------------------------------------------