pdf-info.el (63905B)
1 ;;; pdf-info.el --- Extract info from pdf-files via a helper process. -*- lexical-binding: t -*- 2 3 ;; Copyright (C) 2013, 2014 Andreas Politz 4 5 ;; Author: Andreas Politz <politza@fh-trier.de> 6 ;; Keywords: files, multimedia 7 8 ;; This program is free software; you can redistribute it and/or modify 9 ;; it under the terms of the GNU General Public License as published by 10 ;; the Free Software Foundation, either version 3 of the License, or 11 ;; (at your option) any later version. 12 13 ;; This program is distributed in the hope that it will be useful, 14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 ;; GNU General Public License for more details. 17 18 ;; You should have received a copy of the GNU General Public License 19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>. 20 21 ;;; Commentary: 22 ;; 23 ;; This library represents the Lisp side of the epdfinfo server. This 24 ;; program works on a command/response basis, but there should be no 25 ;; need to understand the protocol, since every command has a 26 ;; corresponding Lisp-function (see below under `High level 27 ;; interface'). 28 ;; 29 ;; Most of these functions receive a file-or-buffer argument, which 30 ;; may be what it says and defaults to the current buffer. Also, most 31 ;; functions return some sort of alist, with, in most cases, 32 ;; straight-forward key-value-pairs. Though some may be only 33 ;; understandable in the context of Adobe's PDF spec \(Adobe 34 ;; PDF32000\) or the poppler documentation (e.g. annotation flags). 35 ;; 36 ;; If the poppler library is fairly recent (>= 0.19.4, older versions 37 ;; have a bug, which may corrupt the document), annotations maybe 38 ;; modified to a certain degree, deleted and text-annotations created. 39 ;; The state of these modifications is held in the server. In order 40 ;; to realize, annotations retrieved or created are referenced by a 41 ;; unique symbol. Saving these changes creates a new file, the 42 ;; original document is never touched. 43 44 ;;; Todo: 45 ;; 46 ;; + Close documents at some time (e.g. when the buffer is killed) 47 ;; 48 49 ;;; Code: 50 51 (require 'tq) 52 (require 'cl-lib) 53 54 55 56 ;; * ================================================================== * 57 ;; * Customizations 58 ;; * ================================================================== * 59 60 (defgroup pdf-info nil 61 "Extract infos from pdf-files via a helper process." 62 :group 'pdf-tools) 63 64 (defcustom pdf-info-epdfinfo-program 65 (let ((executable (if (eq system-type 'windows-nt) 66 "epdfinfo.exe" "epdfinfo")) 67 (default-directory 68 (or (and load-file-name 69 (file-name-directory load-file-name)) 70 default-directory))) 71 (cl-labels ((try-directory (directory) 72 (and (file-directory-p directory) 73 (file-executable-p (expand-file-name executable directory)) 74 (expand-file-name executable directory)))) 75 (or (executable-find executable) 76 ;; This works if epdfinfo is in the same place as emacs and 77 ;; the editor was started with an absolute path, i.e. it is 78 ;; meant for Windows/Msys2. 79 (and (stringp (car-safe command-line-args)) 80 (file-name-directory (car command-line-args)) 81 (try-directory 82 (file-name-directory (car command-line-args)))) 83 ;; If we are running directly from the git repo. 84 (try-directory (expand-file-name "../server")) 85 ;; Fall back to epdfinfo in the directory of this file. 86 (expand-file-name executable)))) 87 "Filename of the epdfinfo executable." 88 :type 'file) 89 90 (defcustom pdf-info-epdfinfo-error-filename nil 91 "Filename for error output of the epdfinfo executable. 92 93 If nil, discard any error messages. Useful for debugging." 94 :type `(choice (const :tag "None" nil) 95 ,@(when (file-directory-p "/tmp/") 96 '((const "/tmp/epdfinfo.log"))) 97 (file))) 98 99 (defcustom pdf-info-log nil 100 "Whether to log the communication with the server. 101 102 If this is non-nil, all communication with the epdfinfo program 103 will be logged to the buffer \"*pdf-info-log*\"." 104 :type 'boolean) 105 106 (defcustom pdf-info-log-entry-max 512 107 "Maximum number of characters in a single log entry. 108 109 This variable has no effect if `pdf-info-log' is nil." 110 :type 'integer) 111 112 (defcustom pdf-info-restart-process-p 'ask 113 "What to do when the epdfinfo server died. 114 115 This should be one of 116 nil -- do nothing, 117 t -- automatically restart it or 118 ask -- ask whether to restart or not. 119 120 If it is `ask', the server quits and you answer no, this variable 121 is set to nil." 122 :type '(choice (const :tag "Do nothing" nil) 123 (const :tag "Restart silently" t) 124 (const :tag "Always ask" ask))) 125 126 (defcustom pdf-info-close-document-hook nil 127 "A hook ran after a document was closed in the server. 128 129 The hook is run in the documents buffer, if it exists. Otherwise 130 in a `with-temp-buffer' form." 131 :type 'hook) 132 133 134 135 ;; * ================================================================== * 136 ;; * Variables 137 ;; * ================================================================== * 138 139 (defvar pdf-info-asynchronous nil 140 "If non-nil process queries asynchronously. 141 142 More specifically the value should be a function of at 2 143 arguments \(fn STATUS RESPONSE\), where STATUS is either nil, for 144 a successful query, or the symbol error. RESPONSE is either the 145 command's response or the error message. This does not work 146 recursive, i.e. if function wants to make another asynchronous 147 query it has to rebind this variable. 148 149 Alternatively it may be a list \(FN . ARGS\), in which case FN 150 will be invoked like \(apply FN STATUS RESPONSE ARGS\). 151 152 Also, all pdf-info functions normally returning a response return 153 nil. 154 155 This variable should only be let-bound.") 156 157 (defconst pdf-info-pdf-date-regexp 158 ;; Adobe PDF32000.book, 7.9.4 Dates 159 (eval-when-compile 160 (concat 161 ;; allow for preceding garbage 162 ;;"\\`" 163 "[dD]:" 164 "\\([0-9]\\{4\\}\\)" ;year 165 "\\(?:" 166 "\\([0-9]\\{2\\}\\)" ;month 167 "\\(?:" 168 "\\([0-9]\\{2\\}\\)" ;day 169 "\\(?:" 170 "\\([0-9]\\{2\\}\\)" ;hour 171 "\\(?:" 172 "\\([0-9]\\{2\\}\\)" ;minutes 173 "\\(?:" 174 "\\([0-9]\\{2\\}\\)" ;seconds 175 "\\)?\\)?\\)?\\)?\\)?" 176 "\\(?:" 177 "\\([+-Zz]\\)" ;UT delta char 178 "\\(?:" 179 "\\([0-9]\\{2\\}\\)" ;UT delta hours 180 "\\(?:" 181 "'" 182 "\\([0-9]\\{2\\}\\)" ;UT delta minutes 183 "\\)?\\)?\\)?" 184 ;; "\\'" 185 ;; allow for trailing garbage 186 ))) 187 188 (defvar pdf-info--queue t 189 "Internally used transmission-queue for the server. 190 191 This variable is initially t, telling the code starting the 192 server, that it never ran.") 193 194 195 ;; * ================================================================== * 196 ;; * Process handling 197 ;; * ================================================================== * 198 199 (defconst pdf-info-empty-page-data 200 (eval-when-compile 201 (concat 202 "%PDF-1.0\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0" 203 " obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</" 204 "Type/Page/MediaBox[0 0 3 3]>>endobj\nxref\n0 4\n00000000" 205 "0065535 f\n0000000010 00000 n\n0000000053 00000 n\n00000" 206 "00102 00000 n\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n149\n%EOF")) 207 "PDF data of an empty page.") 208 209 (defun pdf-info-process () 210 "Return the process object or nil." 211 (and pdf-info--queue 212 (not (eq t pdf-info--queue)) 213 (tq-process pdf-info--queue))) 214 215 (defun pdf-info-check-epdfinfo (&optional interactive-p) 216 "Check if the server should be working properly. 217 218 Signal an error if some problem was found. Message a 219 confirmation, if INTERACTIVE-P is non-nil and no problems were 220 found. 221 222 Returns nil." 223 (interactive "p") 224 (let ((executable pdf-info-epdfinfo-program)) 225 (unless (stringp executable) 226 (error "pdf-info-epdfinfo-program is unset or not a string")) 227 (unless (file-executable-p executable) 228 (error "pdf-info-epdfinfo-program is not executable")) 229 (when pdf-info-epdfinfo-error-filename 230 (unless (and (stringp pdf-info-epdfinfo-error-filename) 231 (file-writable-p pdf-info-epdfinfo-error-filename)) 232 (error "pdf-info-epdfinfo-error-filename should contain writable filename"))) 233 (let* ((default-directory (expand-file-name "~/")) 234 (cmdfile (make-temp-file "commands")) 235 (pdffile (make-temp-file "empty.pdf")) 236 (tempdir (make-temp-file "tmpdir" t)) 237 (process-environment (cons (concat "TMPDIR=" tempdir) 238 process-environment))) 239 (unwind-protect 240 (with-temp-buffer 241 (with-temp-file pdffile 242 (set-buffer-multibyte nil) 243 (insert pdf-info-empty-page-data)) 244 (with-temp-file cmdfile 245 (insert (format "renderpage:%s:1:100\nquit\n" 246 (pdf-info-query--escape pdffile)))) 247 (unless (= 0 (apply #'call-process 248 executable cmdfile (current-buffer) 249 nil (when pdf-info-epdfinfo-error-filename 250 (list pdf-info-epdfinfo-error-filename)))) 251 (error "Error running `%s': %s" 252 pdf-info-epdfinfo-program 253 (buffer-string)))) 254 (when (file-exists-p cmdfile) 255 (delete-file cmdfile)) 256 (when (file-exists-p pdffile) 257 (delete-file pdffile)) 258 (when (file-exists-p tempdir) 259 (delete-directory tempdir t))))) 260 (when interactive-p 261 (message "The epdfinfo program appears to be working.")) 262 nil) 263 264 (defun pdf-info-process-assert-running (&optional force) 265 "Assert a running process. 266 267 If it never ran, i.e. `pdf-info-process' is t, start it 268 unconditionally. 269 270 Otherwise, if FORCE is non-nil start it, if it is not running. 271 Else restart it with respect to the variable 272 `pdf-info-restart-process-p', which see. 273 274 If getting the process to run fails, this function throws an 275 error." 276 (interactive "P") 277 (unless (and (processp (pdf-info-process)) 278 (eq (process-status (pdf-info-process)) 279 'run)) 280 (when (pdf-info-process) 281 (tq-close pdf-info--queue) 282 (setq pdf-info--queue nil)) 283 (unless (or force 284 (eq pdf-info--queue t) 285 (and (eq pdf-info-restart-process-p 'ask) 286 (not noninteractive) 287 (y-or-n-p "The epdfinfo server quit, restart it ? ")) 288 (and pdf-info-restart-process-p 289 (not (eq pdf-info-restart-process-p 'ask)))) 290 291 (when (eq pdf-info-restart-process-p 'ask) 292 (setq pdf-info-restart-process-p nil)) 293 (error "The epdfinfo server quit")) 294 (pdf-info-check-epdfinfo) 295 (let* ((process-connection-type) ;Avoid 4096 Byte bug #12440. 296 (default-directory "~") 297 (proc (apply #'start-process 298 "epdfinfo" " *epdfinfo*" pdf-info-epdfinfo-program 299 (when pdf-info-epdfinfo-error-filename 300 (list pdf-info-epdfinfo-error-filename))))) 301 (with-current-buffer " *epdfinfo*" 302 (erase-buffer)) 303 (set-process-query-on-exit-flag proc nil) 304 (set-process-coding-system proc 'utf-8-unix 'utf-8-unix) 305 (setq pdf-info--queue (tq-create proc)))) 306 pdf-info--queue) 307 308 (when (< emacs-major-version 27) 309 (advice-add 'tq-process-buffer :around #'pdf-info--tq-workaround)) 310 311 (defun pdf-info--tq-workaround (orig-fun tq &rest args) 312 "Fix a bug in trunk where the wrong callback gets called. 313 314 ORIG-FUN is the callback that should be called. TQ and ARGS are 315 the transmission-queue and arguments to the callback." 316 ;; FIXME: Make me iterative. 317 (if (not (equal (car (process-command (tq-process tq))) 318 pdf-info-epdfinfo-program)) 319 (apply orig-fun tq args) 320 (let ((buffer (tq-buffer tq)) 321 done) 322 (when (buffer-live-p buffer) 323 (set-buffer buffer) 324 (while (and (not done) 325 (> (buffer-size) 0)) 326 (setq done t) 327 (if (tq-queue-empty tq) 328 (let ((buf (generate-new-buffer "*spurious*"))) 329 (copy-to-buffer buf (point-min) (point-max)) 330 (delete-region (point-min) (point)) 331 (pop-to-buffer buf nil) 332 (error "Spurious communication from process %s, see buffer %s" 333 (process-name (tq-process tq)) 334 (buffer-name buf))) 335 (goto-char (point-min)) 336 (when (re-search-forward (tq-queue-head-regexp tq) nil t) 337 (setq done nil) 338 (let ((answer (buffer-substring (point-min) (point))) 339 (fn (tq-queue-head-fn tq)) 340 (closure (tq-queue-head-closure tq))) 341 (delete-region (point-min) (point)) 342 (tq-queue-pop tq) 343 (condition-case-unless-debug err 344 (funcall fn closure answer) 345 (error 346 (message "Error while processing tq callback: %s" 347 (error-message-string err)))))))))))) 348 349 350 ;; * ================================================================== * 351 ;; * Sending and receiving 352 ;; * ================================================================== * 353 354 (defun pdf-info-query (cmd &rest args) 355 "Query the server using CMD and ARGS." 356 (pdf-info-process-assert-running) 357 (unless (symbolp cmd) 358 (setq cmd (intern cmd))) 359 (let* ((query (concat (mapconcat #'pdf-info-query--escape 360 (cons cmd args) ":") 361 "\n")) 362 (callback 363 (lambda (closure response) 364 (cl-destructuring-bind (status &rest result) 365 (pdf-info-query--parse-response cmd response) 366 (pdf-info-query--log response) 367 (let* (pdf-info-asynchronous) 368 (if (functionp closure) 369 (funcall closure status result) 370 (apply (car closure) status result (cdr closure))))))) 371 response status done 372 (closure (or pdf-info-asynchronous 373 (lambda (s r) 374 (setq status s response r done t))))) 375 (pdf-info-query--log query t) 376 (tq-enqueue 377 pdf-info--queue query "^\\.\n" closure callback) 378 (unless pdf-info-asynchronous 379 (while (and (not done) 380 (eq (process-status (pdf-info-process)) 381 'run)) 382 (accept-process-output (pdf-info-process) 0.01)) 383 (when (and (not done) 384 (not (eq (process-status (pdf-info-process)) 385 'run)) 386 (not (eq cmd 'quit))) 387 (error "The epdfinfo server quit unexpectedly")) 388 (cond 389 ((null status) response) 390 ((eq status 'error) 391 (error "epdfinfo: %s" response)) 392 ((eq status 'interrupted) 393 (error "epdfinfo: Command was interrupted")) 394 (t 395 (error "Internal error: invalid response status")))))) 396 397 (defun pdf-info-interrupt () 398 "FIXME: This command does currently nothing." 399 (when (and (processp (pdf-info-process)) 400 (eq (process-status (pdf-info-process)) 401 'run)) 402 (signal-process (pdf-info-process) 'SIGUSR1))) 403 404 (defun pdf-info-query--escape (arg) 405 "Escape ARG for transmission to the server." 406 (if (null arg) 407 (string) 408 (with-current-buffer (get-buffer-create " *pdf-info-query--escape*") 409 (erase-buffer) 410 (insert (format "%s" arg)) 411 (goto-char 1) 412 (while (not (eobp)) 413 (cond 414 ((memq (char-after) '(?\\ ?:)) 415 (insert ?\\)) 416 ((eq (char-after) ?\n) 417 (delete-char 1) 418 (insert ?\\ ?n) 419 (backward-char))) 420 (forward-char)) 421 (buffer-substring-no-properties 1 (point-max))))) 422 423 (defmacro pdf-info-query--read-record () 424 "Read a single record of the response in current buffer." 425 `(let (records done (beg (point))) 426 (while (not done) 427 (cl-case (char-after) 428 (?\\ 429 (delete-char 1) 430 (if (not (eq (char-after) ?n)) 431 (forward-char) 432 (delete-char 1) 433 (insert ?\n))) 434 ((?: ?\n) 435 (push (buffer-substring-no-properties 436 beg (point)) records) 437 (forward-char) 438 (setq beg (point) 439 done (bolp))) 440 (t (forward-char)))) 441 (nreverse records))) 442 443 (defun pdf-info-query--parse-response (cmd response) 444 "Parse one epdfinfo RESPONSE to CMD. 445 446 Returns a cons \(STATUS . RESULT\), where STATUS is one of nil 447 for a regular response, error for an error \(RESULT contains the 448 error message\) or interrupted, i.e. the command was 449 interrupted." 450 (with-current-buffer 451 (get-buffer-create " *pdf-info-query--parse-response*") 452 (erase-buffer) 453 (insert response) 454 (goto-char 1) 455 (cond 456 ((looking-at "ERR\n") 457 (forward-line) 458 (cons 'error (buffer-substring-no-properties 459 (point) 460 (progn 461 (re-search-forward "^\\.\n") 462 (1- (match-beginning 0)))))) 463 ((looking-at "OK\n") 464 (let (result) 465 (forward-line) 466 (while (not (and (= (char-after) ?.) 467 (= (char-after (1+ (point))) ?\n))) 468 (push (pdf-info-query--read-record) result)) 469 (cons nil (pdf-info-query--transform-response 470 cmd (nreverse result))))) 471 ((looking-at "INT\n") 472 (cons 'interrupted nil)) 473 (t 474 (cons 'error "Invalid server response"))))) 475 476 (defun pdf-info-query--transform-response (cmd response) 477 "Transform a RESPONSE to CMD into a Lisp form." 478 (cl-case cmd 479 (open nil) 480 (close (equal "1" (caar response))) 481 (number-of-pages (string-to-number (caar response))) 482 (charlayout 483 (mapcar (lambda (elt) 484 (cl-assert (= 1 (length (cadr elt))) t) 485 `(,(aref (cadr elt) 0) 486 ,(mapcar #'string-to-number 487 (split-string (car elt) " " t)))) 488 response)) 489 (regexp-flags 490 (mapcar (lambda (elt) 491 (cons (intern (car elt)) 492 (string-to-number (cadr elt)))) 493 response)) 494 ((search-string search-regexp) 495 (mapcar 496 (lambda (r) 497 `((page . ,(string-to-number (nth 0 r))) 498 (text . ,(let (case-fold-search) 499 (pdf-util-highlight-regexp-in-string 500 (regexp-quote (nth 1 r)) (nth 2 r)))) 501 (edges . ,(mapcar (lambda (m) 502 (mapcar #'string-to-number 503 (split-string m " " t))) 504 (cddr (cdr r)))))) 505 response)) 506 (outline 507 (mapcar (lambda (r) 508 `((depth . ,(string-to-number (pop r))) 509 ,@(pdf-info-query--transform-action r))) 510 response)) 511 (pagelinks 512 (mapcar (lambda (r) 513 `((edges . 514 ,(mapcar #'string-to-number ;area 515 (split-string (pop r) " " t))) 516 ,@(pdf-info-query--transform-action r))) 517 response)) 518 (metadata 519 (let ((md (car response))) 520 (if (= 1 (length md)) 521 (list (cons 'title (car md))) 522 (list 523 (cons 'title (pop md)) 524 (cons 'author (pop md)) 525 (cons 'subject (pop md)) 526 (cons 'keywords-raw (car md)) 527 (cons 'keywords (split-string (pop md) "[\t\n ]*,[\t\n ]*" t)) 528 (cons 'creator (pop md)) 529 (cons 'producer (pop md)) 530 (cons 'format (pop md)) 531 (cons 'created (pop md)) 532 (cons 'modified (pop md)))))) 533 (gettext 534 (or (caar response) "")) 535 (getselection 536 (mapcar (lambda (line) 537 (mapcar #'string-to-number 538 (split-string (car line) " " t))) 539 response)) 540 (features (mapcar #'intern (car response))) 541 (pagesize 542 (setq response (car response)) 543 (cons (round (string-to-number (car response))) 544 (round (string-to-number (cadr response))))) 545 ((getannot editannot addannot) 546 (pdf-info-query--transform-annotation (car response))) 547 (getannots 548 (mapcar #'pdf-info-query--transform-annotation response)) 549 (getattachments 550 (mapcar #'pdf-info-query--transform-attachment response)) 551 ((getattachment-from-annot) 552 (pdf-info-query--transform-attachment (car response))) 553 (boundingbox 554 (mapcar #'string-to-number (car response))) 555 (synctex-forward-search 556 (let ((list (mapcar #'string-to-number (car response)))) 557 `((page . ,(car list)) 558 (edges . ,(cdr list))))) 559 (synctex-backward-search 560 `((filename . ,(caar response)) 561 (line . ,(string-to-number (cadr (car response)))) 562 (column . ,(string-to-number (cadr (cdar response)))))) 563 (delannot nil) 564 ((save) (caar response)) 565 ((renderpage renderpage-text-regions renderpage-highlight) 566 (pdf-util-munch-file (caar response))) 567 ((setoptions getoptions) 568 (let (options) 569 (dolist (key-value response) 570 (let ((key (intern (car key-value))) 571 (value (cadr key-value))) 572 (cl-case key 573 ((:render/printed :render/usecolors) 574 (setq value (equal value "1")))) 575 (push value options) 576 (push key options))) 577 options)) 578 (pagelabels (mapcar #'car response)) 579 (ping (caar response)) 580 (t response))) 581 582 583 (defun pdf-info-query--transform-action (action) 584 "Transform ACTION response into a Lisp form." 585 (let ((type (intern (pop action)))) 586 `((type . ,type) 587 (title . ,(pop action)) 588 ,@(cl-case type 589 (goto-dest 590 `((page . ,(string-to-number (pop action))) 591 (top . ,(and (> (length (car action)) 0) 592 (string-to-number (pop action)))))) 593 (goto-remote 594 `((filename . ,(pop action)) 595 (page . ,(string-to-number (pop action))) 596 (top . ,(and (> (length (car action)) 0) 597 (string-to-number (pop action)))))) 598 (t `((uri . ,(pop action)))))))) 599 600 (defun pdf-info-query--transform-annotation (a) 601 (cl-labels ((not-empty (s) 602 (if (not (equal s "")) s))) 603 (let (a1 a2 a3) 604 (cl-destructuring-bind (page edges type id flags color contents modified &rest rest) 605 a 606 (setq a1 `((page . ,(string-to-number page)) 607 (edges . ,(mapcar #'string-to-number 608 (split-string edges " " t))) 609 (type . ,(intern type)) 610 (id . ,(intern id)) 611 (flags . ,(string-to-number flags)) 612 (color . ,(not-empty color)) 613 (contents . ,contents) 614 (modified . ,(pdf-info-parse-pdf-date modified)))) 615 (when rest 616 (cl-destructuring-bind (label subject opacity popup-edges popup-is-open created 617 &rest rest) 618 rest 619 (setq a2 620 `((label . ,(not-empty label)) 621 (subject . ,(not-empty subject)) 622 (opacity . ,(let ((o (not-empty opacity))) 623 (and o (string-to-number o)))) 624 (popup-edges . ,(let ((p (not-empty popup-edges))) 625 (when p 626 (mapcar #'string-to-number 627 (split-string p " " t))))) 628 (popup-is-open . ,(equal popup-is-open "1")) 629 (created . ,(pdf-info-parse-pdf-date (not-empty created))))) 630 (cond 631 ((eq (cdr (assoc 'type a1)) 'text) 632 (cl-destructuring-bind (icon state is-open) 633 rest 634 (setq a3 635 `((icon . ,(not-empty icon)) 636 (state . ,(not-empty state)) 637 (is-open . ,(equal is-open "1")))))) 638 ((memq (cdr (assoc 'type a1)) 639 '(squiggly highlight underline strike-out)) 640 (setq a3 `((markup-edges 641 . ,(mapcar (lambda (r) 642 (mapcar #'string-to-number 643 (split-string r " " t))) 644 rest))))))))) 645 (append a1 a2 a3)))) 646 647 (defun pdf-info-query--transform-attachment (a) 648 (cl-labels ((not-empty (s) 649 (if (not (equal s "")) s))) 650 (cl-destructuring-bind (id filename description size modified 651 created checksum file) 652 a 653 `((id . ,(intern id)) 654 (filename . ,(not-empty filename)) 655 (description . ,(not-empty description)) 656 (size . ,(let ((n (string-to-number size))) 657 (and (>= n 0) n))) 658 (modified . ,(not-empty modified)) 659 (created . ,(not-empty created)) 660 (checksum . ,(not-empty checksum)) 661 (file . ,(not-empty file)))))) 662 663 (defun pdf-info-query--log (string &optional query-p) 664 "Log STRING as query/response, depending on QUERY-P. 665 666 This is a no-op, if `pdf-info-log' is nil." 667 (when pdf-info-log 668 (with-current-buffer (get-buffer-create "*pdf-info-log*") 669 (buffer-disable-undo) 670 (let ((pos (point-max)) 671 (window (get-buffer-window))) 672 (save-excursion 673 (goto-char (point-max)) 674 (unless (bolp) 675 (insert ?\n)) 676 (insert 677 (propertize 678 (format-time-string "%H:%M:%S ") 679 'face 680 (if query-p 681 'font-lock-keyword-face 682 'font-lock-function-name-face)) 683 (if (and (numberp pdf-info-log-entry-max) 684 (> (length string) 685 pdf-info-log-entry-max)) 686 (concat (substring string 0 pdf-info-log-entry-max) 687 "...[truncated]\n") 688 string))) 689 (when (and (window-live-p window) 690 (= pos (window-point window))) 691 (set-window-point window (point-max))))))) 692 693 694 695 ;; * ================================================================== * 696 ;; * Utility functions 697 ;; * ================================================================== * 698 699 (defvar doc-view-buffer-file-name) 700 (defvar doc-view--buffer-file-name) 701 702 (defun pdf-info--normalize-file-or-buffer (file-or-buffer) 703 "Return the PDF file corresponding to FILE-OR-BUFFER. 704 705 FILE-OR-BUFFER may be nil, a PDF buffer, the name of a PDF buffer 706 or a PDF file." 707 (unless file-or-buffer 708 (setq file-or-buffer 709 (current-buffer))) 710 (when (bufferp file-or-buffer) 711 (unless (buffer-live-p file-or-buffer) 712 (error "Buffer is not live :%s" file-or-buffer)) 713 (with-current-buffer file-or-buffer 714 (unless (setq file-or-buffer 715 (cl-case major-mode 716 (doc-view-mode 717 (cond ((boundp 'doc-view-buffer-file-name) 718 doc-view-buffer-file-name) 719 ((boundp 'doc-view--buffer-file-name) 720 doc-view--buffer-file-name))) 721 (pdf-view-mode (pdf-view-buffer-file-name)) 722 (t (buffer-file-name)))) 723 (error "Buffer is not associated with any file :%s" (buffer-name))))) 724 (unless (stringp file-or-buffer) 725 (signal 'wrong-type-argument 726 (list 'stringp 'bufferp 'null file-or-buffer))) 727 ;; is file 728 (when (file-remote-p file-or-buffer) 729 (error "Processing remote files not supported :%s" 730 file-or-buffer)) 731 ;; (unless (file-readable-p file-or-buffer) 732 ;; (error "File not readable :%s" file-or-buffer)) 733 (expand-file-name file-or-buffer)) 734 735 (defun pdf-info-valid-page-spec-p (pages) 736 "The type predicate for a valid page-spec." 737 (not (not (ignore-errors (pdf-info-normalize-page-range pages))))) 738 739 (defun pdf-info-normalize-page-range (pages) 740 "Normalize PAGES for sending to the server. 741 742 PAGES may be a single page number, a cons \(FIRST . LAST\), or 743 nil, which stands for all pages. 744 745 The result is a cons \(FIRST . LAST\), where LAST may be 0 746 representing the final page." 747 (cond 748 ((natnump pages) 749 (cons pages pages)) 750 ((null pages) 751 (cons 1 0)) 752 ((and (natnump (car pages)) 753 (natnump (cdr pages))) 754 pages) 755 (t 756 (signal 'wrong-type-argument 757 (list 'pdf-info-valid-page-spec-p pages))))) 758 759 (defun pdf-info-parse-pdf-date (date) 760 (when (and date 761 (string-match pdf-info-pdf-date-regexp date)) 762 (let ((year (match-string 1 date)) 763 (month (match-string 2 date)) 764 (day (match-string 3 date)) 765 (hour (match-string 4 date)) 766 (min (match-string 5 date)) 767 (sec (match-string 6 date)) 768 (ut-char (match-string 7 date)) 769 (ut-hour (match-string 8 date)) 770 (ut-min (match-string 9 date)) 771 (tz 0)) 772 (when (or (equal ut-char "+") 773 (equal ut-char "-")) 774 (when ut-hour 775 (setq tz (* 3600 (string-to-number ut-hour)))) 776 (when ut-min 777 (setq tz (+ tz (* 60 (string-to-number ut-min))))) 778 (when (equal ut-char "-") 779 (setq tz (- tz)))) 780 (encode-time 781 (if sec (string-to-number sec) 0) 782 (if min (string-to-number min) 0) 783 (if hour (string-to-number hour) 0) 784 (if day (string-to-number day) 1) 785 (if month (string-to-number month) 1) 786 (string-to-number year) 787 tz)))) 788 789 (defmacro pdf-info-compose-queries (let-forms &rest body) 790 "Let-bind each VAR to QUERIES results and evaluate BODY. 791 792 All queries in each QUERIES form are run by the server in the 793 order they appear and the results collected in a list, which is 794 bound to VAR. Then BODY is evaluated and its value becomes the 795 final result of all queries, unless at least one of them provoked 796 an error. In this case BODY is ignored and the error is the 797 result. 798 799 This macro handles synchronous and asynchronous calls, 800 i.e. `pdf-info-asynchronous' is non-nil, transparently. 801 802 \(FN \(\(VAR QUERIES\)...\) BODY\)" 803 (declare (indent 1) 804 (debug ((&rest &or 805 (symbolp &optional form) 806 symbolp) 807 body))) 808 (unless (cl-every (lambda (form) 809 (when (symbolp form) 810 (setq form (list form))) 811 (and (consp form) 812 (symbolp (car form)) 813 (listp (cdr form)))) 814 let-forms) 815 (error "Invalid let-form: %s" let-forms)) 816 817 (setq let-forms (mapcar (lambda (form) 818 (if (symbolp form) 819 (list form) 820 form)) 821 let-forms)) 822 (let* ((status (make-symbol "status")) 823 (response (make-symbol "response")) 824 (first-error (make-symbol "first-error")) 825 (done (make-symbol "done")) 826 (callback (make-symbol "callback")) 827 (results (make-symbol "results")) 828 (push-fn (make-symbol "push-fn")) 829 (terminal-fn (make-symbol "terminal-fn")) 830 (buffer (make-symbol "buffer"))) 831 `(let* (,status 832 ,response ,first-error ,done 833 (,buffer (current-buffer)) 834 (,callback pdf-info-asynchronous) 835 ;; Ensure a new alist on every invocation. 836 (,results (mapcar 'copy-sequence 837 ',(cl-mapcar (lambda (form) 838 (list (car form))) 839 let-forms))) 840 (,push-fn (lambda (status result var) 841 ;; Store result in alist RESULTS under key 842 ;; VAR. 843 (if status 844 (unless ,first-error 845 (setq ,first-error result)) 846 (let ((elt (assq var ,results))) 847 (setcdr elt (append (cdr elt) 848 (list result))))))) 849 (,terminal-fn 850 (lambda (&rest _) 851 ;; Let-bind responses corresponding to their variables, 852 ;; i.e. keys in alist RESULTS. 853 (let (,@(mapcar (lambda (var) 854 `(,var (cdr (assq ',var ,results)))) 855 (mapcar #'car let-forms))) 856 (setq ,status (not (not ,first-error)) 857 ,response (or ,first-error 858 (with-current-buffer ,buffer 859 ,@body)) 860 ,done t) 861 ;; Maybe invoke the CALLBACK (which was bound to 862 ;; pdf-info-asynchronous). 863 (when ,callback 864 (if (functionp ,callback) 865 (funcall ,callback ,status ,response) 866 (apply (car ,callback) 867 ,status ,response (cdr ,callback)))))))) 868 ;; Wrap each query in an asynchronous call, with its VAR as 869 ;; callback argument, so the PUSH-FN can put it in the alist 870 ;; RESULTS. 871 ,@(mapcar (lambda (form) 872 (list 'let (list 873 (list 'pdf-info-asynchronous 874 (list 'list push-fn (list 'quote (car form))))) 875 (cadr form))) 876 let-forms) 877 ;; Request a no-op, just so we know that we are finished. 878 (let ((pdf-info-asynchronous ,terminal-fn)) 879 (pdf-info-ping)) 880 ;; CALLBACK is the original value of pdf-info-asynchronous. If 881 ;; nil, this is a synchronous query. 882 (unless ,callback 883 (while (and (not ,done) 884 (eq (process-status (pdf-info-process)) 885 'run)) 886 (accept-process-output (pdf-info-process) 0.01)) 887 (when (and (not ,done) 888 (not (eq (process-status (pdf-info-process)) 889 'run))) 890 (error "The epdfinfo server quit unexpectedly")) 891 (when ,status 892 (error "epdfinfo: %s" ,response)) 893 ,response)))) 894 895 896 ;; * ================================================================== * 897 ;; * Buffer local server instances 898 ;; * ================================================================== * 899 900 (put 'pdf-info--queue 'permanent-local t) 901 902 (defun pdf-info-make-local-server (&optional buffer force-restart-p) 903 "Create a server instance local to BUFFER. 904 905 Does nothing if BUFFER already has a local instance. Unless 906 FORCE-RESTART-P is non-nil, then quit a potential process and 907 restart it." 908 (unless buffer 909 (setq buffer (current-buffer))) 910 (with-current-buffer buffer 911 (unless (and 912 (not force-restart-p) 913 (local-variable-p 'pdf-info--queue) 914 (processp (pdf-info-process)) 915 (eq (process-status (pdf-info-process)) 916 'run)) 917 (when (and (local-variable-p 'pdf-info--queue) 918 (processp (pdf-info-process))) 919 (tq-close pdf-info--queue)) 920 (set (make-local-variable 'pdf-info--queue) nil) 921 (pdf-info-process-assert-running t) 922 (add-hook 'kill-buffer-hook #'pdf-info-kill-local-server nil t) 923 pdf-info--queue))) 924 925 (defun pdf-info-kill-local-server (&optional buffer) 926 "Kill the local server in BUFFER. 927 928 A No-op, if BUFFER has not running server instance." 929 (save-current-buffer 930 (when buffer 931 (set-buffer buffer)) 932 (when (local-variable-p 'pdf-info--queue) 933 (pdf-info-kill) 934 (kill-local-variable 'pdf-info--queue) 935 t))) 936 937 (defun pdf-info-local-server-p (&optional buffer) 938 "Return non-nil, if BUFFER has a running server instance." 939 (unless buffer 940 (setq buffer (current-buffer))) 941 (setq buffer (get-buffer buffer)) 942 (and (buffer-live-p buffer) 943 (local-variable-p 'pdf-info--queue buffer))) 944 945 (defun pdf-info-local-batch-query (producer-fn 946 consumer-fn 947 sentinel-fn 948 args) 949 "Process a set of queries asynchronously in a local instance." 950 (unless (pdf-info-local-server-p) 951 (error "Create a local server first")) 952 (let* ((buffer (current-buffer)) 953 (producer-symbol (make-symbol "producer")) 954 (consumer-symbol (make-symbol "consumer")) 955 (producer 956 (lambda (args) 957 (if (null args) 958 (funcall sentinel-fn 'finished buffer) 959 (let ((pdf-info-asynchronous 960 (apply-partially 961 (symbol-function consumer-symbol) 962 args))) 963 (cond 964 ((pdf-info-local-server-p buffer) 965 (with-current-buffer buffer 966 (apply producer-fn (car args)))) 967 (t 968 (funcall sentinel-fn 'error buffer))))))) 969 (consumer (lambda (args status result) 970 (if (not (pdf-info-local-server-p buffer)) 971 (funcall sentinel-fn 'error buffer) 972 (with-current-buffer buffer 973 (apply consumer-fn status result (car args))) 974 (funcall (symbol-function producer-symbol) 975 (cdr args)))))) 976 (fset producer-symbol producer) 977 (fset consumer-symbol consumer) 978 (funcall producer args))) 979 980 981 982 ;; * ================================================================== * 983 ;; * High level interface 984 ;; * ================================================================== * 985 986 (defvar pdf-info-features nil) 987 988 (defun pdf-info-features () 989 "Return a list of symbols describing compile-time features." 990 (or pdf-info-features 991 (setq pdf-info-features 992 (let (pdf-info-asynchronous) 993 (pdf-info-query 'features))))) 994 995 (defun pdf-info-writable-annotations-p () 996 (not (null (memq 'writable-annotations (pdf-info-features))))) 997 998 (defun pdf-info-markup-annotations-p () 999 (not (null (memq 'markup-annotations (pdf-info-features))))) 1000 1001 (defmacro pdf-info-assert-writable-annotations () 1002 `(unless (memq 'writable-annotations (pdf-info-features)) 1003 (error "Writing annotations is not supported by this version of epdfinfo"))) 1004 1005 (defmacro pdf-info-assert-markup-annotations () 1006 `(unless (memq 'markup-annotations (pdf-info-features)) 1007 (error "Creating markup annotations is not supported by this version of epdfinfo"))) 1008 1009 (defun pdf-info-creatable-annotation-types () 1010 (let ((features (pdf-info-features))) 1011 (cond 1012 ((not (memq 'writable-annotations features)) nil) 1013 ((memq 'markup-annotations features) 1014 (list 'text 'squiggly 'underline 'strike-out 'highlight)) 1015 (t (list 'text))))) 1016 1017 (defun pdf-info-open (&optional file-or-buffer password) 1018 "Open the document FILE-OR-BUFFER using PASSWORD. 1019 1020 Generally, documents are opened and closed automatically on 1021 demand, so this function is rarely needed, unless a PASSWORD is 1022 set on the document. 1023 1024 Manually opened documents are never closed automatically." 1025 1026 (pdf-info-query 1027 'open (pdf-info--normalize-file-or-buffer file-or-buffer) 1028 password)) 1029 1030 (defun pdf-info-close (&optional file-or-buffer) 1031 "Close the document FILE-OR-BUFFER. 1032 1033 Returns t, if the document was actually open, otherwise nil. 1034 This command is rarely needed, see also `pdf-info-open'." 1035 (let* ((pdf (pdf-info--normalize-file-or-buffer file-or-buffer)) 1036 (buffer (cond 1037 ((not file-or-buffer) (current-buffer)) 1038 ((bufferp file-or-buffer) file-or-buffer) 1039 ((stringp file-or-buffer) 1040 (find-buffer-visiting file-or-buffer))))) 1041 (prog1 1042 (pdf-info-query 'close pdf) 1043 (if (buffer-live-p buffer) 1044 (with-current-buffer buffer 1045 (run-hooks 'pdf-info-close-document-hook)) 1046 (with-temp-buffer 1047 (run-hooks 'pdf-info-close-document-hook)))))) 1048 1049 (defun pdf-info-encrypted-p (&optional file-or-buffer) 1050 "Return non-nil if FILE-OR-BUFFER requires a password. 1051 1052 Note: This function returns nil, if the document is encrypted, 1053 but was already opened (presumably using a password)." 1054 1055 (condition-case err 1056 (pdf-info-open 1057 (pdf-info--normalize-file-or-buffer file-or-buffer)) 1058 (error (or (string-match-p 1059 ":Document is encrypted\\'" (cadr err)) 1060 (signal (car err) (cdr err)))))) 1061 1062 (defun pdf-info-metadata (&optional file-or-buffer) 1063 "Extract the metadata from the document FILE-OR-BUFFER. 1064 1065 This returns an alist containing some information about the 1066 document." 1067 (pdf-info-query 1068 'metadata 1069 (pdf-info--normalize-file-or-buffer file-or-buffer))) 1070 1071 (defun pdf-info-search-string (string &optional pages file-or-buffer) 1072 "Search for STRING in PAGES of document FILE-OR-BUFFER. 1073 1074 See `pdf-info-normalize-page-range' for valid PAGES formats. 1075 1076 This function returns a list of matches. Each item is an alist 1077 containing keys PAGE, TEXT and EDGES, where PAGE and TEXT are the 1078 matched page resp. line. EDGES is a list containing a single 1079 edges element \(LEFT TOP RIGHT BOTTOM\). This is for consistency 1080 with `pdf-info-search-regexp', which may return matches with 1081 multiple edges. 1082 1083 The TEXT contains `match' face properties on the matched parts. 1084 1085 Search is case-insensitive, unless `case-fold-search' is nil and 1086 searching case-sensitive is supported by the server." 1087 1088 (let ((pages (pdf-info-normalize-page-range pages))) 1089 (pdf-info-query 1090 'search-string 1091 (pdf-info--normalize-file-or-buffer file-or-buffer) 1092 (car pages) 1093 (cdr pages) 1094 string 1095 (if case-fold-search 1 0)))) 1096 1097 (defvar pdf-info-regexp-compile-flags nil 1098 "PCRE compile flags. 1099 1100 Don't use this, but the equally named function.") 1101 1102 (defvar pdf-info-regexp-match-flags nil 1103 "PCRE match flags. 1104 1105 Don't use this, but the equally named function.") 1106 1107 (defun pdf-info-regexp-compile-flags () 1108 (or pdf-info-regexp-compile-flags 1109 (let* (pdf-info-asynchronous 1110 (flags (pdf-info-query 'regexp-flags)) 1111 (match (cl-remove-if-not 1112 (lambda (flag) 1113 (string-match-p 1114 "\\`match-" (symbol-name (car flag)))) 1115 flags)) 1116 (compile (cl-set-difference flags match))) 1117 (setq pdf-info-regexp-compile-flags compile 1118 pdf-info-regexp-match-flags match) 1119 pdf-info-regexp-compile-flags))) 1120 1121 (defun pdf-info-regexp-match-flags () 1122 (or pdf-info-regexp-match-flags 1123 (progn 1124 (pdf-info-regexp-compile-flags) 1125 pdf-info-regexp-match-flags))) 1126 1127 (defvar pdf-info-regexp-flags '(multiline) 1128 "Compile- and match-flags for the PCRE engine. 1129 1130 This is a list of symbols denoting compile- and match-flags when 1131 searching for regular expressions. 1132 1133 You should not change this directly, but rather `let'-bind it 1134 around a call to `pdf-info-search-regexp'. 1135 1136 Valid compile-flags are: 1137 1138 newline-crlf, newline-lf, newline-cr, dupnames, optimize, 1139 no-auto-capture, raw, ungreedy, dollar-endonly, anchored, 1140 extended, dotall, multiline and caseless. 1141 1142 Note that the last one, caseless, is handled special, as it is 1143 always added if `case-fold-search' is non-nil. 1144 1145 And valid match-flags: 1146 1147 match-anchored, match-notbol, match-noteol, match-notempty, 1148 match-partial, match-newline-cr, match-newline-lf, 1149 match-newline-crlf and match-newline-any. 1150 1151 See the glib documentation at url 1152 `https://developer.gnome.org/glib/stable/glib-Perl-compatible-regular-expressions.html'.") 1153 1154 (defun pdf-info-search-regexp (pcre &optional pages 1155 no-error 1156 file-or-buffer) 1157 "Search for a PCRE on PAGES of document FILE-OR-BUFFER. 1158 1159 See `pdf-info-normalize-page-range' for valid PAGES formats and 1160 `pdf-info-search-string' for its return value. 1161 1162 Uses the flags in `pdf-info-regexp-flags', which see. If 1163 `case-fold-search' is non-nil, the caseless flag is added. 1164 1165 If NO-ERROR is non-nil, catch errors due to invalid regexps and 1166 return nil. If it is the symbol `invalid-regexp', then re-signal 1167 this kind of error as a `invalid-regexp' error." 1168 1169 (cl-labels ((orflags (flags alist) 1170 (cl-reduce 1171 (lambda (v flag) 1172 (let ((n 1173 (cdr (assq flag alist)))) 1174 (if n (logior n v) v))) 1175 (cons 0 flags)))) 1176 (let ((pages (pdf-info-normalize-page-range pages))) 1177 (condition-case err 1178 (pdf-info-query 1179 'search-regexp 1180 (pdf-info--normalize-file-or-buffer file-or-buffer) 1181 (car pages) 1182 (cdr pages) 1183 pcre 1184 (orflags `(,(if case-fold-search 1185 'caseless) 1186 ,@pdf-info-regexp-flags) 1187 (pdf-info-regexp-compile-flags)) 1188 (orflags pdf-info-regexp-flags 1189 (pdf-info-regexp-match-flags))) 1190 (error 1191 (let ((re 1192 (concat "\\`epdfinfo: *Invalid *regexp: *" 1193 ;; glib error 1194 "\\(?:Error while compiling regular expression" 1195 " *%s *\\)?\\(.*\\)"))) 1196 (if (or (null no-error) 1197 (not (string-match 1198 (format re (regexp-quote pcre)) 1199 (cadr err)))) 1200 (signal (car err) (cdr err)) 1201 (if (eq no-error 'invalid-regexp) 1202 (signal 'invalid-regexp 1203 (list (match-string 1 (cadr err)))))))))))) 1204 1205 (defun pdf-info-pagelinks (page &optional file-or-buffer) 1206 "Return a list of links on PAGE in document FILE-OR-BUFFER. 1207 1208 This function returns a list of alists with the following keys. 1209 EDGES represents the relative bounding-box of the link , TYPE is 1210 the type of the action, TITLE is a, possibly empty, name for this 1211 action. 1212 1213 TYPE may be one of 1214 1215 goto-dest -- This is a internal link to some page. Each element 1216 contains additional keys PAGE and TOP, where PAGE is the page of 1217 the link and TOP its vertical position. 1218 1219 goto-remote -- This a external link to some document. Same as 1220 goto-dest, with an additional FILENAME of the external PDF. 1221 1222 uri -- A link in form of some URI. Alist contains additional key 1223 URI. 1224 1225 In the first two cases, PAGE may be 0 and TOP nil, which means 1226 these data is unspecified." 1227 (cl-check-type page natnum) 1228 (pdf-info-query 1229 'pagelinks 1230 (pdf-info--normalize-file-or-buffer file-or-buffer) 1231 page)) 1232 1233 (defun pdf-info-number-of-pages (&optional file-or-buffer) 1234 "Return the number of pages in document FILE-OR-BUFFER." 1235 (pdf-info-query 'number-of-pages 1236 (pdf-info--normalize-file-or-buffer 1237 file-or-buffer))) 1238 1239 (defun pdf-info-outline (&optional file-or-buffer) 1240 "Return the PDF outline of document FILE-OR-BUFFER. 1241 1242 This function returns a list of alists like `pdf-info-pagelinks'. 1243 Additionally every alist has a DEPTH (>= 1) entry with the depth 1244 of this element in the tree." 1245 1246 (pdf-info-query 1247 'outline 1248 (pdf-info--normalize-file-or-buffer file-or-buffer))) 1249 1250 (defun pdf-info-gettext (page edges &optional selection-style 1251 file-or-buffer) 1252 "Get text on PAGE according to EDGES. 1253 1254 EDGES should contain relative coordinates. The selection may 1255 extend over multiple lines, which works similar to a Emacs 1256 region. SELECTION-STYLE may be one of glyph, word or line and 1257 determines the smallest unit of the selected region. 1258 1259 Return the text contained in the selection." 1260 1261 (pdf-info-query 1262 'gettext 1263 (pdf-info--normalize-file-or-buffer file-or-buffer) 1264 page 1265 (mapconcat #'number-to-string edges " ") 1266 (cl-case selection-style 1267 (glyph 0) 1268 (word 1) 1269 (line 2) 1270 (t 0)))) 1271 1272 (defun pdf-info-getselection (page edges &optional selection-style 1273 file-or-buffer) 1274 "Return the edges of the selection EDGES on PAGE. 1275 1276 Arguments are the same as for `pdf-info-gettext'. Return a list 1277 of edges corresponding to the text that would be returned by the 1278 aforementioned function, when called with the same arguments." 1279 1280 (pdf-info-query 1281 'getselection 1282 (pdf-info--normalize-file-or-buffer file-or-buffer) 1283 page 1284 (mapconcat #'number-to-string edges " ") 1285 (cl-case selection-style 1286 (glyph 0) 1287 (word 1) 1288 (line 2) 1289 (t 0)))) 1290 1291 (defun pdf-info-textregions (page &optional file-or-buffer) 1292 "Return a list of edges describing PAGE's text-layout." 1293 (pdf-info-getselection 1294 page '(0 0 1 1) 'glyph file-or-buffer)) 1295 1296 (defun pdf-info-charlayout (page &optional edges-or-pos file-or-buffer) 1297 "Return the layout of characters of PAGE in/at EDGES-OR-POS. 1298 1299 Returns a list of elements \(CHAR . \(LEFT TOP RIGHT BOT\)\) mapping 1300 character to their corresponding relative bounding-boxes. 1301 1302 EDGES-OR-POS may be a region \(LEFT TOP RIGHT BOT\) restricting 1303 the returned value to include only characters fully contained in 1304 it. Or a cons \(LEFT . TOP\) which means to only include the 1305 character at this position. In this case the return value 1306 contains at most one element." 1307 1308 ;; FIXME: Actually returns \(CHAR . LEFT ...\). 1309 1310 (unless edges-or-pos 1311 (setq edges-or-pos '(0 0 1 1))) 1312 (when (numberp (cdr edges-or-pos)) 1313 (setq edges-or-pos (list (car edges-or-pos) 1314 (cdr edges-or-pos) 1315 -1 -1))) 1316 (pdf-info-query 1317 'charlayout 1318 (pdf-info--normalize-file-or-buffer file-or-buffer) 1319 page 1320 (mapconcat #'number-to-string edges-or-pos " "))) 1321 1322 (defun pdf-info-pagesize (page &optional file-or-buffer) 1323 "Return the size of PAGE as a cons \(WIDTH . HEIGHT\) 1324 1325 The size is in PDF points." 1326 (pdf-info-query 1327 'pagesize 1328 (pdf-info--normalize-file-or-buffer file-or-buffer) 1329 page)) 1330 1331 (defun pdf-info-running-p () 1332 "Return non-nil, if the server is running." 1333 (and (processp (pdf-info-process)) 1334 (eq (process-status (pdf-info-process)) 1335 'run))) 1336 1337 (defun pdf-info-quit (&optional timeout) 1338 "Quit the epdfinfo server. 1339 1340 This blocks until all outstanding requests are answered. Unless 1341 TIMEOUT is non-nil, in which case we wait at most TIMEOUT seconds 1342 before killing the server." 1343 (cl-check-type timeout (or null number)) 1344 (when (pdf-info-running-p) 1345 (let ((pdf-info-asynchronous 1346 (if timeout (lambda (&rest _)) 1347 pdf-info-asynchronous))) 1348 (pdf-info-query 'quit) 1349 (when timeout 1350 (setq timeout (+ (float-time) (max 0 timeout))) 1351 (while (and (pdf-info-running-p) 1352 (> timeout (float-time))) 1353 (accept-process-output (pdf-info-process) 0.5 nil t))))) 1354 (when (processp (pdf-info-process)) 1355 (tq-close pdf-info--queue)) 1356 (setq pdf-info--queue nil)) 1357 1358 (defun pdf-info-kill () 1359 "Kill the epdfinfo server. 1360 1361 Immediately delete the server process, see also `pdf-info-quit', 1362 for a more sane way to exit the program." 1363 (when (processp (pdf-info-process)) 1364 (tq-close pdf-info--queue)) 1365 (setq pdf-info--queue nil)) 1366 1367 (defun pdf-info-getannots (&optional pages file-or-buffer) 1368 "Return the annotations on PAGE. 1369 1370 See `pdf-info-normalize-page-range' for valid PAGES formats. 1371 1372 This function returns the annotations for PAGES as a list of 1373 alists. Each element of this list describes one annotation and 1374 contains the following keys. 1375 1376 page - Its page number. 1377 edges - Its area. 1378 type - A symbol describing the annotation's type. 1379 id - A document-wide unique symbol referencing this annotation. 1380 flags - Its flags, binary encoded. 1381 color - Its color in standard Emacs notation. 1382 contents - The text of this annotation. 1383 modified - The last modification date of this annotation. 1384 1385 Additionally, if the annotation is a markup annotation, the 1386 following keys are present. 1387 1388 label - The annotation's label. 1389 subject - The subject addressed. 1390 opacity - The level of relative opacity. 1391 popup-edges - The edges of a associated popup window or nil. 1392 popup-is-open - Whether this window should be displayed open. 1393 created - The date this markup annotation was created. 1394 1395 If the annotation is also a markup text annotation, the alist 1396 contains the following keys. 1397 1398 text-icon - A string describing the purpose of this annotation. 1399 text-state - A string, e.g. accepted or rejected." ;FIXME: Use symbols ? 1400 1401 (let ((pages (pdf-info-normalize-page-range pages))) 1402 (pdf-info-query 1403 'getannots 1404 (pdf-info--normalize-file-or-buffer file-or-buffer) 1405 (car pages) 1406 (cdr pages)))) 1407 1408 (defun pdf-info-getannot (id &optional file-or-buffer) 1409 "Return the annotation for ID. 1410 1411 ID should be a symbol, which was previously returned in a 1412 `pdf-info-getannots' query. Signal an error, if an annotation 1413 with ID is not available. 1414 1415 See `pdf-info-getannots' for the kind of return value of this 1416 function." 1417 (pdf-info-query 1418 'getannot 1419 (pdf-info--normalize-file-or-buffer file-or-buffer) 1420 id)) 1421 1422 (defun pdf-info-addannot (page edges type &optional file-or-buffer &rest markup-edges) 1423 "Add a new annotation to PAGE with EDGES of TYPE. 1424 1425 FIXME: TYPE may be one of `text', `markup-highlight', ... . 1426 FIXME: -1 = 24 1427 See `pdf-info-getannots' for the kind of value of this function 1428 returns." 1429 (pdf-info-assert-writable-annotations) 1430 (when (consp file-or-buffer) 1431 (push file-or-buffer markup-edges) 1432 (setq file-or-buffer nil)) 1433 (apply 1434 #'pdf-info-query 1435 'addannot 1436 (pdf-info--normalize-file-or-buffer file-or-buffer) 1437 page 1438 type 1439 (mapconcat 'number-to-string edges " ") 1440 (mapcar (lambda (me) 1441 (mapconcat 'number-to-string me " ")) 1442 markup-edges))) 1443 1444 (defun pdf-info-delannot (id &optional file-or-buffer) 1445 "Delete the annotation with ID in FILE-OR-BUFFER. 1446 1447 ID should be a symbol, which was previously returned in a 1448 `pdf-info-getannots' query. Signal an error, if annotation ID 1449 does not exist." 1450 (pdf-info-assert-writable-annotations) 1451 (pdf-info-query 1452 'delannot 1453 (pdf-info--normalize-file-or-buffer file-or-buffer) 1454 id)) 1455 1456 (defun pdf-info-mvannot (id edges &optional file-or-buffer) 1457 "Move/Resize annotation ID to fit EDGES. 1458 1459 ID should be a symbol, which was previously returned in a 1460 `pdf-info-getannots' query. Signal an error, if annotation ID 1461 does not exist. 1462 1463 EDGES should be a list \(LEFT TOP RIGHT BOT\). RIGHT and/or BOT 1464 may also be negative, which means to keep the width 1465 resp. height." 1466 (pdf-info-editannot id `((edges . ,edges)) file-or-buffer)) 1467 1468 (defun pdf-info-editannot (id modifications &optional file-or-buffer) 1469 "Edit annotation ID, applying MODIFICATIONS. 1470 1471 ID should be a symbol, which was previously returned in a 1472 `pdf-info-getannots' query. 1473 1474 MODIFICATIONS is an alist of properties and their new values. 1475 1476 The server must support modifying annotations for this to work." 1477 1478 (pdf-info-assert-writable-annotations) 1479 (let ((edits 1480 (mapcar 1481 (lambda (elt) 1482 (cl-case (car elt) 1483 (color 1484 (list (car elt) 1485 (pdf-util-hexcolor (cdr elt)))) 1486 (edges 1487 (list (car elt) 1488 (mapconcat 'number-to-string (cdr elt) " "))) 1489 ((popup-is-open is-open) 1490 (list (car elt) (if (cdr elt) 1 0))) 1491 (t 1492 (list (car elt) (cdr elt))))) 1493 modifications))) 1494 (apply #'pdf-info-query 1495 'editannot 1496 (pdf-info--normalize-file-or-buffer file-or-buffer) 1497 id 1498 (apply #'append edits)))) 1499 1500 (defun pdf-info-save (&optional file-or-buffer) 1501 "Save FILE-OR-BUFFER. 1502 1503 This saves the document to a new temporary file, which is 1504 returned and owned by the caller." 1505 (pdf-info-assert-writable-annotations) 1506 (pdf-info-query 1507 'save 1508 (pdf-info--normalize-file-or-buffer file-or-buffer))) 1509 1510 (defun pdf-info-getattachment-from-annot (id &optional do-save file-or-buffer) 1511 "Return the attachment associated with annotation ID. 1512 1513 ID should be a symbol which was previously returned in a 1514 `pdf-info-getannots' query, and referencing an attachment of type 1515 `file', otherwise an error is signaled. 1516 1517 See `pdf-info-getattachments' for the kind of return value of this 1518 function and the meaning of DO-SAVE." 1519 1520 (pdf-info-query 1521 'getattachment-from-annot 1522 (pdf-info--normalize-file-or-buffer file-or-buffer) 1523 id 1524 (if do-save 1 0))) 1525 1526 (defun pdf-info-getattachments (&optional do-save file-or-buffer) 1527 "Return all document level attachments. 1528 1529 If DO-SAVE is non-nil, save the attachments data to a local file, 1530 which is then owned by the caller, see below. 1531 1532 This function returns a list of alists, where every element 1533 contains the following keys. All values, except for id, may be 1534 nil, i.e. not present. 1535 1536 id - A symbol uniquely identifying this attachment. 1537 filename - The filename of this attachment. 1538 description - A description of this attachment. 1539 size - The size in bytes. 1540 modified - The last modification date. 1541 created - The date of creation. 1542 checksum - A MD5 checksum of this attachment's data. 1543 file - The name of a tempfile containing the data (only present if 1544 DO-SAVE is non-nil)." 1545 1546 (pdf-info-query 1547 'getattachments 1548 (pdf-info--normalize-file-or-buffer file-or-buffer) 1549 (if do-save 1 0))) 1550 1551 (defun pdf-info-synctex-forward-search (source &optional line column file-or-buffer) 1552 "Perform a forward search with synctex. 1553 1554 SOURCE should be a LaTeX buffer or the absolute filename of a 1555 corresponding file. LINE and COLUMN represent the position in 1556 the buffer or file. Finally FILE-OR-BUFFER corresponds to the 1557 PDF document. 1558 1559 Returns an alist with entries PAGE and relative EDGES describing 1560 the position in the PDF document corresponding to the SOURCE 1561 location." 1562 1563 (let ((source (if (buffer-live-p (get-buffer source)) 1564 (buffer-file-name (get-buffer source)) 1565 source))) 1566 (pdf-info-query 1567 'synctex-forward-search 1568 (pdf-info--normalize-file-or-buffer file-or-buffer) 1569 source 1570 (or line 1) 1571 (or column 1)))) 1572 1573 (defun pdf-info-synctex-backward-search (page &optional x y file-or-buffer) 1574 "Perform a backward search with synctex. 1575 1576 Find the source location corresponding to the coordinates 1577 \(X . Y\) on PAGE in FILE-OR-BUFFER. 1578 1579 Returns an alist with entries FILENAME, LINE and COLUMN." 1580 1581 1582 (pdf-info-query 1583 'synctex-backward-search 1584 (pdf-info--normalize-file-or-buffer file-or-buffer) 1585 page 1586 (or x 0) 1587 (or y 0))) 1588 1589 (defun pdf-info-renderpage (page width &optional file-or-buffer &rest commands) 1590 "Render PAGE with width WIDTH. 1591 1592 Return the data of the corresponding PNG image." 1593 (when (keywordp file-or-buffer) 1594 (push file-or-buffer commands) 1595 (setq file-or-buffer nil)) 1596 (apply #'pdf-info-query 1597 'renderpage 1598 (pdf-info--normalize-file-or-buffer file-or-buffer) 1599 page 1600 (* width (pdf-util-frame-scale-factor)) 1601 (let (transformed) 1602 (while (cdr commands) 1603 (let ((kw (pop commands)) 1604 (value (pop commands))) 1605 (setq value 1606 (cl-case kw 1607 ((:crop-to :highlight-line :highlight-region :highlight-text) 1608 (mapconcat #'number-to-string value " ")) 1609 ((:foreground :background) 1610 (pdf-util-hexcolor value)) 1611 (:alpha 1612 (number-to-string value)) 1613 (otherwise value))) 1614 (push kw transformed) 1615 (push value transformed))) 1616 (when commands 1617 (error "Keyword is missing a value: %s" (car commands))) 1618 (nreverse transformed)))) 1619 1620 (defun pdf-info-renderpage-text-regions (page width single-line-p 1621 &optional file-or-buffer 1622 &rest regions) 1623 "Highlight text on PAGE with width WIDTH using REGIONS. 1624 1625 REGIONS is a list determining foreground and background color and 1626 the regions to render. So each element should look like \(FG BG 1627 \(LEFT TOP RIGHT BOT\) \(LEFT TOP RIGHT BOT\) ... \) . The 1628 rendering is text-aware. 1629 1630 If SINGLE-LINE-P is non-nil, the edges in REGIONS are each 1631 supposed to be limited to a single line in the document. Setting 1632 this, if applicable, avoids rendering problems. 1633 1634 For the other args see `pdf-info-renderpage'. 1635 1636 Return the data of the corresponding PNG image." 1637 1638 (when (consp file-or-buffer) 1639 (push file-or-buffer regions) 1640 (setq file-or-buffer nil)) 1641 1642 (apply #'pdf-info-renderpage 1643 page width file-or-buffer 1644 (apply #'append 1645 (mapcar (lambda (elt) 1646 `(:foreground ,(pop elt) 1647 :background ,(pop elt) 1648 ,@(cl-mapcan (lambda (edges) 1649 `(,(if single-line-p 1650 :highlight-line 1651 :highlight-text) 1652 ,edges)) 1653 elt))) 1654 regions)))) 1655 1656 (defun pdf-info-renderpage-highlight (page width 1657 &optional file-or-buffer 1658 &rest regions) 1659 "Highlight regions on PAGE with width WIDTH using REGIONS. 1660 1661 REGIONS is a list determining the background color, a alpha value 1662 and the regions to render. So each element should look like \(FILL-COLOR 1663 STROKE-COLOR ALPHA \(LEFT TOP RIGHT BOT\) \(LEFT TOP RIGHT BOT\) ... \) 1664 . 1665 1666 For the other args see `pdf-info-renderpage'. 1667 1668 Return the data of the corresponding PNG image." 1669 1670 (when (consp file-or-buffer) 1671 (push file-or-buffer regions) 1672 (setq file-or-buffer nil)) 1673 1674 (apply #'pdf-info-renderpage 1675 page width file-or-buffer 1676 (apply #'append 1677 (mapcar (lambda (elt) 1678 `(:background ,(pop elt) 1679 :foreground ,(pop elt) 1680 :alpha ,(pop elt) 1681 ,@(cl-mapcan (lambda (edges) 1682 `(:highlight-region ,edges)) 1683 elt))) 1684 regions)))) 1685 1686 (defun pdf-info-boundingbox (page &optional file-or-buffer) 1687 "Return a bounding-box for PAGE. 1688 1689 Returns a list \(LEFT TOP RIGHT BOT\)." 1690 1691 (pdf-info-query 1692 'boundingbox 1693 (pdf-info--normalize-file-or-buffer file-or-buffer) 1694 page)) 1695 1696 (defun pdf-info-getoptions (&optional file-or-buffer) 1697 (pdf-info-query 1698 'getoptions 1699 (pdf-info--normalize-file-or-buffer file-or-buffer))) 1700 1701 (defun pdf-info-setoptions (&optional file-or-buffer &rest options) 1702 (when (symbolp file-or-buffer) 1703 (push file-or-buffer options) 1704 (setq file-or-buffer nil)) 1705 (unless (= (% (length options) 2) 0) 1706 (error "Missing a option value")) 1707 (apply #'pdf-info-query 1708 'setoptions 1709 (pdf-info--normalize-file-or-buffer file-or-buffer) 1710 (let (soptions) 1711 (while options 1712 (let ((key (pop options)) 1713 (value (pop options))) 1714 (unless (and (keywordp key) 1715 (not (eq key :))) 1716 (error "Keyword expected: %s" key)) 1717 (cl-case key 1718 ((:render/foreground :render/background) 1719 (push (pdf-util-hexcolor value) 1720 soptions)) 1721 ((:render/usecolors :render/printed) 1722 (push (if value 1 0) soptions)) 1723 (t (push value soptions))) 1724 (push key soptions))) 1725 soptions))) 1726 1727 1728 1729 (defun pdf-info-pagelabels (&optional file-or-buffer) 1730 "Return a list of pagelabels. 1731 1732 Returns a list of strings corresponding to the labels of the 1733 pages in FILE-OR-BUFFER." 1734 1735 (pdf-info-query 1736 'pagelabels 1737 (pdf-info--normalize-file-or-buffer file-or-buffer))) 1738 1739 (defun pdf-info-ping (&optional message) 1740 "Ping the server using MESSAGE. 1741 1742 Returns MESSAGE, which defaults to \"pong\"." 1743 (pdf-info-query 'ping (or message "pong"))) 1744 1745 (provide 'pdf-info) 1746 1747 ;;; pdf-info.el ends here