-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathoverleaf.el
More file actions
1874 lines (1654 loc) · 78.7 KB
/
overleaf.el
File metadata and controls
1874 lines (1654 loc) · 78.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; overleaf.el --- Sync and track changes live with overleaf -*- lexical-binding: t; -*-
;; Copyright (C) 2020-2025 Valentin Boettcher
;; Author: Valentin Boettcher
;; Maintainer: Valentin Boettcher <overleaf at protagon.space>
;; Created: March 18, 2025
;; URL: https://github.com/vale981/overleaf.el
;; Package-Requires: ((emacs "29.4") (plz "0.9") (websocket "1.15") (webdriver "0.1") (posframe "1.4.4"))
;; Version: 1.1.5
;; Keywords: hypermedia, tex, comm
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is not part of GNU Emacs.
;;; License:
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or (at
;; your option) any later version.
;;
;; This program is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see https://www.gnu.org/licenses/.
;;; Commentary:
;; Provides a minor mode that allows to sync the changes of a buffer
;; to an overleaf instance (https://github.com/overleaf/overleaf).
(require 'webdriver)
(require 'webdriver-firefox)
(require 'websocket)
(require 'plz)
(require 'posframe)
(require 'xref)
;;; Code:
;;;; Variables
(defgroup overleaf nil
"Sync and track changes live with overleaf."
:prefix "overleaf-"
:group 'tools)
(defcustom overleaf-user-colors
["green" "red" "blue" "pink" "goldenrod"]
"The colors used to display cursors and names."
:type '(repeat color)
;; Customize UI cannot work with variable length vectors, so we need
;; these conversion functions.
:get (lambda (name) (append (symbol-value name) nil))
:set (lambda (name value) (set name (vconcat value))))
(defcustom overleaf-cursor-gravatars nil
"Display gravatars at other users' cursor positions."
:type 'boolean)
(defvar overleaf-cookies nil
"The overleaf session cookies.
Can a string or function that returns a string containing the overleaf
authentication cookies.
For example the variable can be bound to a function that loads the
cookies from a gpg encrypted file. See
`overleaf-read-cookies-from-file' or `overleaf-read-cookies-from-firefox'..
The cookies are most easily obtained from the developer tools in the
browser.")
(defun overleaf--buffer-string (&optional start end)
"Return the buffer contents between START and END with no text properties.
If START and END are nil, return the whole buffer.
Widen the buffer before extracting the contents."
(save-restriction
(widen)
(buffer-substring-no-properties
(or start (point-min))
(or end (point-max)))))
;;;###autoload
(defun overleaf-read-cookies-from-file (file)
"Return a cookie saving function to load the cookie-string from FILE.
To be used with `overleaf-cookies'."
(lambda ()
(with-temp-buffer
(insert-file-contents (expand-file-name file))
(read (string-trim (buffer-string))))))
(defun overleaf--sqlite-select-firefox-overleaf-cookies (dbfile)
"Return Overleaf cookies from Firefox cookie DBFILE.
Returns a list of (host cookie-string expiry)."
(let ((db (sqlite-open dbfile)))
(unwind-protect
(mapcar
(lambda (row)
(pcase-let* ((`(,domain ,name ,value ,expiry) row))
`(,domain
,(format "%s=%s" name value)
,expiry)))
(sqlite-select
db
(concat
"SELECT host, name, value, expiry FROM moz_cookies "
"WHERE name = 'overleaf_session2' OR name = 'overleaf.sid'")))
(sqlite-close db))))
;;;###autoload
(cl-defun overleaf-read-cookies-from-firefox (&key (firefox-folder "~/.mozilla/firefox/") (profile nil))
"Make a cookie saving function reading the database at FIREFOX-FOLDER.
To be used with `overleaf-cookies'. The Firefox folder should be
located at `~/.mozilla/firefox/'. If PROFILE is provided, choose this
profile. Otherwise prompt."
(lambda ()
(setopt overleaf-cache-cookies nil)
(if (sqlite-available-p)
(let* ((profile-blocks
(with-temp-buffer
(insert-file-contents (expand-file-name (concat firefox-folder "/profiles.ini")))
(goto-char (point-min))
(let ((matches))
(while (re-search-forward "\\[.*\\]\\(\\(?:.\\|\n\\)+?\\)\\[" (point-max) t)
(backward-char)
(push (match-string 1) matches))
matches)))
(profiles
(remq 'nil
(mapcar (lambda (block)
(save-match-data
(when-let*
((path (and (string-match "^Path=\\(.*?\\)$" block)
(match-string 1 block)))
(name (and (string-match "^Name=\\(.*?\\)$" block)
(match-string 1 block))))
`(:fields (,name) :data ,path))))
profile-blocks)))
(profile (if profile
(plist-get
(seq-find
(lambda (row)
(string= (car (plist-get row :fields)) profile))
profiles)
:data)
(overleaf--completing-read "Profile: " profiles)))
(cookie-file
(if profile
(expand-file-name (concat firefox-folder "/" profile "/cookies.sqlite"))
(user-error "Profile does not exist"))))
(condition-case err
(overleaf--sqlite-select-firefox-overleaf-cookies cookie-file)
(sqlite-error
(condition-case _err
(let* ((temp-dir (make-temp-file "overleaf-firefox-cookies." t))
(temp-cookie-file (expand-file-name "cookies.sqlite" temp-dir))
(cookie-file-wal (concat cookie-file "-wal"))
(temp-cookie-file-wal (concat temp-cookie-file "-wal"))
(cookie-file-shm (concat cookie-file "-shm"))
(temp-cookie-file-shm (concat temp-cookie-file "-shm")))
(unwind-protect
(progn
(copy-file cookie-file temp-cookie-file t t)
(when (file-exists-p cookie-file-wal)
(ignore-errors
(copy-file cookie-file-wal temp-cookie-file-wal t t)))
(when (file-exists-p cookie-file-shm)
(ignore-errors
(copy-file cookie-file-shm temp-cookie-file-shm t t)))
(overleaf--sqlite-select-firefox-overleaf-cookies temp-cookie-file))
(ignore-errors (delete-directory temp-dir t))))
(sqlite-error
(signal 'sqlite-error err))))))
(user-error "Sqlite not available!"))))
(defvar overleaf-save-cookies (lambda (cookies)
(setq overleaf-cookies cookies))
"A function (lambda) that stores the session cookies.
The function receives a string containing the session cookies and stores
in a way that `overleaf-cookies' can access it. The default
implementation simply sets `overleaf-cookies' to the string value.
Another possibility is to store them into a gpg encrypted file. See
`overleaf-save-cookies-to-file'.")
;;;###autoload
(defun overleaf-save-cookies-to-file (file)
"Return a cookie saving function to save the cookie-string to FILE.
To be used with `overleaf-save-cookies'."
(lambda (cookies)
(with-temp-file file
(insert cookies))))
(defcustom overleaf-default-url "https://www.overleaf.com"
"The default url of the overleaf server."
:type 'string)
(defcustom overleaf-flush-interval .5
"The idle-timer delay to flush the edit queue."
:type 'float)
(defcustom overleaf-debug nil
"Whether to log debug messages."
:type 'boolean)
(defcustom overleaf-use-nerdfont nil
"Whether to use nerd-font icons for the modeline."
:type 'boolean)
(defcustom overleaf-context-size 10
"Standard context window size for finding where to re-apply an edit."
:type 'integer)
(defcustom overleaf-cache-cookies t
"Whether to cache the cookies after obtaining them.
This does nothing if `overleaf-read-cookies-from-firefox'
or `overleaf-read-cookies-from-chromium' is used."
:type 'boolean)
(defcustom overleaf-ancestor-location 'local
"Where to store the overleaf ancestor backup files."
:type '(choice (const :tag "Local directory" local)
(const :tag "Centralized (~/.emacs.d/overleaf-ancestors/)" centralized))
:group 'overleaf)
(defcustom overleaf-user-info-template "%n\t%e\t%i"
"The `format-spec' template used in `overleaf-list-users'.
The following specification characters can be used:
%n -- user's name
%e -- user's email address
%i -- user's internal ID
%w -- `which-function' at user's current cursor position
(produces an empty string if `which-function-mode' is not enabled)"
:type 'string
:group 'overleaf-mode)
(defvar-local overleaf-auto-save nil
"Whether to auto-save the buffer each time a change is synced.")
(defvar-local overleaf-project-id nil
"The overleaf project id.
When having a project opened in the browser the URL should read
\"https://[overleaf-domain]/project/[project-id]\".")
(defvar-local overleaf-document-id nil
"The overleaf document id as a string.
The id is most easily obtained by downloading the file that is to be
edited from the overleaf interface. The download URL will then be of the form
\"https://[overleaf-domain]/project/[project-id]/doc/[document-id]\".")
(defvar-local overleaf-track-changes nil
"Whether or not to track changes in overleaf.")
(defvar-local overleaf-url nil
"The url of the overleaf server.")
;;;###autoload
(eval-and-compile
(put 'overleaf-auto-save 'safe-local-variable #'booleanp)
(put 'overleaf-url 'safe-local-variable #'stringp)
(put 'overleaf-track-changes 'safe-local-variable #'booleanp)
(put 'overleaf-project-id 'safe-local-variable #'overleaf-id-p)
(put 'overleaf-document-id 'safe-local-variable #'overleaf-id-p)
;; Do not ignore :propertize forms. See variable `mode-line-format'.
(put 'overleaf--mode-line 'risky-local-variable t))
(defvar-local overleaf--is-overleaf-change nil
"Is set to t if the current change in the buffer comes from overleaf.
Used to inhibit the change detection.")
(defvar-local overleaf--force-close nil
"If t the connection will not be reestablished upon disconnection.")
(defvar-local overleaf--websocket nil
"The websocket instance connected to overleaf.")
(defvar-local overleaf--flush-edit-queue-timer nil
"A timer that flushes the edit queue.
See `overleaf--edit-queue'.")
(defvar-local overleaf--edit-queue '()
"A list of edits that can be send in one go.")
(defvar-local overleaf--edits-in-flight nil
"If non-nil, we still await the acknowledgment from overleaf.")
(defvar-local overleaf--doc-version -2
"Current version of the document.")
(defvar-local overleaf--sequence-id -1
"An internal counter for the websocket communication.")
(defvar-local overleaf--mode-line ""
"Contents of the mode-line indicator.")
(defvar overleaf--ws-url->buffer-table (make-hash-table :test #'equal)
"A hash table associating web-sockets to buffers.")
(defvar overleaf--buffer nil
"The current overleaf buffer (used in lexical binding).")
(defvar-local overleaf--user-id ""
"The public id of the user.")
(defvar-local overleaf--buffer-before-edit-queue ""
"The contents of the buffer before any edits were queued.")
(defvar-local overleaf--last-good-state nil
"The last received overleaf update.")
(defvar-local overleaf--history nil
"An list that relates version numbers to the buffer text at that version.
Should only contain known-good states. Is limited to length
`overleaf-history-buffer-length'.")
(defvar-local overleaf-history-buffer-length 50
"How many past versions of the buffer to keep in memory.")
(defvar-local overleaf--recent-updates nil
"An alist of recent updates received from overleaf.
An alist that contains the `overleaf-update-buffer-length'
recent updates. It has elements of the form `((from-version
. (to-version . update)) ...)'.")
(defvar-local overleaf-update-buffer-length 50
"How many past updates of the buffer to keep in memory.")
(defvar overleaf--current-cookies nil
"The current cookies so we don't have to read them every time.")
(defvar-local overleaf--receiving nil
"When t we are currently in the process of receiving and processing an update.")
(defvar-local overleaf--window-configuration nil
"The window configuration to restore after ediff exits.")
(easy-menu-define overleaf-menu nil
"Overleaf menu."
'("Overleaf"
["Connect" overleaf-connect
:help "Connect to overleaf"]
["Disconnect" overleaf-disconnect
:help "Disconnect from overleaf"]
["Toggle auto save" overleaf-toggle-auto-save
:help "Toggle auto-save on overleaf"]
["Toggle track changes" overleaf-toggle-track-changes
:help "Toggle track-changes on overleaf"]
["Browse project" overleaf-browse-project
:help "Browse project with `browse-url'"
:active overleaf-project-id]
["Goto cursor" overleaf-goto-cursor
:help "Jump to the cursor of another user."
:active (overleaf--other-users-p)]
["List active users" overleaf-list-users
:help "List other active users in an xref buffer"
:active (overleaf--other-users-p)]))
(defvar overleaf--menu-map
(let ((map (make-sparse-keymap)))
(define-key map [mode-line down-mouse-1] overleaf-menu)
map))
(cl-defstruct overleaf--queued-message
"A container that holds a queued message."
edits
doc-version
hash
track-changes
buffer-before
buffer
context)
(cl-defstruct overleaf--update
"An update received from or sent to overleaf.
EDITS are a list of edit operations (inserts and deletes).
FROM-VERSION is the buffer version being edited.
TO-VERSION is the buffer version we hope to reach.
HASH is a hash obtained from `overleaf--get-hash' after the
edit is performed.
BUFFER is the buffer value after applying the update."
edits
from-version
to-version
hash
buffer)
;;;; Macros
(defmacro overleaf--warn (&rest args)
"Print a warning message passing ARGS on to `display-warning'."
`(display-warning 'overleaf (format ,@args)))
(defmacro overleaf--message (string &rest args)
"Print a message with format string STRING and arguments ARGS."
`(message ,(concat "Overleaf: " string) ,@args))
(defmacro overleaf--save-context (&rest body)
"Like `save-excursion' but using text search with context window.
Executes BODY and then tries to reset the point.
The context window size is configured using `overleaf-context-size'."
(let ((pos (gensym))
(context-before (gensym))
(context-after (gensym))
(context (gensym)))
`(let ((,pos (point)))
(cl-destructuring-bind (,context-before ,context-after ,context) (overleaf--extract-context-at-point)
,@body
(save-restriction
(widen)
(goto-char ,pos)
(when (> ,pos 1)
(ignore-errors (backward-char (1+ (length ,context-before)))))
(if (search-forward ,context nil t)
(ignore-errors (backward-char (length ,context-after)))
(if (search-backward ,context nil t)
(ignore-errors (forward-char (length ,context-before)))
(goto-char ,pos))))))))
;;;; Logging
(defsubst overleaf--debug (format-string &rest args)
"Print a debug message with format string FORMAT-STRING and arguments ARGS."
(when overleaf-debug
(if overleaf--buffer
(with-current-buffer overleaf--buffer
(with-current-buffer (get-buffer-create (format "*overleaf-%s*" overleaf-document-id))
(setq buffer-read-only nil)
(goto-char (point-max))
(insert (apply #'format format-string args))
(insert "\n")
(setq buffer-read-only t)))
(apply #'warn format-string args))))
;;;; Communication
(defun overleaf--get-full-cookies ()
"Load the association list domain<->cookies."
(if (and overleaf--current-cookies overleaf-cache-cookies)
overleaf--current-cookies
(condition-case err
(setq overleaf--current-cookies
(if (or (functionp overleaf-cookies)
(fboundp 'overleaf-cookies))
(funcall overleaf-cookies)
overleaf-cookies))
(error
(overleaf--warn "Error while loading cookies: %s" (error-message-string err))
nil))))
(defun overleaf--get-cookies ()
"Load the cookies from `overleaf-cookies'."
(if-let*
((cookies
(cl-some (lambda (prefix)
(alist-get (concat prefix (overleaf--cookie-domain))
(overleaf--get-full-cookies)
nil nil #'string=))
'("." "")))
(now (time-convert nil 'integer))) ; Current unix time in seconds.
(pcase-let ((`(,value ,validity) cookies))
(if (or (not validity) (< now validity))
value
(setq overleaf--current-cookies nil)
(user-error "Cookies for %s are expired. Please refresh them using `overleaf-authenticate' or manually"
(overleaf--cookie-domain))))
(setq overleaf--current-cookies nil)
(user-error "Cookies for %s are not set. Please set them using `overleaf-authenticate' or manually"
(overleaf--cookie-domain))))
(defun overleaf--connected-p ()
"Return t if the buffer is connected to overleaf."
(and overleaf--websocket
(websocket-openp overleaf--websocket)
(>= overleaf--doc-version -1)))
(defun overleaf--on-open (websocket)
"Handle the open even of the web-socket WEBSOCKET."
(let ((overleaf--buffer
(gethash (websocket-url websocket) overleaf--ws-url->buffer-table)))
(with-current-buffer overleaf--buffer
(overleaf--update-modeline)
(add-hook 'after-change-functions #'overleaf--after-change-function nil :local)
(add-hook 'before-change-functions #'overleaf--before-change-function nil :local)
(add-hook 'kill-buffer-hook #'overleaf-disconnect nil :local)
(setq-local
overleaf--flush-edit-queue-timer
(progn
(when overleaf--flush-edit-queue-timer
(cancel-timer overleaf--flush-edit-queue-timer))
(run-with-idle-timer overleaf-flush-interval t
(lambda (buffer)
(with-current-buffer buffer
(unless overleaf--receiving
(overleaf--flush-edit-queue buffer))))
overleaf--buffer))))))
(defun overleaf--on-message (ws frame)
"Handle a message received from websocket WS with contents FRAME."
(let ((overleaf--buffer
(gethash (websocket-url ws) overleaf--ws-url->buffer-table)))
(overleaf--debug "Got message %S" frame)
(overleaf--parse-message ws (websocket-frame-text frame))))
(defun overleaf--on-close (ws)
"Handle the closure of the websocket WS."
(let ((overleaf--buffer
(gethash (websocket-url ws) overleaf--ws-url->buffer-table)))
(when overleaf--buffer
(with-current-buffer overleaf--buffer
(when overleaf--websocket
(overleaf--message "Websocket for document %s closed." overleaf-document-id)
(setq-local buffer-read-only nil)
(cancel-timer overleaf--flush-edit-queue-timer)
(remhash (websocket-url ws) overleaf--ws-url->buffer-table)
(setq-local overleaf--websocket nil)
(overleaf--update-modeline)
(unless overleaf--force-close
(with-current-buffer overleaf--buffer
(setq buffer-read-only t)
(sleep-for .1)
(setq overleaf--websocket nil)
(overleaf-connect))))))))
(defun overleaf--sync-surgically (source-buf target-buf)
"Surgically sync TARGET-BUF to SOURCE-BUF using hunk-by-hunk application."
(save-excursion
(save-window-excursion
(let ((diff-buf (let ((inhibit-message t))
(diff-no-select target-buf source-buf "-u -U0" t))))
(when (buffer-live-p diff-buf)
(unwind-protect
(with-current-buffer diff-buf
(goto-char (point-min))
(while (re-search-forward "^@@" nil t)
(beginning-of-line)
(let ((diff-jump-to-old-file t)
(inhibit-read-only t)
(inhibit-message t))
(cl-letf* (((symbol-function 'diff-find-file-definition)
(lambda (&rest _) target-buf))
((symbol-function 'read-file-name)
(lambda (&rest _) (buffer-name target-buf)))
((symbol-function 'completing-read)
(lambda (&rest _) (buffer-name target-buf))))
(diff-apply-hunk)))))
(kill-buffer diff-buf)))))))
(defun overleaf--handle-pong (ws)
"Respond to a heart-beat message from WS."
(websocket-send-text ws "2::"))
(defun overleaf--handle-initial-load (ws message)
"Handle the initial document load message (ID 6)."
(save-match-data
(when-let* ((doc (progn
(string-match "null,\\(\\[.*?\\]\\),\\([0-9]+\\)" message)
(match-string 1 message)))
(version (1- (string-to-number (match-string 2 message))))
(overleaf--is-overleaf-change t))
(when doc
(let ((hash (and (not (buffer-modified-p))
(save-restriction (widen) (buffer-hash)))))
(setq-local buffer-read-only nil)
(let* ((server-text (overleaf--decode-utf8 (string-join (json-parse-string doc) "\n")))
(local-text (save-restriction
(widen)
(buffer-substring-no-properties (point-min) (point-max)))))
(overleaf--reset-buffer-to server-text)
(when (not (string= local-text server-text))
(run-with-timer
0 nil
(lambda (buf local)
(when (buffer-live-p buf)
(with-current-buffer buf
(when (y-or-n-p "Resolve conflicts with ediff? ")
(let* ((local-buffer (generate-new-buffer "*overleaf-local*"))
(ancestor-file (overleaf--ancestor-file))
(has-ancestor (and ancestor-file (file-exists-p ancestor-file))))
(setq overleaf--window-configuration (current-window-configuration))
(with-current-buffer local-buffer
(insert local)
(set-buffer-modified-p nil))
(if has-ancestor
(let* ((ancestor-buffer (generate-new-buffer "*overleaf-ancestor*"))
(server-buffer (generate-new-buffer "*overleaf-server*"))
(target-buf buf)
(coding (with-current-buffer target-buf buffer-file-coding-system))
(server-text (with-current-buffer target-buf (buffer-string))))
(with-current-buffer ancestor-buffer
(insert-file-contents ancestor-file)
(set-buffer-file-coding-system coding)
(set-buffer-modified-p nil))
(with-current-buffer server-buffer
(insert server-text)
(set-buffer-file-coding-system coding)
(set-buffer-modified-p nil))
(with-current-buffer local-buffer
(set-buffer-file-coding-system coding))
(ediff-merge-buffers-with-ancestor
local-buffer server-buffer ancestor-buffer
(list (lambda ()
(let ((res-buf ediff-buffer-C)
(target target-buf)
(a-buf ediff-buffer-A)
(b-buf ediff-buffer-B)
(anc-buf ediff-ancestor-buffer))
(let ((sync-fn (lambda ()
(when (and (buffer-live-p res-buf)
(buffer-live-p target))
(overleaf--sync-surgically res-buf target)))))
(add-hook 'ediff-select-hook sync-fn nil t)
(add-hook 'ediff-after-merge-hook sync-fn nil t)
(add-hook 'ediff-quit-hook
(lambda ()
(funcall sync-fn)
(with-current-buffer target
(overleaf--save-ancestor))
(when (buffer-live-p a-buf) (kill-buffer a-buf))
(when (buffer-live-p b-buf) (kill-buffer b-buf))
(when (buffer-live-p anc-buf) (kill-buffer anc-buf))
(when (buffer-live-p res-buf) (kill-buffer res-buf))
(when overleaf--window-configuration
(set-window-configuration overleaf--window-configuration)))
nil t)
(funcall sync-fn)))))))
(let ((ctl-buf (ediff-buffers local-buffer buf)))
(with-current-buffer ctl-buf
(setq-local ediff-keep-variants t)
(add-hook 'ediff-quit-hook
(lambda ()
(setq ediff-buffer-B nil) ; Protect main buffer
(when (buffer-live-p ediff-buffer-A)
(kill-buffer ediff-buffer-A))
(when overleaf--window-configuration
(set-window-configuration overleaf--window-configuration)))
nil t)))))))))
(current-buffer) local-text)))
(setq buffer-undo-list nil)
(overleaf--set-version version)
(overleaf--push-to-history version)
;; Copied from `fill-paragraph':
;; If we didn't change anything in the buffer (and the buffer
;; was previously unmodified), then flip the modification status
;; back to "unchanged".
(when (and hash
(equal hash (save-restriction (widen) (buffer-hash))))
(set-buffer-modified-p nil))))
(run-with-idle-timer
1 nil
(lambda (buffer)
(with-current-buffer buffer
(overleaf--write-buffer-variables)))
overleaf--buffer)
(overleaf--update-modeline))))
(defun overleaf--handle-event (ws id message-raw)
"Handle event messages with JSON payload (ID 5)."
(when message-raw
(when-let* ((message (json-parse-string message-raw :object-type 'plist :array-type 'list))
(name (plist-get message :name)))
(pcase name
("clientTracking.clientUpdated"
(let ((args (car (plist-get message :args))))
(overleaf--update-cursor
(plist-get args :id)
(plist-get args :name)
(plist-get args :email)
(plist-get args :row)
(plist-get args :column))))
("clientTracking.clientDisconnected"
(let ((id (car (plist-get message :args))))
(overleaf--remove-cursor id)))
("connectionRejected"
(overleaf--warn "Connection error: %S" (plist-get message :args))
(overleaf-disconnect))
("otUpdateError"
(overleaf--debug "-------- Update ERROR")
(overleaf--warn "Update error %S" (car (plist-get message :args)))
(overleaf-connect))
("joinProjectResponse"
(setq-local overleaf--user-id
(plist-get
(car (plist-get message :args))
:publicId))
(unwind-protect
(unless overleaf-document-id
(let* ((root
(overleaf--pget
(car (plist-get message :args))
:project
:rootFolder 0))
(collection
(overleaf--get-files root)))
(setq-local overleaf-document-id
(overleaf--completing-read
"Select file: "
collection))))
(if overleaf-document-id
(websocket-send-text ws (format "5:2+::{\"name\":\"joinDoc\",\"args\":[\"%s\",{\"encodeRanges\":true}]}" overleaf-document-id))
(overleaf--warn "Invalid document id %S" overleaf-document-id)
(overleaf-disconnect))))
("serverPing"
(overleaf--debug "Received Ping -> PONG")
(let ((res (concat id ":::" (json-encode `(:name "clientPong" :args ,(plist-get message :args))))))
(websocket-send-text ws res)))
("otUpdateApplied"
(let ((last-version (plist-get (car (plist-get message :args)) :lastV))
(version (plist-get (car (plist-get message :args)) :v))
(hash (plist-get (car (plist-get message :args)) :hash))
(overleaf--is-overleaf-change t)
(edits (when (plist-get message :args) (plist-get (car (plist-get message :args)) :op))))
(overleaf--debug "%S Got update with version %s->%s (buffer version %s) %S" (buffer-name) last-version version overleaf--doc-version message)
(overleaf--apply-changes edits version last-version hash))
(overleaf--send-position-update))))))
(defun overleaf--parse-message (ws message)
"Parse a message MESSAGE from overleaf, responding by writing to WS."
(with-current-buffer overleaf--buffer
(setq-local overleaf--receiving t)
(unwind-protect
(pcase-let ((`(,id ,message-raw) (string-split message ":::")))
(pcase id
("2::" (overleaf--handle-pong ws))
("6" (overleaf--handle-initial-load ws message))
("5" (overleaf--handle-event ws id message-raw))))
(setq-local overleaf--receiving nil))))
(defun overleaf--get-files (folder &optional parent)
"Recursively parse overleafs FOLDER structure to list all documents.
Optionally a PARENT prefix string may be provided."
(let* ((docs
(plist-get folder :docs))
(folders
(plist-get folder :folders))
(name (let ((tmpname (plist-get folder :name)))
(if (string= tmpname "rootFolder")
""
tmpname)))
(parent (concat (or parent "") name "/")))
(apply #'nconc
(mapcar
(lambda (file)
`(:fields (,(concat parent (plist-get file :name))) :data ,(plist-get file :_id)))
docs)
(mapcar
(lambda (folder)
(overleaf--get-files folder parent))
folders))))
(defun overleaf--get-hash ()
"Get the hash of the overleaf buffer."
(with-current-buffer overleaf--buffer
(let ((buff (overleaf--buffer-string)))
(secure-hash 'sha1 (format "blob %i\x00%s" (length buff) buff)))))
(defun overleaf--push-to-history (version &optional buffer-string)
"Push the buffer to the version history.
Push the contents of the buffer or BUFFER-STRING of VERSION to the local
overleaf version history."
(when (and version overleaf--buffer)
(with-current-buffer overleaf--buffer
(setq-local overleaf--history
(overleaf--splice-into overleaf--history version
(or buffer-string (overleaf--buffer-string)) t))
(setq-local overleaf--history
(overleaf--truncate
overleaf--history
overleaf-history-buffer-length))
(when overleaf-auto-save
(save-buffer)))))
(defun overleaf--push-to-recent-updates (update)
"Splice the UPDATE of type `overleaf--update' into `overleaf--recent-updates'."
(let ((from-version (overleaf--update-from-version update))
(to-version (overleaf--update-to-version update)))
(when (and from-version to-version overleaf--buffer)
(with-current-buffer overleaf--buffer
(setq-local overleaf--recent-updates
(overleaf--splice-into
overleaf--recent-updates from-version (cons to-version update)
t))
(setq-local overleaf--recent-updates
(overleaf--truncate
overleaf--recent-updates overleaf-update-buffer-length))))))
(defun overleaf--send-position-update ()
"Send a position tracking update to overleaf."
(with-current-buffer overleaf--buffer
(when (overleaf--connected-p)
(save-restriction
(widen)
(websocket-send-text
overleaf--websocket
(format
"5:::{\"name\":\"clientTracking.updatePosition\",\"args\":[{\"row\":%i,\"column\":%i,\"doc_id\":\"%s\"}]}"
(1- (line-number-at-pos)) (- (point) (line-beginning-position)) overleaf-document-id))))))
(defun overleaf--apply-changes-internal (edits)
"Parse the edit list EDITS and apply them to the buffer.
Returns the edits as applied. This is required because deletions might
no longer be possible, or will occur at a different location. If CONTEXT
is provided use the context to fine tune where the edit is applied."
(let ((overleaf--is-overleaf-change t)
(new-edits nil))
(save-restriction
(widen)
(dolist (op edits)
(let ((pos (1+ (plist-get op :p))))
(goto-char pos)
(if-let* ((insert (plist-get op :i)))
(progn
(insert insert)
(setq buffer-undo-list (memq nil buffer-undo-list))
(push `(:p ,(1- pos) :i ,insert) new-edits))
(if-let* ((delete (plist-get op :d)))
(save-match-data
(if (re-search-forward (regexp-quote delete) nil t)
(progn
(let ((delete-loc (1- (- (point) (length delete)))))
(replace-match "")
(setq buffer-undo-list (memq nil buffer-undo-list))
(push `(:p ,delete-loc :d ,delete) new-edits)))
(setq edits nil))))))))
(nreverse new-edits)))
(defun overleaf--verify-buffer (hash)
"Verify that the current buffer has the hash HASH.
Re-connect if this is not the case."
(overleaf--debug "Verify")
(when (and hash
(not (string= (overleaf--get-hash) hash)))
(overleaf--debug "%s" (overleaf--buffer-string))
(overleaf--warn "Hash mismatch... reconnecting")
(setq-local buffer-read-only t)
(overleaf-connect)))
(defun overleaf--transform-edits (edits history-edits)
"Transform EDITS to new positions by HISTORY-EDITS that came after the EDITS."
(dolist (history-op history-edits)
(setq edits
(mapcar
(lambda (op)
(let ((history-position (plist-get history-op :p))
(position (plist-get op :p)))
(if (<= history-position position)
(progn
(overleaf--debug "--------> updating: history: %S this: %S" history-op op)
(plist-put
op :p
(+ position (let* ((insert (plist-get history-op :i))
(delete (plist-get history-op :d)))
(+ (if insert (length insert) 0)
(if delete (* -1 (length delete)) 0))))))
op)))
edits)))
edits)
(defun overleaf--apply-changes (edits version last-version hash)
"Apply change EDITS from version LAST-VERSION to VERSION to have the hash HASH.
If there are some updates to the buffer that haven't yet been
acknowledged by overleaf or even haven't yet been sent we have to replay
them on top of the changes received from overleaf in the meantime."
(overleaf--debug "VERSION: %S -> %S Current: %S Edits: %S In flight: %S" last-version version overleaf--doc-version edits overleaf--edits-in-flight)
(overleaf-queue-pending-edit)
(let ((overleaf--is-overleaf-change t))
(if (and overleaf--edits-in-flight (not edits))
(progn
(let ((update (car overleaf--edits-in-flight)))
(overleaf--debug "%S BINGO, we've been waiting for this. %S %S" (buffer-name) (overleaf--update-to-version update) version)
(setf (overleaf--update-to-version update) version)
(overleaf--push-to-recent-updates
update)
(overleaf--push-to-history version (overleaf--buffer-string))
(setf (overleaf--update-to-version update) version)
(setf (overleaf--update-from-version update) (1- version))
(overleaf--push-to-recent-updates update)
(overleaf--set-version version))
(setq overleaf--edits-in-flight (cdr overleaf--edits-in-flight)))
(when edits
(overleaf--save-context
(with-current-buffer overleaf--buffer
(when overleaf--edit-queue
(overleaf--debug "-------------> RESET")
(overleaf--reset-buffer-to overleaf--buffer-before-edit-queue))
(when overleaf--edits-in-flight
(overleaf--reset-buffer-to (overleaf--update-buffer (car overleaf--edits-in-flight))))
(overleaf--apply-changes-internal edits)
(overleaf--set-version version)
(when (and hash (not overleaf--edits-in-flight)) (overleaf--verify-buffer hash))
(overleaf--push-to-history version)
(overleaf--push-to-recent-updates
(make-overleaf--update
:edits edits
:from-version (1- version) ;; we updated it so that there's no jump
:to-version version
:edits edits
:buffer ""))
(if overleaf--edit-queue
(progn
(when edits
(setq overleaf--edit-queue (overleaf--transform-edits overleaf--edit-queue edits)))
(setq overleaf--buffer-before-edit-queue (overleaf--buffer-string))
(setq overleaf--edit-queue (overleaf--apply-changes-internal overleaf--edit-queue)))
(overleaf--reset-edit-queue))))))
(overleaf--update-modeline)))
;;;; Misc
;;;###autoload
(defun overleaf-id-p (id)
"Return t if ID is an overleaf project/document id."
(string-match-p "^[a-z0-9]+$" (format "%s" id)))
(defun overleaf--pget (plist &rest keys)
"Recursively find KEYS in PLIST."
(while keys
(let ((key (pop keys)))
(if (integerp key)
(setq plist (nth key plist))
(setq plist (plist-get plist key)))))
plist)
(defun overleaf--completing-read (prompt collection &optional padding)
"Perform a completing read with PROMPT.
The COLLECTION contains row of the form `(:fields ([string 1] \...)
:data [data] [optional: :propertize [arguments to propeRTIZE-string]] )'
where the fields are displayed as columns of the table separated by
PADDING (2 characters by default)."
(let* ((num-fields (1- (length (plist-get (car collection) :fields))))
(padding (or padding 2))
(field-widths
(mapcar
(lambda (field)
(apply #'max
(mapcar
(lambda (row)
(length (nth field (plist-get row :fields))))
collection)))
(number-sequence 0 num-fields)))
(format-string
(apply #'concat
(mapcar (lambda (width)
(format "%%-%is" (+ padding width)))
field-widths)))
(final-collection
(cl-loop for row in collection
collect `(,(let ((str (apply #'format format-string (plist-get row :fields))))
(if-let* ((args (plist-get row :propertize)))
(apply #'propertize str args)
str))
,(plist-get row :data)))))
(car (cdr
(assoc
(completing-read prompt
final-collection
nil t)
final-collection)))))
(defun overleaf--set-version (vers)
"Set the buffer version to VERS."
(overleaf--debug "Setting buffer version to %s" vers)
(setq-local overleaf--doc-version vers))
(defun overleaf--write-buffer-variables ()
"Write the current buffer-local variables to the buffer."
(when (overleaf--connected-p)
(let ((overleaf--is-overleaf-change nil)
(track-changes overleaf-track-changes))
(save-excursion