~ubuntu-branches/ubuntu/utopic/evernote-mode/utopic-proposed

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
;;
;;  Copyright 2010 Yusuke Kawakami
;;
;;   Licensed under the Apache License, Version 2.0 (the "License");
;;   you may not use this file except in compliance with the License.
;;   You may obtain a copy of the License at
;;
;;       http://www.apache.org/licenses/LICENSE-2.0
;;
;;   Unless required by applicable law or agreed to in writing, software
;;   distributed under the License is distributed on an "AS IS" BASIS,
;;   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;   See the License for the specific language governing permissions and
;;   limitations under the License.

;;
;; evernote-mode home page is at:
;; Author: Yusuke Kawakami
;; Version: 0.03
;; Keywords: tools

;; This emacs lisp offers the interactive functions to open, edit, and update notes of Evernote.
;; The minor mode Evernote-mode is applied to the buffer editing a note of Evernote.
;;
;; Please copy this file into emacs lisp library directory or place it in
;; a directory (for example "~/lisp") and write $HOME/.emacs like this.
;;
;;      (add-to-list 'load-path "~/lisp")
;;      (require 'evernote-mode)
;;      (global-set-key "\C-cec" 'evernote-create-note)
;;      (global-set-key "\C-ceo" 'evernote-open-note)
;;      (global-set-key "\C-ces" 'evernote-search-notes)
;;      (global-set-key "\C-ceS" 'evernote-do-saved-search)
;;      (global-set-key "\C-cew" 'evernote-write-note)
;;
;; There is one hooks, evernotes-mode-hook.
;; The usage of the hook is shown as follows.
;;
;; (setq evernote-mode-hook
;;   '(lambda ()
;;      (...)))

;;; Code

(defvar evernote-mode nil
  "Non-nil if Evernote mode is enabled.")
(make-variable-buffer-local 'evernote-mode)

(defvar evernote-note-guid nil
  "Note guid of the buffer")
(make-variable-buffer-local 'evernote-note-guid)

(defvar evernote-note-name nil
  "Note name of the buffer")
(make-variable-buffer-local 'evernote-note-name)

(defvar evernote-note-tags nil
  "Tags of the buffer")
(make-variable-buffer-local 'evernote-note-tags)

(defvar evernote-note-edit-mode nil
  "Edit mode of the buffer")
(make-variable-buffer-local 'evernote-note-edit-mode)

(defvar evernote-mode-map (make-sparse-keymap)
  "Keymap used in evernote mode.")
(define-key evernote-mode-map "\C-x\C-s" 'evernote-save-note)
(define-key evernote-mode-map "\C-cet"   'evernote-edit-tags)
(define-key evernote-mode-map "\C-cee"   'evernote-change-edit-mode)
(define-key evernote-mode-map "\C-cer"   'evernote-rename-note)
(define-key evernote-mode-map "\C-ced"   'evernote-delete-note)

(defvar evernote-read-note-map
  (copy-keymap minibuffer-local-completion-map))
(define-key evernote-read-note-map [tab] 'evernote-read-note-completion)
(define-key evernote-read-note-map "\C-i" 'evernote-read-note-completion)
(define-key evernote-read-note-map "\C-m" 'evernote-read-note-finish)
(define-key evernote-read-note-map  " "   'self-insert-command)


(defvar evernote-search-mode-map (copy-keymap global-map)
  "Keymap used in evernote search mode.")
(define-key evernote-search-mode-map "\C-m" 'evernote-select-note-in-search-mode)

(defvar evernote-search-mode-formatted-name-displayed-name-alist nil
  "Alist from formatted names to names used only in evernote-search-mode buffer")
(make-variable-buffer-local 'evernote-search-mode-formatted-name-displayed-name-alist)


(defconst evernote-command-output-buffer-name "*Evernote-Client-Output*")
(defconst evernote-error-ok                  0)
(defconst evernote-error-fail                100)
(defconst evernote-error-parse               101)
(defconst evernote-error-unknown             1)
(defconst evernote-error-bad-data-format     2)
(defconst evernote-error-permission-denied   3)
(defconst evernote-error-internal-error      4)
(defconst evernote-error-data-required       5)
(defconst evernote-error-limit-reached       6)
(defconst evernote-error-quota-reached       7)
(defconst evernote-error-invalid-auth        8)
(defconst evernote-error-auth-expired        9)
(defconst evernote-error-data-conflict      10)
(defconst evernote-error-enml-validation    11)
(defconst evernote-error-shared-unavailable 12)


;;
;; Interactive functions.
;;


(defun evernote-open-note ()
  "Open a note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (evernote-open-note-common
      (evernote-command-get-note-list-from-tags
       (evernote-completing-read-multiple
        "Tags used for search (comma separated form. default search all tags):"
        (evernote-get-tag-alist
         (evernote-command-get-tag-list))
        nil t))))))


(defun evernote-search-notes ()
  "Search notes with query and open a note among them"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (evernote-open-note-common
      (evernote-command-get-note-list-from-query
       (read-string "Query:"))
      t))))


(defun evernote-do-saved-search ()
  "Do a saved search and open a note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (evernote-open-note-common
      (evernote-command-get-note-list-from-query
       (let ((search-alist
              (evernote-get-search-alist (evernote-command-get-search-list))))
         (evernote-assoc-cdr
          'query
          (evernote-assoc-cdr
           (completing-read
            "Saved search:"
            search-alist
            nil t)
           search-alist))))
      t))))


(defun evernote-open-note-common (note-command-output &optional display-completion)
  "Common procedure of opening a note"
  (let (note-attr note-guid note-name note-edit-mode note-tags opened-buf)
    (setq note-attr (evernote-read-note-attr note-command-output display-completion))
    (setq note-guid (evernote-assoc-cdr 'guid note-attr)
          note-name (evernote-assoc-cdr 'name note-attr)
          note-edit-mode (evernote-assoc-cdr 'edit-mode note-attr)
          note-tags (evernote-assoc-cdr 'tags note-attr))
    (setq opened-buf (evernote-find-opened-buffer note-guid))
    (if opened-buf
        (evernote-move-cursor-to-window opened-buf)
      (progn
        (evernote-create-note-buffer
         note-guid
         note-name
         note-edit-mode
         note-tags
         (evernote-command-get-note-content note-guid note-edit-mode))))))


(defun evernote-save-note ()
  "Save a note"
  (interactive)
  (if (and evernote-note-guid (buffer-modified-p))
      (evernote-command-with-auth
       (lambda ()
         (progn
           (evernote-command-update-note
            (current-buffer)
            evernote-note-guid
            evernote-note-name
            evernote-note-tags
            evernote-note-edit-mode)
           (set-buffer-modified-p nil))))
    (message "(No changes need to be saved)")))


(defun evernote-create-note ()
  "Create a note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (let (tags name edit-mode)
       (setq tags
             (evernote-completing-read-multiple
              "Attached Tags (comma separated form):"
              (evernote-get-tag-alist
               (evernote-command-get-tag-list))))
       (setq name (read-string "Note name:"))
       (setq edit-mode "TEXT")
       (switch-to-buffer (generate-new-buffer name))
       (evernote-command-create-note (current-buffer)
                                     name
                                     tags
                                     edit-mode)
       (setq evernote-note-guid (evernote-eval-command-result)
             evernote-note-name name
             evernote-note-tags tags
             evernote-note-edit-mode edit-mode)
       (evernote-mode)
       (evernote-update-mode-line)
       (set-buffer-modified-p nil)))))


(defun evernote-write-note ()
  "Write buffer to a note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (let (tags name edit-mode)
       (setq tags
             (evernote-completing-read-multiple
              "Attached Tags (comma separated form):"
              (evernote-get-tag-alist
               (evernote-command-get-tag-list))))
       (setq name (read-string "Note name:" (buffer-name)))
       (setq edit-mode (evernote-read-edit-mode "TEXT"))
       (evernote-command-create-note (current-buffer)
                                     name
                                     tags
                                     edit-mode)
       (setq evernote-note-guid (evernote-eval-command-result)
             evernote-note-name name
             evernote-note-tags tags
             evernote-note-edit-mode edit-mode)
       (if (not evernote-mode)
           (evernote-mode))
       (rename-buffer name t)
       (evernote-update-mode-line)
       (set-buffer-modified-p nil)))))


(defun evernote-edit-tags ()
  "Add or remove tags from/to the note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (if evernote-mode
         (progn
           (setq evernote-note-tags
                 (evernote-completing-read-multiple
                  "Change attached Tags (comma separated form):"
                  (evernote-get-tag-alist (evernote-command-get-tag-list))
                  nil nil (mapconcat #'identity evernote-note-tags ",")))
           (evernote-update-mode-line)
           (set-buffer-modified-p t))))))


(defun evernote-change-edit-mode ()
  "Change edit mode of the note"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (if evernote-mode
         (progn
           (setq evernote-note-edit-mode
                 (evernote-read-edit-mode evernote-note-edit-mode))
           (evernote-update-mode-line)
           (set-buffer-modified-p t))))))


(defun evernote-rename-note ()
  "Rename a note"
  (interactive)
  (if evernote-mode
      (progn
        (setq evernote-note-name
              (read-string "New note name:" evernote-note-name))
        (rename-buffer evernote-note-name t)
        (set-buffer-modified-p t))))


(defun evernote-delete-note ()
  "Delete a note"
  (interactive)
  (if (and evernote-mode
           (y-or-n-p "Do you really want to remove this note? "))
      (evernote-command-with-auth
       (lambda ()
         (evernote-command-delete-note evernote-note-guid)
         (kill-buffer (current-buffer))))))


(defun evernote-create-search ()
  "Create a saved search"
  (interactive)
  (evernote-command-with-auth
   (lambda ()
     (evernote-command-create-search
      (read-string "Saved Search Name:")
      (read-string "Query:")))))


;;
;; Helper functions.
;;

(defun evernote-command-with-auth (func &rest args)
  "Add or remove tags from/to the note"
  (let ((error-code (catch 'error (apply func args))))
    (if (or (eq error-code evernote-error-invalid-auth)
            (eq error-code evernote-error-auth-expired))
        (let ((error-code (catch 'error (evernote-command-login))))
          (if (eq error-code t)
              (apply func args)
            (message (evernote-error-message error-code))))
      (message (evernote-error-message error-code)))))


(defun evernote-get-tag-alist (tag-command-out)
  "Get the alist for completion from command output"
  (let (acc collect-tagname)
    (setq collect-tagname
          (lambda (node)
            (setq acc
                  (cons
                   (list (evernote-assoc-cdr 'name node))
                   acc))
            (mapc collect-tagname (evernote-assoc-cdr 'children node))))
    (mapcar collect-tagname tag-command-out)
    (nreverse acc)))


(defun evernote-get-search-alist (search-command-out)
  "Get the alist for completion from command output"
  (mapcar
   (lambda (elem)
     (cons
      (evernote-assoc-cdr 'name elem)
      elem))
   search-command-out))


(defun evernote-read-note-attr (note-command-out &optional display-completion)
  "Prompts a note name and returns a note attribute"
  (let ((name-num-hash (make-hash-table :test #'equal))
        evernote-note-displayed-name-attr-alist ; used in evernote-search-mode
        evenote-note-displayed-name-formatted-name-alist) ; used in evernote-search-mode
    (mapc
     (lambda (attr)
       (let (name displayed-name)
         (setq name (evernote-assoc-cdr 'name attr))
         (setq displayed-name
               (evernote-get-displayed-note-name name name-num-hash))
         (setq evernote-note-displayed-name-attr-alist
               (cons (cons displayed-name attr)
                     evernote-note-displayed-name-attr-alist))
         (setq evenote-note-displayed-name-formatted-name-alist
               (cons (cons displayed-name
                           (format "%s   %s"
                                   (evernote-assoc-cdr 'updated attr)
                                   displayed-name))
                     evenote-note-displayed-name-formatted-name-alist))))
     note-command-out)
    (setq evernote-note-displayed-name-attr-alist
          (nreverse evernote-note-displayed-name-attr-alist))
    (setq evenote-note-displayed-name-formatted-name-alist
          (nreverse evenote-note-displayed-name-formatted-name-alist))
    (if display-completion
        (evernote-display-note-completion-buf
         evenote-note-displayed-name-formatted-name-alist))
    (evernote-assoc-cdr (read-from-minibuffer "Note:"
                                              nil evernote-read-note-map)
                        evernote-note-displayed-name-attr-alist)))


(defun evernote-get-displayed-note-name (name name-hash)
  "Get displayed note name from the read note name"
  (let ((num (gethash name name-num-hash))
        result)
    (if num
        (progn
          (setq num (+ num 1))
          (setq result (format "%s(%d)" name num))
          (puthash name num name-num-hash))
      (setq result (substring name 0))
      (puthash name 1 name-num-hash))
    result))


(defun evernote-read-note-completion ()
  "Complete note name and display completion list"
  (interactive)
  (let (word result start)
    (setq word (evernote-get-minibuffer-string))
    (setq result (try-completion word evernote-note-displayed-name-attr-alist))
    ;(evernote-minibuffer-tmp-message (concat "[" word "]"))
    (cond
     ((eq result t)
      (evernote-minibuffer-tmp-message "[Sole Completion]"))
     ((eq result nil)
      (ding)
      (evernote-minibuffer-tmp-message "[No Match]"))
     ((string= result word)
      (evernote-display-note-completion-buf
       evenote-note-displayed-name-formatted-name-alist))
     (t (evernote-set-minibuffer-string result)
        (end-of-buffer)
        (if (eq t
                (try-completion result
                                evernote-note-displayed-name-attr-alist))
            nil
          (evernote-minibuffer-tmp-message "[Complete, but not unique]"))))))


(defun evernote-read-note-finish ()
  "Finish input note name"
  (interactive)
  (if (assoc
       (evernote-get-minibuffer-string)
       evernote-note-displayed-name-attr-alist)
      (progn
        (let ((completion-buf (get-buffer "*Evernote-Completions*")))
          (if completion-buf
              (kill-buffer completion-buf)))
        (exit-minibuffer))
    (evernote-minibuffer-tmp-message "[No Match]")))


(defun evernote-display-note-completion-buf (displayed-name-formatted-name-alist &optional word)
  (let (formatted-name-displayed-name-alist completion-buf)
    (setq formatted-name-displayed-name-alist
          (mapcar (lambda (displayed-name)
                    (cons
                     (evernote-assoc-cdr
                      displayed-name
                      evenote-note-displayed-name-formatted-name-alist)
                     displayed-name))
                  (all-completions
                   (if word
                       word
                     "")
                   evenote-note-displayed-name-formatted-name-alist)))
    (save-excursion
      (setq completion-buf (get-buffer-create "*Evernote-Completions*"))
      (set-buffer completion-buf)
      (evernote-display-note-completion-list
       formatted-name-displayed-name-alist)
      (setq evernote-search-mode-formatted-name-displayed-name-alist
            formatted-name-displayed-name-alist)
      (evernote-search-mode))
    (display-buffer completion-buf)))


(defun evernote-display-note-completion-list (formatted-name-displayed-name-alist)
  "Display formatted note names on this buffer"
  (setq buffer-read-only nil)
  (erase-buffer)
  (mapc (lambda (elem)
          (insert (car elem) "\n"))
        formatted-name-displayed-name-alist)
  (setq buffer-read-only t))


(defun evernote-select-note-in-search-mode ()
  "Select a note name on this buffer and input it into the mini buffer"
  (interactive)
  (save-excursion
    (let (displayed-name)
      (setq displayed-name
            (evernote-assoc-cdr
             (evernote-get-current-line-string)
             evernote-search-mode-formatted-name-displayed-name-alist))
      (kill-buffer (current-buffer))
      (if (active-minibuffer-window)
          (progn
            (evernote-set-minibuffer-string displayed-name)
            (exit-minibuffer))))))


(defun evernote-find-opened-buffer (guid)
  "Find a buffer associated with guid"
  (let ((found_buf nil))
    (save-excursion
      (mapc (lambda (buf)
              (set-buffer buf)
              (if (string= evernote-note-guid guid)
                  (setq found_buf buf)))
            (buffer-list)))
    found_buf))


(defun evernote-move-cursor-to-window (buf)
  "Move cursor to the window associated with the bufer"
  (let ((buf-window (get-buffer-window buf)))
    (if buf-window
        (select-window buf-window)
      (pop-to-buffer buf))))


(defun evernote-create-note-buffer (guid name edit-mode tags content)
  "Create new buffer for the note"
  (save-excursion
    (let ((buf (generate-new-buffer name)))
      (set-buffer buf)
      (insert content)
      (setq evernote-note-guid guid
            evernote-note-name name
            evernote-note-edit-mode edit-mode
            evernote-note-tags tags)
      (evernote-mode)
      (goto-char (point-min))
      (evernote-update-mode-line)
      (set-buffer-modified-p nil)
      (pop-to-buffer buf))))


(defun evernote-get-tag-list-string (tags maxlen)
  (substring
   (mapconcat #'identity tags ",")
   0 maxlen))


(defun evernote-read-edit-mode (default)
  (completing-read "Edit Mode (type \"TEXT\" or \"XHTML\"):"
                   '(("TEXT") ("XHTML"))
                   nil t default))


(defun evernote-string-to-oct (string)
  "Convert the string into quoted backslashed octal edit mode."
  (concat
   "\""
   (apply 'concat (mapcar (lambda (string)
                            (format "\\%03o" string))
                          (mapcar 'identity (encode-coding-string string 'utf-8))))
   "\""))


(defun evernote-assoc-cdr (key alist)
  (cdr (assoc key alist)))


(defun evernote-get-current-line-string ()
  (save-excursion
    (buffer-substring
     (progn
       (beginning-of-line)
       (point))
     (progn
       (end-of-line)
       (point)))))


(defun evernote-get-minibuffer-string ()
  (save-excursion
    (evernote-set-buffer-to-minibuffer)
    (buffer-substring
     (progn
       (goto-char (+ 1 (minibuffer-prompt-width)))
       (point))
     (progn
       (end-of-line)
       (point)))))


(defun evernote-set-minibuffer-string (str)
  (save-excursion
    (evernote-set-buffer-to-minibuffer)
    (delete-region
     (progn
       (goto-char (+ 1 (minibuffer-prompt-width)))
       (point))
     (progn
       (end-of-line)
       (point)))
    (insert str)))


(defun evernote-set-buffer-to-minibuffer ()
  (set-buffer (window-buffer (active-minibuffer-window))))


(defun evernote-minibuffer-tmp-message (msg)
  (save-excursion
    (goto-char (point-max))
    (save-excursion (insert " " msg))
    (sit-for 1)
    (delete-region (point) (point-max))))


(defun evernote-update-mode-line ()
  "Update mode line"
  (setq vc-mode
        (concat "[Tag:" (mapconcat #'identity evernote-note-tags ",") "] "
                "[Edit mode:" evernote-note-edit-mode "]"))
  (force-mode-line-update))


(defun evernote-completing-read-multiple
  (prompt table &optional predicate require-match initial-input hist def inherit-input-method)
  "Read multiple strings with completion. and return nil if no input is given"
  (let (results)
    (setq results
          (completing-read-multiple prompt
                                    table
                                    predicate
                                    require-match
                                    initial-input
                                    hist
                                    def
                                    inherit-input-method))
    (delete "" results)))


;;
;; Command interface.
;;

(defun evernote-command-login ()
  "Issue login command"
  (let* ((user (read-string "Evernote user name:"))
         (passwd (read-passwd "Passwd:")))
    (evernote-issue-command nil "login" user passwd)))


(defun evernote-command-get-tag-list ()
  "Issue listtags command"
  (evernote-issue-command nil "listtags")
  (evernote-eval-command-result))


(defun evernote-command-get-note-list-from-tags (tag-names)
  "Issue listnotes command from the tag name list."
  (if tag-names
      (let ((oct-tag-names
             (mapconcat #'identity (mapcar 'evernote-string-to-oct tag-names) ",")))
        (evernote-issue-command nil "listnotes" "-t" oct-tag-names))
    (evernote-issue-command nil "listnotes"))
  (evernote-eval-command-result))


(defun evernote-command-get-note-list-from-query (query)
  "Issue listnotes command from the query."
  (if query
      (let ((oct-query (evernote-string-to-oct query)))
        (evernote-issue-command nil "listnotes" "-q" oct-query))
    (evernote-issue-command nil "listnotes"))
  (evernote-eval-command-result))


(defun evernote-command-get-note-content (guid note-edit-mode)
  "Issue getnotecontent command specified by the guid and the edit mode."
  (let ((option (cond
                 ((string= note-edit-mode "XHTML") "-x")
                 ((string= note-edit-mode "TEXT") "--text"))))
    (evernote-issue-command nil "getnotecontent" guid option)
    (evernote-get-command-result)))


(defun evernote-command-create-note (inbuf name tags edit-mode)
  "Issue createnote command specified by the guid, tags and the edit-mode."
  (let (edit-mode-option)
    (cond
     ((string= edit-mode "XHTML")
      (setq edit-mode-option "-x"))
     ((string= edit-mode "TEXT")
      (setq edit-mode-option "--text")))
    (if tags
        (evernote-issue-command inbuf
                                "createnote" "-c"
                                "-t" (mapconcat #'identity (mapcar 'evernote-string-to-oct tags) ",")
                                (evernote-string-to-oct name)
                                edit-mode-option)
      (evernote-issue-command inbuf
                              "createnote" "-c"
                              (evernote-string-to-oct name)
                              edit-mode-option))))


(defun evernote-command-update-note (inbuf guid name tags edit-mode)
  "Issue updatenote command specified by the guid and the parameters for updating."
  (let (edit-mode-option)
    (cond
     ((string= edit-mode "XHTML")
      (setq edit-mode-option "-x"))
     ((string= edit-mode "TEXT")
      (setq edit-mode-option "--text")))
    (if tags
        (evernote-issue-command inbuf
                                "updatenote" "-c"
                                "-t" (mapconcat #'identity (mapcar 'evernote-string-to-oct tags) ",")
                                guid (evernote-string-to-oct name) edit-mode-option)
      (evernote-issue-command inbuf
                              "updatenote" "-c" "--delete-all-tags"
                              guid (evernote-string-to-oct name) edit-mode-option))))


(defun evernote-command-delete-note (guid)
  "Issue deletenote command specified by the guid, tags and the edit mode."
  (evernote-issue-command nil "deletenote" guid))


(defun evernote-command-get-search-list ()
  "Issue listsearch command"
  (evernote-issue-command nil "listsearch")
  (evernote-eval-command-result))


(defun evernote-command-create-search (name query)
  "Issue createsearch command"
  (evernote-issue-command nil
                          "createsearch"
                          (evernote-string-to-oct name)
                          (evernote-string-to-oct query)))


(defun evernote-issue-command (inbuf &rest args)
  "Invoke external process to issue an evernote command."
  (let ((outbuf (get-buffer-create evernote-command-output-buffer-name))
        (infile nil)
        (coding-system-for-read 'utf-8)
        (coding-system-for-write 'utf-8))
    (if inbuf
        (save-excursion
          (set-buffer inbuf)
          (setq infile (make-temp-file "evernote"))
          (write-region (point-min) (point-max) infile)))
    (save-excursion
      (set-buffer outbuf)
      (set-buffer-file-coding-system 'utf-8)
      (erase-buffer))
    (message "Waiting for the result...")
    (let ((result (apply 'call-process "ruby" infile outbuf nil "-S" "enclient.rb" args)))
      (message "")
      (cond
       ((eq result evernote-error-ok) t)
       (t (throw 'error result))))))


(defun evernote-get-command-result ()
  "Get the result of the result of the lately issued command as a string."
  (let ((outbuf (get-buffer-create evernote-command-output-buffer-name)))
    (save-excursion
      (set-buffer outbuf)
      (set-buffer-file-coding-system 'utf-8)
      (buffer-substring (point-min) (point-max)))))


(defun evernote-eval-command-result ()
  "Get the result of the result of the lately issued command as a string and eval the string."
  (let ((outbuf (get-buffer-create evernote-command-output-buffer-name)))
    (save-excursion
      (set-buffer outbuf)
      (set-buffer-file-coding-system 'utf-8)
      (car (read-from-string
            (buffer-substring (point-min) (point-max)))))))


(defun evernote-error-message (error-code)
  "Get the error message corresponding to  the integer command result."
  (cond
   ((eq error-code evernote-error-ok)                 "OK")
   ((eq error-code evernote-error-fail)               "System error")
   ((eq error-code evernote-error-parse)              "Parse error")
   ((eq error-code evernote-error-unknown)            "Unknown error")
   ((eq error-code evernote-error-bad-data-format)    "Bad data format")
   ((eq error-code evernote-error-permission-denied)  "Permission denied")
   ((eq error-code evernote-error-internal-error)     "Internal error")
   ((eq error-code evernote-error-data-required)      "Data required")
   ((eq error-code evernote-error-limit-reached)      "Limit reached")
   ((eq error-code evernote-error-quota-reached)      "Quota reached")
   ((eq error-code evernote-error-invalid-auth)       "Invalid auth")
   ((eq error-code evernote-error-auth-expired)       "Auth expired")
   ((eq error-code evernote-error-data-conflict)      "Data conflict")
   ((eq error-code evernote-error-enml-validation)    "Enml validation. Tried to save a note of invalid format.")
   ((eq error-code evernote-error-shared-unavailable) "Shared unavailable")))


;;
;; Evernote mode
;;

(defun evernote-search-mode ()
  "Major mode for selecting a note."
  (interactive)
  (use-local-map evernote-search-mode-map)
  (setq buffer-read-only t
        truncate-lines t
        major-mode 'evernote-search-mode
        mode-name "Evernote-Search")
  (goto-char (point-min)))

;;
;; Evernote mode
;;

(defun evernote-mode ()
  "Toggle Evernote mode, a minor mode for using evernote functions."
  (interactive)
  (or (assq 'evernote-mode minor-mode-alist)
      (setq minor-mode-alist (cons '(evernote-mode " Evernote") minor-mode-alist)))
  (or (assq 'evernote-mode minor-mode-map-alist)
      (setq minor-mode-map-alist
            (cons (cons 'evernote-mode evernote-mode-map) minor-mode-map-alist)))
  (set-buffer-file-coding-system 'utf-8)
  (setq evernote-mode (not evernote-mode))
  (setq vc-mode
        (concat "[Tag:" (mapconcat #'identity evernote-note-tags ",") "] "
                "[Edit Mode:" evernote-note-edit-mode "]"))
  (run-hooks 'evernote-mode-hook))


(provide 'evernote-mode)

;;(setq debug-on-error t)