-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathess-view-data.el
2274 lines (1958 loc) · 89.6 KB
/
ess-view-data.el
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
;;; ess-view-data.el --- View Data -*- lexical-binding: t; -*-
;; Copyright (C) 2019-2023 Shuguang Sun <shuguang79@qq.com>
;; Author: Shuguang Sun <shuguang79@qq.com>
;; Created: 2019/04/06
;; Version: 1.3
;; URL: https://github.com/ShuguangSun/ess-view-data
;; Package-Requires: ((emacs "26.1") (ess "18.10.1") (csv-mode "1.12"))
;; Keywords: tools
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Customization:
;; ess-view-data-backend-list: dplyr (default), dplyr+DT, data.table+magrittr
;; ess-view-data-print-backend-list: print (default), kable
;; ess-view-data-save-backend-list: write.csv (default), readr::write_csv,
;; data.table::fwrite kable
;; ess-view-data-complete-backend-list: jsonlite
;; ess-view-data-read-string: ess-completing-read (default), completing-read,
;; ido-completing-read, ivy-completing-read
;; Utils:
;; NOTE: it will make a copy of the data and then does the following action
;; ess-view-data-print: the main function to view data
;; Example: In a ess-r buffer or a Rscript buffer, `M-x ess-view-data-print`
;; and input `mtcars`.
;; ess-view-data-set-backend: change backend
;; ess-view-data-toggle-maxprint: toggle limitation of lines per page to print
;; ess-view-data-verbs
;; Example: In the ESS-V buffer, `M-x ess-view-data-verbs` and select the verb
;; to do with.
;; ess-view-data-filter
;; Example: In the ESS-V buffer, `M-x ess-view-data-filter`, `cyl <RET> mpg` to
;; select columns and <C-j> to finish input. An indirect buffer pops up and
;; 'data-masking' Expressions can be edited.
;; ess-view-data-select / ess-view-data-unselect
;; Example: In the ESS-V buffer, `M-x ess-view-data-select`, `cyl <RET> mpg` to
;; select columns and <C-j> to finish input.
;; ess-view-data-sort
;; ess-view-data-group / ess-view-data-ungroup
;; ess-view-data-mutate
;; ess-view-data-slice
;; ess-view-data-wide2long / ess-view-data-long2wide
;; ess-view-data-update
;; ess-view-data-reset
;; Example: In the ESS-V buffer, `M-x ess-view-data-reset`, an indirect buffer
;; pops up and the action history can be edited.
;; ess-view-data-unique
;; ess-view-data-count
;; Example: In the ESS-V buffer, `M-x ess-view-data-count`, `cyl <RET> mpg` to
;; select columns and <C-j> to finish input. In the updated buffer with count
;; information, `M-x ess-view-data-print` to go back.
;; ess-view-data-summarise
;; ess-view-data-overview
;; ess-view-data-goto-page / -next-page / -previous-page / -first-page /
;; -last-page / -page-number
;; ess-view-data-save
;;; Code:
;; (require 'eieio)
(eval-when-compile (require 'cl-lib))
(eval-when-compile (require 'cl-generic))
(require 'ess-inf)
(require 'ess-rdired)
(require 'ess-r-mode)
(require 'ess-r-completion)
(require 'subr-x)
(require 'json)
(defgroup ess-view-data ()
"ess-view-dat"
:group 'ess
:prefix "ess-view-data-")
(defcustom ess-view-data-buffer-name-format "*R Data View: %1$s (%2$s)*"
"Buffer name for R data, with two parameter: variable name, proc-name."
:type 'string
:group 'ess-view-data)
(defcustom ess-view-data-source-buffer-name-format "*R Data View Edit: %s*"
"Buffer for R data."
:type 'string
:group 'ess-view-data)
;; FIXME: r symbol name
(defcustom ess-view-data-objname-regex "^[^a-zA-Z]\\|[^.a-zA-Z0-9]+"
"Object name needs to be back quoted."
:type 'string
:group 'ess-view-data)
(defcustom ess-view-data-options-width 5000
"Width to print data: options(width= `ess-view-data-options-width')."
:type 'integer
:group 'ess-view-data)
(defcustom ess-view-data-rows-per-page 200
"Rows per page."
:type 'integer
:group 'ess-view-data)
(defcustom ess-view-data-show-code t
"Show code on top of the view data buffer."
:type 'boolean
:group 'ess-view-data)
(defcustom ess-view-data-show-no-page-number t
"Not to show page number on top of the view data buffer."
:type 'boolean
:group 'ess-view-data)
(defcustom ess-view-data-write-dribble t
"Write to dribble for tracking."
:type 'boolean
:group 'ess-view-data)
(defcustom ess-view-data-tibble-crayon-enabled-p nil
"Whether to enable crayon for tibble.
If enabled, `ansi-color-for-comint-mode-on' should be turn on."
:type 'boolean
:group 'ess-view-data)
(defvar ess-view-data-backend-list
(list 'dplyr 'dplyr+DT 'data.table+magrittr)
"List of backends.")
(defcustom ess-view-data-current-backend 'dplyr
"The ess-view-data backend in using."
:type `(choice ,@(mapcar (lambda (x)
`(const :tag ,(symbol-name x) ,x))
ess-view-data-backend-list)
(symbol :tag "Other"))
:group 'ess-view-data)
(defvar ess-view-data-print-backend-list
(list 'print 'kable)
"List of backends.")
(defcustom ess-view-data-current-update-print-backend 'print
"The ess-view-data backend in using."
:type `(choice ,@(mapcar (lambda (x)
`(const :tag ,(symbol-name x) ,x))
ess-view-data-print-backend-list)
(symbol :tag "Other"))
:group 'ess-view-data)
(defcustom ess-view-data-current-summarize-print-backend 'kable
"The ess-view-data backend in using."
:type `(choice ,@(mapcar (lambda (x)
`(const :tag ,(symbol-name x) ,x))
ess-view-data-print-backend-list)
(symbol :tag "Other"))
:group 'ess-view-data)
(defvar ess-view-data-save-backend-list
(list 'write.csv 'readr::write_csv 'data.table::fwrite 'kable)
"List of backends for write data to csv.")
(defcustom ess-view-data-current-save-backend 'write.csv
"The backend to save data."
:type `(choice ,@(mapcar (lambda (x)
`(const :tag ,(symbol-name x) ,x))
ess-view-data-save-backend-list)
(symbol :tag "Other"))
:group 'ess-view-data)
(defvar ess-view-data-complete-backend-list
(list 'jsonlite)
"List of backends to read completion list.")
(defcustom ess-view-data-current-complete-backend 'jsonlite
"The backend to save data."
:type `(choice ,@(mapcar (lambda (x)
`(const :tag ,(symbol-name x) ,x))
ess-view-data-complete-backend-list)
(symbol :tag "Other"))
:group 'ess-view-data)
(defcustom ess-view-data-read-string 'ess-completing-read
"The function used to completing read."
:type `(choice (const :tag "ESS" ess-completing-read)
(const :tag "basic" completing-read)
(const :tag "ido" ido-completing-read)
(const :tag "ivy" ivy-completing-read)
(function :tag "Other"))
:group 'ess-view-data)
;; TODO: configure input functions here
(defvar ess-view-data-backend-setting
'((dplyr . (:desc "desc(%s)" :slice "pos, like 1, 1:5, n(): "))
(dplyr+DT . (:desc "desc(%s)" :slice "pos, like 1, 1:5, n(): "))
(data.table+magrittr . (:desc "-%s" :slice "pos, like 1, 1:5, .N: ")))
"List of backends.")
(defvar ess-view-data-verb-update-list
(list "select" "unselect" "sort" "group" "ungroup" "slice")
"List of verbs which can change the data.")
(defvar ess-view-data-verb-update-indirect-list
(list "filter" "mutate" "transmute"
"wide2long" "long2wide" "wide2long-pivot_longer" "long2wide-pivot_wider")
"List of verbs which can change the data.")
(defvar ess-view-data-verb-summarise-list
(list "count" "unique" "slice" "summarise" "skimr" "skimr-all")
"List of verbs which do summarise.")
(defvar ess-view-data-verb-summarise-indirect-list
(list "count" "unique" "slice" "summarise")
"List of verbs which do summarise.")
(defvar-local ess-view-data-object nil
"Cache of object name.")
(defvar-local ess-view-data-temp-object nil
"Temporary variable for ess-view-data.")
(defvar ess-view-data-temp-object-list '()
"List of temporary variable for ess-view-data.")
(defvar-local ess-view-data-maxprint-p nil
"Whether to print all data in one page.")
(defvar-local ess-view-data-page-number 0
"Current page number - 1.")
(defvar-local ess-view-data-total-page 1
"Total page number.")
(defvar-local ess-view-data-history nil
"The history of operations.")
(defvar-local ess-view-data-completion-object nil
"The candidate for completion.")
(defvar-local ess-view-data-completion-candidate nil
"The candidate for completion.")
(defvar ess-view-data-mode-map
(let ((keymap (make-sparse-keymap)))
(define-key keymap (kbd "C-c C-p") #'ess-view-data-print-ex)
(define-key keymap (kbd "C-c C-t") #'ess-view-data-toggle-maxprint)
(define-key keymap (kbd "C-c C-s") #'ess-view-data-select)
(define-key keymap (kbd "C-c C-u") #'ess-view-data-unselect)
(define-key keymap (kbd "C-c C-f") #'ess-view-data-filter)
(define-key keymap (kbd "C-c C-o") #'ess-view-data-sort)
;; (define-key keymap (kbd "C-c C-g") #'ess-view-data-group)
;; (define-key keymap (kbd "C-c C-G") #'ess-view-data-ungroup)
(define-key keymap (kbd "C-c C-i") #'ess-view-data-slice)
(define-key keymap (kbd "C-c C-l") #'ess-view-data-unique)
(define-key keymap (kbd "C-c C-v") #'ess-view-data-summarise)
(define-key keymap (kbd "C-c C-r") #'ess-view-data-reset)
(define-key keymap (kbd "C-c C-w") #'ess-view-data-save)
(define-key keymap (kbd "M-g p") #'ess-view-data-goto-previous-page)
(define-key keymap (kbd "M-g n") #'ess-view-data-goto-next-page)
(define-key keymap (kbd "M-g f") #'ess-view-data-goto-first-page)
(define-key keymap (kbd "M-g l") #'ess-view-data-goto-last-page)
keymap)
"Keymap for function `ess-view-data-mode'.")
;;; Indirect Buffers Minor Mode
(defvar ess-view-data-edit-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c'" #'ess-view-data-do-commit)
(define-key map "\C-c\C-k" #'ess-view-data-commit-abort)
(define-key map "\C-c\C-i" #'ess-view-data-complete-object)
(define-key map "\C-c\C-l" #'ess-view-data-complete-data)
(define-key map "\C-c\C-a" #'ess-view-data-insert-all-cols)
(define-key map "\C-c\C-v" #'ess-view-data-insert-all-values)
map)
"Keymap for `ess-view-data-edit-mode', a minor mode.")
(defvar ess-view-data-edit-mode-hook nil
"Hook for the `ess-view-data-edit-mode' minor mode.")
(define-minor-mode ess-view-data-edit-mode
"Minor mode for special key bindings in a ess-view-data-edit buffer.
Turning on this mode runs the normal hook `ess-view-data-edit-mode-hook'."
:lighter " Evd"
(setq-local
header-line-format
(substitute-command-keys
"Edit, then exit with `\\[ess-view-data-do-commit] '' or abort with `\\[ess-view-data-commit-abort]'")))
;;; Utils
;;; Backend Access API
(cl-defgeneric ess-view-data--do-print (backend str)
"Benchmark function to do print.
Argument BACKEND Backend to dispatch, i.e.,
the `ess-view-data-current-update-print-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--do-update (backend str)
"Do Update.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--do-summarise (backend str)
"Do summarising.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--create-indirect-buffer (backend str)
"Create indirect-buffer for editing.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--do-reset (backend str)
"Reset print buffer.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data-do-save (backend str)
"Save.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data-do-complete-data (backend str)
"Completing input.
Argument BACKEND Backend to dispatch, i.e.,
the `ess-view-data-current-complete-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data-get-total-page (backend str)
"Total number of pages.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--header-line (backend str)
"Head-line.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
(cl-defgeneric ess-view-data--initialize-backend (_backend)
"Initialization."
nil)
(cl-defgeneric ess-view-data-do-kill-buffer-hook (backend str)
"Functions to run after `kill-buffer' on '*R Data View' buffer.
Argument BACKEND Backend to dispatch, i.e., the `ess-view-data-current-backend'.
Argument STR R script to run.")
;;; * print-backend: print
(defvar ess-view-data--print-format
(concat
(format
(concat
"op.tmp <- options(\"width\", \"tibble.width\", \"crayon.enabled\");"
"options(tibble.width = Inf, width = %d, crayon.enabled = FALSE);")
ess-view-data-options-width)
"print(%s, n = nrow(%s));"
"options(op.tmp)")
"Format string for print.")
(defvar ess-view-data--print-format-with-crayon
(concat
(format
(concat
"op.tmp <- options(\"width\", \"tibble.width\", \"crayon.enabled\");"
"options(tibble.width = Inf, width = %d, crayon.enabled = TRUE);")
ess-view-data-options-width)
"print(%s, n = nrow(%s));"
"options(op.tmp)")
"Format string for print, with crayon.enabled for tibble.")
(cl-defmethod ess-view-data--do-print ((_backend (eql print)))
"Do print using print."
(if ess-view-data-tibble-crayon-enabled-p
ess-view-data--print-format-with-crayon
ess-view-data--print-format))
;;; * kable-backend: kable
(defvar ess-view-data--kable-format
(concat
(format
(concat
"op.tmp <- options(\"width\", \"tibble.width\", \"crayon.enabled\");"
"options(tibble.width = Inf, width = %d, crayon.enabled = FALSE);")
ess-view-data-options-width)
"print(knitr::kable(%s, n = nrow(%s)));"
"options(op.tmp)")
"Format string for kable.")
(cl-defmethod ess-view-data--do-print ((_backend (eql kable)))
"Do print using kable."
ess-view-data--kable-format)
;;; * backend: dplyr
;;; ** Initialization
(cl-defmethod ess-view-data--initialize-backend ((_backend (eql dplyr)) proc-name proc)
"Initialization.
Initializing the history of operations, make temp object.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(let ((obj-space-p (string-match-p ess-view-data-objname-regex ess-view-data-object))
(obj-back-quote-p (string-match-p "`" ess-view-data-object))
(obj-back-quote (replace-regexp-in-string "`" "" ess-view-data-object)))
(unless ess-view-data-history
(setq ess-view-data-history
(format (cond (obj-back-quote-p "as_tibble(%s)")
(obj-space-p "as_tibble(`%s`)")
(t "as_tibble(%s)"))
ess-view-data-object)))
;; Initializing the temporary object, for stepwise
(unless ess-view-data-temp-object
(setq ess-view-data-temp-object
(format (cond (obj-back-quote-p "`%s`")
(obj-space-p "`%s`")
(t "`%s`"))
(make-temp-name obj-back-quote)))
(when (and proc-name proc
(not (process-get proc 'busy)))
(ess-command (concat "{suppressPackageStartupMessages(require(dplyr)); "
;; ess-command using local 2021-12-04
ess-view-data-temp-object " <<- as_tibble("
(format (cond (obj-back-quote-p "`%s`")
(obj-space-p "`%s`")
(t "`%s`"))
obj-back-quote)
")}\n")
nil nil nil nil proc))))
(cl-pushnew ess-view-data-temp-object ess-view-data-temp-object-list)
(delete-dups ess-view-data-temp-object-list))
;; (defvar csv--header-line)
(defvar-local csv--header-line nil)
(declare-function csv-header-line "csv-mode")
(cl-defmethod ess-view-data--header-line ((_backend (eql dplyr)))
"Make header-line for dplyr."
(goto-char (point-min))
;; (if (looking-at "# A tibble:")
;; (delete-region (point-min) (1+ (line-end-position))))
(let ((lin 1))
(while ;; (looking-at-p "^\\(+\\|#\\)")
(search-forward-regexp "^\\([+]\\|#\\|[[].+?#\\)" nil t)
(forward-line)
(setq lin (1+ lin)))
(unless (fboundp 'csv-header-line) (require 'csv-mode nil t))
(when (fboundp 'csv-header-line)
(setq csv--header-line nil)
(with-no-warnings (csv-header-line lin))))
(goto-char (point-min)))
(cl-defmethod ess-view-data-get-total-page ((_backend (eql dplyr)) proc-name proc)
"Get total number of pages of the current object (data.frame/tibble/data.table).
If `ess-view-data-maxprint-p' is nil, it will show 100 rows/lines
per page for dplyr+print/kable.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(when (and proc-name proc
(not (process-get proc 'busy)))
(setq ess-view-data-total-page
(string-to-number
(car (ess-get-words-from-vector
(format "as.character(nrow(%s))\n" ess-view-data-temp-object)))))
(setq ess-view-data-total-page
(1+ (floor (/ ess-view-data-total-page ess-view-data-rows-per-page))))))
(cl-defmethod ess-view-data-do-kill-buffer-hook ((_backend (eql dplyr)) proc-name proc)
"Functions to run after `kill-buffer' on '*R Data View' buffer.
The default is to rm the temporary object.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(when (and proc-name proc
(not (process-get proc 'busy)))
(ess-command (format "rm(%s, envir = globalenv())\n" ess-view-data-temp-object))
(ess-write-to-dribble-buffer (format "[ESS-v] rm(%s, envir = globalenv())\n" ess-view-data-temp-object))))
;;; ** Utilities
(cl-defmethod ess-view-data--do-update ((_backend (eql dplyr)) fun action)
"Update the data frame by dplyr stepwisely.
Optional argument FUN What to do with the data, e.g.,
verb like select, filter, and etc..
Optional argument ACTION Parameter (R script) for FUN, e.g., columns for select."
(let (cmdhist cmd result)
(setq cmdhist
(pcase fun
('select
(format " %%>%% dplyr::select(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('filter
(format " %%>%% dplyr::filter(%s)" action))
('mutate
(format " %%>%% dplyr::mutate(%s)" action))
('sort
(format " %%>%% dplyr::arrange(%s, .by_group = TRUE)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('group
(format " %%>%% dplyr::group_by(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('ungroup
(format " %%>%% dplyr::ungroup(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('transmute
(format " %%>%% dplyr::transmute(%s)" action))
('wide2long
(format " %%>%% tidyr::gather(%s)" action))
('long2wide
(format " %%>%% tidyr::spread(%s)" action))
('wide2long-pivot_longer
(format " %%>%% tidyr::pivot_longer(%s)" action))
('long2wide-pivot_wider
(format " %%>%% tidyr::pivot_wider(%s)" action))
('slice
(format " %%>%% dplyr::slice(%s)" action))
('unselect
(format " %%>%% dplyr::select(%s)"
(mapconcat (lambda (x) (concat "-" x))
(delete-dups (nreverse action)) ",")))
(_
(format " %%>%% %s" action))))
(setq ess-view-data-page-number 0)
(setq cmd (concat
ess-view-data-temp-object " <<- " ess-view-data-temp-object cmdhist "; "
"local({"
(format (ess-view-data--do-print ess-view-data-current-update-print-backend)
(concat ess-view-data-temp-object
(unless ess-view-data-maxprint-p
(format "[(%1$d*%2$d + 1) : min((%1$d + 1)*%2$d, nrow(%s)),]"
ess-view-data-page-number
ess-view-data-rows-per-page
ess-view-data-temp-object)))
ess-view-data-temp-object)
"})\n"))
(setq result (cons cmdhist cmd))
result))
(cl-defmethod ess-view-data--do-summarise ((_backend (eql dplyr)) fun action)
"Do summarising by dplyr stepwisely, without modify the data frame.
Optional argument FUN What to do with the data, e.g.,
verb like count, unique, and etc..
Optional argument ACTION Parameter (R script) for FUN, e.g., columns for count."
(let (cmdhist cmd result)
(setq cmdhist
(pcase fun
('count
(format " %%>%% dplyr::count(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('unique
(format " %%>%% dplyr::distinct(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('slice
(format " %%>%% dplyr::slice(%s)" action))
('skimr
(format " %%>%% skimr::skim(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('skimr-all
" %>% skimr::skim()")
;; ('summarise
;; (format " %%>%% dplyr::summarise(%s)" action))
(_
(format " %%>%% %s" action))))
(setq cmd (concat
"local({"
(format (ess-view-data--do-print ess-view-data-current-summarize-print-backend)
(concat ess-view-data-temp-object cmdhist)
ess-view-data-temp-object)
"})\n"))
(setq result (cons cmdhist cmd))
result))
(cl-defmethod ess-view-data--do-reset ((_backend (eql dplyr)) action)
"Update the data frame by dplyr stepwisely.
Optional argument ACTION R script to reset the view process,
which will become the cmd history."
(let (cmdhist cmd result)
(setq cmdhist action)
(setq ess-view-data-page-number 0)
(setq cmd (concat
ess-view-data-temp-object " <<- " cmdhist "; "
"local({"
(format (ess-view-data--do-print ess-view-data-current-update-print-backend)
(concat ess-view-data-temp-object
(unless ess-view-data-maxprint-p
(format "[(%1$d*%2$d + 1) : min((%1$d + 1)*%2$d, nrow(%s)),]"
ess-view-data-page-number
ess-view-data-rows-per-page
ess-view-data-temp-object)))
ess-view-data-temp-object)
"})\n"))
(setq result (cons cmdhist cmd))
result))
(cl-defmethod ess-view-data-do-goto-page ((_backend (eql dplyr)) page &optional pnumber)
"Goto PAGE.
Optional argument PNUMBER The page number to go to."
(let (cmd result)
(setq ess-view-data-page-number
(pcase page
('first 0)
('last ess-view-data-total-page)
('previous (max 0 (1- ess-view-data-page-number)))
('next (min (1+ ess-view-data-page-number) ess-view-data-total-page))
('page (max (min pnumber ess-view-data-total-page) 0))
(_ ess-view-data-page-number)))
(setq cmd (concat
"local({"
(format (ess-view-data--do-print ess-view-data-current-update-print-backend)
(concat ess-view-data-temp-object
(unless ess-view-data-maxprint-p
(format "[(%1$d*%2$d + 1) : min((%1$d + 1)*%2$d, nrow(%s)),]"
ess-view-data-page-number
ess-view-data-rows-per-page
ess-view-data-temp-object)))
ess-view-data-temp-object)
"})\n"))
(setq result (cons nil cmd))
result))
(defvar-local ess-view-data--parent-buffer nil)
(defvar-local ess-view-data--reset-buffer-p nil)
(defvar-local ess-view-data--action nil)
(defvar-local ess-local-process-name nil)
(cl-defmethod ess-view-data--create-indirect-buffer
((_backend (eql dplyr))
type fun obj-list temp-object parent-buf proc-name)
"Create an edit-indirect buffer and return it.
Optional argument TYPE Action type, e.g., update, reset, summarise.
Optional argument FUN Action function to do with data, e.g.,
select, count, and etc..
Optional argument OBJ-LIST Columns/variables to do with.
Optional argument TEMP-OBJECT Temporary data in the view process.
Optional argument PARENT-BUF The associated parent buffer for the view process.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'."
(let ((buf (get-buffer-create (format ess-view-data-source-buffer-name-format temp-object)))
pts)
(with-current-buffer buf
(ess-r-mode)
(set-buffer-modified-p nil)
(setq ess-view-data--parent-buffer parent-buf)
(setq ess-view-data--reset-buffer-p t)
(setq ess-view-data--action `((:type . ,type) (:function . ,fun)))
;; (print (alist-get :function ess-view-data--action))
;; (print (alist-get ':type ess-view-data--action))
(insert "# Insert [all] variable name[s] (C-c C-i[a]), [all] Values (C-c C-l[v])\n")
(insert "# Line started with `#' will be omitted\n")
(insert "# Don't comment code as all code will be wrapped in one line\n")
(pcase fun
('filter
(setq ess-view-data-completion-object (car obj-list))
(insert "# dplyr::filter(...)\n")
(setq pts (point))
(insert (mapconcat (lambda (x) (propertize x 'evd-object x))
(delete-dups (nreverse obj-list)) ","))
(goto-char pts))
('mutate
(insert "# dplyr::mutate(...)\n")
(setq pts (point))
(insert (mapconcat (lambda (x) (format " = %s" (propertize x 'evd-object x)))
(delete-dups (nreverse obj-list)) ","))
(goto-char pts))
('wide2long
(insert "# tidyr::gather(cols, ...)\n")
(insert (format "key = %s, value = %s" (car obj-list) (nth 1 obj-list))))
('long2wide
(insert "# tidyr::spread(key to column names)\n")
(insert (format "key = %s, value = %s" (car obj-list) (nth 1 obj-list))))
('wide2long-pivot_longer
(insert "# tidyr::pivot_longer(cols, names and values to)\n")
(insert (format "c(), names_to = %s, values_to = %s" (car obj-list) (nth 1 obj-list))))
('long2wide-pivot_wider
(insert "# tidyr::pivot_wider(names and values from)\n")
(insert (format "names_from = %s, values_from = %s" (car obj-list) (nth 1 obj-list))))
;; ('summarise
;; (insert "# %> ... \n# Not limited to function summarise\n")
;; (insert (mapconcat (lambda (x) (format "%s" (propertize x 'evd-object x)))
;; (delete-dups (nreverse obj-list)) ","))
('summarise
(insert "# %> ... \n# Not limited to function summarise\n")
;; (insert (format "summarise(mean = mean(%s, na.rm = TRUE), n = n())" obj-list))
(insert "summarise(")
(insert (mapconcat (lambda (x) (format "%s" (propertize x 'evd-object x)))
(delete-dups (nreverse obj-list)) ","))
(insert ", n = n())"))
('reset
(insert "# reset\n")
(insert obj-list))
(_
(insert "# %> ... \n")
(setq pts (point))
(insert (mapconcat 'identity (delete-dups (nreverse obj-list)) ","))
(goto-char pts)))
(setq ess-local-process-name proc-name)
(setq ess-view-data-temp-object
(buffer-local-value 'ess-view-data-temp-object parent-buf))
(ess-view-data-edit-mode))
(select-window (display-buffer buf))))
;;; * backend: dplyr+DT
(defcustom ess-view-data-DT-rows-per-page 1000
"Rows per page for DT."
:type 'integer
:group 'ess-view-data)
(defcustom ess-view-data-cache-directory
(expand-file-name (format "ess-view-data-%d" (user-uid))
temporary-file-directory)
"The base directory, where the cache files (e.g., html files from DT)
will be saved."
:type 'directory
:group 'ess-view-data)
(defun ess-view-data-make-safe-dir (dir)
"This is from `doc-view-make-safe-dir'.
Just to try create a temporary directory to cache the DT files.
Argument DIR name of temporary dir."
(condition-case nil
;; Create temp files with strict access rights. It's easy to
;; loosen them later, whereas it's impossible to close the
;; time-window of loose permissions otherwise.
(with-file-modes #o0700 (make-directory dir))
(file-already-exists
(when (file-symlink-p dir)
(error "Danger: %s points to a symbolic link" dir))
;; In case it was created earlier with looser rights.
;; We could check the mode info returned by file-attributes, but it's
;; a pain to parse and it may not tell you what we want under
;; non-standard file-systems. So let's just say what we want and let
;; the underlying C code and file-system figure it out.
;; This also ends up checking a bunch of useful conditions: it makes
;; sure we have write-access to the directory and that we own it, thus
;; closing a bunch of security holes.
(condition-case error
(set-file-modes dir #o0700)
(file-error
(error
(format "Unable to use temporary directory %s: %s"
dir (mapconcat #'identity (cdr error) " "))))))))
;;; ** Initialization
(cl-defmethod ess-view-data--initialize-backend ((_backend (eql dplyr+DT)) proc-name proc)
"Initialization.
Initializing the history of operations, make temp object.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(let ((obj-space-p (string-match-p ess-view-data-objname-regex ess-view-data-object))
(obj-back-quote-p (string-match-p "`" ess-view-data-object))
(obj-back-quote (replace-regexp-in-string "`" "" ess-view-data-object)))
(unless ess-view-data-history
(setq ess-view-data-history
(format (cond (obj-back-quote-p "as_tibble(%s)")
(obj-space-p "as_tibble(`%s`)")
(t "as_tibble(%s)"))
ess-view-data-object)))
;; Initializing the temporary object, for stepwise
(unless ess-view-data-temp-object
(setq ess-view-data-temp-object
(format (cond (obj-back-quote-p "`%s`")
(obj-space-p "`%s`")
(t "`%s`"))
(make-temp-name obj-back-quote)))
(ess-view-data-make-safe-dir ess-view-data-cache-directory)
(when (and proc-name proc
(not (process-get proc 'busy)))
(ess-command (concat "{suppressPackageStartupMessages(require(dplyr));"
"suppressPackageStartupMessages(require(DT)); "
ess-view-data-temp-object " <<- as_tibble("
(format (cond (obj-back-quote-p "`%s`")
(obj-space-p "`%s`")
(t "`%s`"))
obj-back-quote)
")}\n")
nil nil nil nil proc))))
(cl-pushnew ess-view-data-temp-object ess-view-data-temp-object-list)
(delete-dups ess-view-data-temp-object-list))
(cl-defmethod ess-view-data--header-line ((_backend (eql dplyr+DT)))
"Make header-line for dplyr+DT."
(goto-char (point-min))
(browse-url (format "%s/%s.html" ess-view-data-cache-directory
(replace-regexp-in-string "`" "" ess-view-data-temp-object))))
(cl-defmethod ess-view-data-get-total-page ((_backend (eql dplyr+DT)) proc-name proc)
"Get the total number of pages.
Get total number of pages of the current object (data.frame/tibble/data.table).
If `ess-view-data-maxprint-p' is nil, it will show 1000 rows/lines per page
for DT.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(when (and proc-name proc
(not (process-get proc 'busy)))
(setq ess-view-data-total-page
(string-to-number
(car (ess-get-words-from-vector
(format "as.character(nrow(%s))\n" ess-view-data-temp-object)))))
(setq ess-view-data-total-page
(1+ (floor (/ ess-view-data-total-page ess-view-data-rows-per-page))))))
(cl-defmethod ess-view-data-do-kill-buffer-hook ((_backend (eql dplyr+DT)) proc-name proc)
"Functions to run after `kill-buffer' on '*R Data View' buffer.
The default is to rm the temporary object.
Optional argument PROC-NAME The name of associated ESS process,
usually `ess-local-process-name'.
Optional argument PROC The associated ESS process."
(when (and proc-name proc
(not (process-get proc 'busy)))
(ess-command (format "rm(%s, envir = globalenv())\n" ess-view-data-temp-object))
(ess-write-to-dribble-buffer (format "[ESS-v] rm(%s, envir = globalenv())\n" ess-view-data-temp-object))))
;;; ** Utilities
(cl-defmethod ess-view-data--do-update ((_backend (eql dplyr+DT)) fun action)
"Update the data frame by dplyr stepwisely.
Optional argument FUN what to do, e.g. select, filter, etc..
Optional argument ACTION parameters to the FUN."
(let (cmdhist cmd result)
(setq cmdhist
(pcase fun
('select
(format " %%>%% dplyr::select(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('filter
(format " %%>%% dplyr::filter(%s)" action))
('mutate
(format " %%>%% dplyr::mutate(%s)" action))
('sort
(format " %%>%% dplyr::arrange(%s, .by_group = TRUE)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('group
(format " %%>%% dplyr::group_by(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('ungroup
(format " %%>%% dplyr::ungroup(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('transmute
(format " %%>%% dplyr::transmute(%s)" action))
('wide2long
(format " %%>%% tidyr::gather(%s)" action))
('long2wide
(format " %%>%% tidyr::spread(%s)" action))
('wide2long-pivot_longer
(format " %%>%% tidyr::pivot_longer(%s)" action))
('long2wide-pivot_wider
(format " %%>%% tidyr::pivot_wider(%s)" action))
('slice
(format " %%>%% dplyr::slice(%s)" action))
('unselect
(format " %%>%% dplyr::select(%s)"
(mapconcat (lambda (x) (concat "-" x))
(delete-dups (nreverse action)) ",")))
(_
(format " %%>%% %s" action))))
(setq ess-view-data-page-number 0)
(setq cmd (concat
ess-view-data-temp-object " <<- " ess-view-data-temp-object cmdhist "; "
"local({"
(format "DT::saveWidget(datatable(%1$s, filter = 'top' %2$s), file = '%3$s/%4$s.html')\n"
ess-view-data-temp-object
(if ess-view-data-maxprint-p
(format ", options = list(autoWidth = FALSE,pageLength = %d)"
ess-view-data-DT-rows-per-page)
(format ", options = list(lengthMenu = c(10,50,100,%d))" ess-view-data-DT-rows-per-page))
ess-view-data-cache-directory
(replace-regexp-in-string "`" "" ess-view-data-temp-object))
"})\n"))
(setq result (cons cmdhist cmd))
result))
(cl-defmethod ess-view-data--do-summarise ((_backend (eql dplyr+DT)) fun action)
"Do summarising by dplyr stepwisely, without modify the data frame.
Optional argument FUN what to do, e.g., count, unique, etc..
Optional argument ACTION parameters to the FUN."
(let (cmdhist cmd result)
(setq cmdhist
(pcase fun
('count
(format " %%>%% dplyr::count(%s)" (mapconcat 'identity (delete-dups (nreverse action)) ",")))
('unique
(format " %%>%% dplyr::distinct(%s)" (mapconcat 'identity (delete-dups (nreverse action)) ",")))
('slice
(format " %%>%% dplyr::slice(%s)" action))
('skimr
(format " %%>%% skimr::skim(%s)"
(mapconcat 'identity (delete-dups (nreverse action)) ",")))
('skimr-all
" %>% skimr::skim()")
;; ('summarise
;; (format " %%>%% dplyr::summarise(%s)" action))
(_
(format " %%>%% %s" action))))
(setq cmd (concat
"local({"
(format (ess-view-data--do-print ess-view-data-current-summarize-print-backend)
(concat ess-view-data-temp-object cmdhist)
ess-view-data-temp-object)
"})\n"))
(setq result (cons cmdhist cmd))
result))
(cl-defmethod ess-view-data--do-reset ((_backend (eql dplyr+DT)) action)
"Update the data frame by dplyr stepwisely.
Optional argument ACTION R script to reset the view process,
which will become the cmd history."
(let (cmdhist cmd result)
(setq cmdhist action)
(setq ess-view-data-page-number 0)
(setq cmd (concat