File: w3m-ems.el

package info (click to toggle)
w3m-el 1.4.569+0.20170110-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,780 kB
  • sloc: lisp: 45,666; sh: 515; makefile: 403
file content (1412 lines) | stat: -rw-r--r-- 51,186 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
;;; w3m-ems.el --- GNU Emacs stuff for emacs-w3m

;; Copyright (C) 2001-2013, 2016 TSUCHIYA Masatoshi <tsuchiya@namazu.org>

;; Authors: Yuuichi Teranishi  <teranisi@gohome.org>,
;;          TSUCHIYA Masatoshi <tsuchiya@namazu.org>,
;;          Katsumi Yamaoka    <yamaoka@jpl.org>
;; Keywords: w3m, WWW, hypermedia

;; This file is a part of emacs-w3m.

;; 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 2, 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; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.


;;; Commentary:

;; This file contains GNU Emacs stuff that emacs-w3m uses.  For more
;; detail about emacs-w3m, see:
;;
;;    http://emacs-w3m.namazu.org/
;;
;; We can use w3m-static- switches to make the byte code differ between
;; Emacs 2[12] and 2[34], if anything, it is impossible to share the byte
;; code with those versions of Emacsen.

;;; Code:

(eval-when-compile
  (require 'cl))

(require 'w3m-util)
(require 'w3m-proc)
(require 'w3m-image)
(require 'w3m-favicon)
(require 'w3m-ccl)
(require 'wid-edit)

;; Functions and variables which should be defined in the other module
;; at run-time.
(eval-when-compile
  (defvar w3m-add-tab-number)
  (defvar w3m-coding-system)
  (defvar w3m-current-process)
  (defvar w3m-current-title)
  (defvar w3m-current-url)
  (defvar w3m-default-coding-system)
  (defvar w3m-display-inline-images)
  (defvar w3m-favicon-image)
  (defvar w3m-form-input-textarea-coding-system)
  (defvar w3m-form-use-fancy-faces)
  (defvar w3m-icon-directory)
  (defvar w3m-image-default-background)
  (defvar w3m-mode-map)
  (defvar w3m-modeline-process-status-on)
  (defvar w3m-new-session-in-background)
  (defvar w3m-process-queue)
  (defvar w3m-show-graphic-icons-in-header-line)
  (defvar w3m-show-graphic-icons-in-mode-line)
  (defvar w3m-toolbar)
  (defvar w3m-toolbar-buttons)
  (defvar w3m-use-favicon)
  (defvar w3m-use-header-line)
  (defvar w3m-use-header-line-title)
  (defvar w3m-use-tab)
  ;; `w3m-tab-move-right' calls the inline function `w3m-buffer-set-number'
  ;; which uses it.
  (defvar w3m-use-title-buffer-name)
  (defvar w3m-work-buffer-list)
  (defvar w3m-work-buffer-name)
  (autoload 'w3m-copy-buffer "w3m")
  (autoload 'w3m-delete-buffer "w3m")
  (autoload 'w3m-image-type "w3m")
  (autoload 'w3m-retrieve "w3m")
  (autoload 'w3m-select-buffer-update "w3m")
  (unless (fboundp 'image-animate)
    (defalias 'image-animate 'ignore)
    (defalias 'image-multi-frame-p 'ignore)))

(eval-and-compile
  (unless (fboundp 'frame-current-scroll-bars)
    (defalias 'frame-current-scroll-bars 'ignore))
  (unless (fboundp 'window-fringes)
    (defalias 'window-fringes 'ignore))
  (unless (fboundp 'unencodable-char-position)
    (defalias 'unencodable-char-position 'ignore)))

;;; Coding system and charset.

(defsubst w3m-find-coding-system (obj)
  "Return OBJ if it is a coding-system."
  (if (coding-system-p obj) obj))

(defun w3m-detect-coding-region (start end &optional priority-list)
  "Detect coding system of the text in the region between START and END.
Return the first possible coding system.

PRIORITY-LIST is a list of coding systems ordered by priority."
  (w3m-static-if (fboundp 'with-coding-priority)
      (with-coding-priority priority-list
	(car (detect-coding-region start end)))
    (let (category categories)
      (dolist (codesys priority-list)
	(setq category (coding-system-category codesys))
	(unless (or (null category) (assq category categories))
	  (push (cons category codesys) categories)))
      (car (detect-coding-with-priority start end (nreverse categories))))))

(defun w3m-mule-unicode-p ()
  "Check the existence as charsets of mule-unicode."
  (and (charsetp 'mule-unicode-0100-24ff)
       (charsetp 'mule-unicode-2500-33ff)
       (charsetp 'mule-unicode-e000-ffff)))

(defalias 'w3m-make-ccl-coding-system
  (if (fboundp 'define-coding-system)
      (eval-when-compile
	(funcall (if (and (fboundp 'define-coding-system)
			  (featurep 'bytecomp))
		     'byte-compile
		   'identity)
		 '(lambda (coding-system mnemonic docstring decoder encoder) "\
Define a new CODING-SYSTEM by CCL programs DECODER and ENCODER.
CODING-SYSTEM, DECODER and ENCODER must be symbols.
This function is an interface to `define-coding-system'."
		    (define-coding-system coding-system docstring
		      :mnemonic mnemonic :coding-type 'ccl
		      :ccl-decoder decoder :ccl-encoder encoder))))
    (eval-when-compile
      (funcall
       (if (featurep 'bytecomp)
	   (lambda (form)
	     (let ((byte-compile-warnings
		    (if (or (get 'make-coding-system 'byte-obsolete-info)
			    (eq (get 'make-coding-system 'byte-compile)
				'byte-compile-obsolete))
			(delq 'obsolete
			      (copy-sequence
			       (cond ((consp byte-compile-warnings)
				      byte-compile-warnings)
				     (byte-compile-warnings
				      byte-compile-warning-types)
				     (t nil))))
		      byte-compile-warnings)))
	       (byte-compile form)))
	 'identity)
       '(lambda (coding-system mnemonic docstring decoder encoder) "\
Define a new CODING-SYSTEM by CCL programs DECODER and ENCODER.
CODING-SYSTEM, DECODER and ENCODER must be symbols.
This function is an interface to `make-coding-system'."
	  (make-coding-system coding-system 4 mnemonic docstring
			      (cons decoder encoder)))))))

;; For Emacsen of which the `mule-version' is 5.x, redefine the ccl
;; programs that been defined in w3m-ccl.el.
(w3m-static-when (string-match "\\`5\\." mule-version)
  (let ((source
	 ;; CCL program to convert multibyte char to ucs with emacs-unicode.
	 `((if (r1 == ,(charset-id 'latin-iso8859-1))
	       ((r1 = (r0 + 128)))
	     (if (r1 == ,(charset-id 'mule-unicode-0100-24ff))
		 ((r1 = ((((r0 & #x3f80) >> 7) - 32) * 96))
		  (r0 &= #x7f)
		  (r1 += (r0 + 224)))		; 224 == -32 + #x0100
	       (if (r1 == ,(charset-id 'mule-unicode-2500-33ff))
		   ((r1 = ((((r0 & #x3f80) >> 7) - 32) * 96))
		    (r0 &= #x7f)
		    (r1 += (r0 + 9440)))	; 9440 == -32 + #x2500
		 (if (r1 == ,(charset-id 'mule-unicode-e000-ffff))
		     ((r1 = ((((r0 & #x3f80) >> 7) - 32) * 96))
		      (r0 &= #x7f)
		      (r1 += (r0 + 57312)))	; 57312 == -32 + #xe000
		   ,(if (fboundp 'ccl-compile-lookup-character)
			'((lookup-character utf-subst-table-for-encode r1 r0)
			  (if (r7 == 0)		; lookup failed
			      (r1 = #xfffd)))
		      '((r1 = #xfffd)))))))
	   (if (r1 == #xfffd)
	       (write-repeat ?~)		; unknown character.
	     (r0 = r1)))))
    (if (get 'utf-translation-table-for-encode 'translation-table-id)
	;; Emacs 21.3 and later.
	(progn
	  (eval
	   `(define-ccl-program w3m-euc-japan-encoder
	      '(4
		(loop
		 ,@w3m-ccl-write-euc-japan-character
		 (translate-character utf-translation-table-for-encode r1 r0)
		 ,@source
		 ,@w3m-ccl-generate-ncr))))
	  (eval
	   `(define-ccl-program w3m-iso-latin-1-encoder
	      '(4
		(loop
		 ,@w3m-ccl-write-iso-latin-1-character
		 (translate-character utf-translation-table-for-encode r1 r0)
		 ,@source
		 ,@w3m-ccl-generate-ncr)))))
      ;; Emacs 21.2 and earlier.
      (eval
       `(define-ccl-program w3m-euc-japan-encoder
	  '(4
	    (loop
	     ,@w3m-ccl-write-euc-japan-character
	     ,@source
	     ,@w3m-ccl-generate-ncr))))
      (eval
       `(define-ccl-program w3m-iso-latin-1-encoder
	  '(4
	    (loop
	     ,@w3m-ccl-write-iso-latin-1-character
	     ,@source
	     ,@w3m-ccl-generate-ncr)))))))

;; This might be redefined by w3m-ucs.el.
(defun w3m-ucs-to-char (codepoint)
  (or (decode-char 'ucs codepoint) ?~))

;; Function which returns non-nil when the current display device can
;; show images inline.
(defalias 'w3m-display-graphic-p 'display-images-p)

(defun w3m-display-inline-images-p ()
  "Returns non-nil when images can be displayed under the present
circumstances."
  (and w3m-display-inline-images (display-images-p)))

;; Animation.
(defcustom w3m-image-animate-seconds 10
  "Animate images (if possible) for this many seconds.
If nil, don't play the animation.  If t, loop forever."
  :group 'w3m
  :type '(choice (integer :tag "Animate for (seconds)")
		 (const :tag "Inhibit animation" nil)
		 (const :tag "Animate forever" t)))

(eval-and-compile
  (defalias 'w3m-image-multi-frame-p
    (if (fboundp 'image-multi-frame-p)
	(lambda (image)
	  (cdr (image-multi-frame-p image)))
      'image-animated-p)))

(defun w3m-image-animate (image)
  "Start animating IMAGE if possible.  Return IMAGE."
    (when (and (fboundp 'image-animate)
	       w3m-image-animate-seconds
	       (w3m-image-multi-frame-p image))
      (image-animate image nil w3m-image-animate-seconds)
      ;; Reset an image to the initial one after playing the animation.
      ;; FIXME: Is there a better way?
      (when (numberp w3m-image-animate-seconds)
	(run-with-timer (1+ w3m-image-animate-seconds) nil
			(lambda (image)
			  (image-animate image 0 0))
			image)))
    image)

(defun w3m-create-image (url &optional no-cache referer size handler)
  "Retrieve data from URL and create an image object.
If optional argument NO-CACHE is non-nil, cache is not used.
If second optional argument REFERER is non-nil, it is used as Referer: field.
If third optional argument SIZE is non-nil, its car element is used as width
and its cdr element is used as height."
  (if (not handler)
      (w3m-process-with-wait-handler
	(w3m-create-image url no-cache referer size handler))
    (lexical-let ((cur (current-buffer))
		  (set-size size)
		  (url url)
		  image size)
      (w3m-process-do-with-temp-buffer
	  (type (progn
		  (set-buffer-multibyte nil)
		  (w3m-retrieve url nil no-cache nil referer handler)))
	(goto-char (point-min))
	(when (w3m-image-type-available-p
	       (setq type
		     (or (and (let (case-fold-search)
				(looking-at
				 "\\(GIF8\\)\\|\\(\377\330\\)\\|\211PNG\r\n"))
			      (cond ((match-beginning 1) 'gif)
				    ((match-beginning 2) 'jpeg)
				    (t 'png)))
			 (w3m-image-type type))))
	  (setq image (create-image
		       (buffer-string) type t
		       :ascent 'center
		       :background w3m-image-default-background))
	  (if (and w3m-resize-images set-size)
	      (progn
		(set-buffer-multibyte t)
		(setq size (image-size image 'pixels))
		(if (and (null (car set-size)) (cdr set-size))
		    (setcar set-size
			    (/ (* (car size) (cdr set-size)) (cdr size))))
		(if (and (null (cdr set-size)) (car set-size))
		    (setcdr set-size
			    (/ (* (cdr size) (car set-size)) (car size))))
		(if (or (not (eq (car size)
				 (car set-size)))  ; width is different
			(not (eq (cdr size)
				 (cdr set-size)))) ; height is different
		    (lexical-let ((image image))
		      (w3m-process-do
			  (resized (w3m-resize-image
				    (plist-get (cdr image) :data)
				    (car set-size)(cdr set-size)
				    handler))
			(if resized (plist-put (cdr image) :data resized)))))))
	  (with-current-buffer cur (w3m-image-animate image)))))))

(defun w3m-create-resized-image (url rate &optional referer size handler)
  "Resize an cached image object.
URL is the image file's url.
RATE is resize percentage.
If REFERER is non-nil, it is used as Referer: field.
If SIZE is non-nil, its car element is used as width
and its cdr element is used as height."
  (if (not handler)
      (w3m-process-with-wait-handler
	(w3m-create-image url nil referer size handler))
    (lexical-let ((url url)
		  (rate rate)
		  image)
      (w3m-process-do-with-temp-buffer
	  (type (progn
		  (set-buffer-multibyte nil)
		  (w3m-retrieve url nil nil nil referer handler)))
	(when (w3m-image-type-available-p (setq type (w3m-image-type type)))
	  (setq image (create-image (buffer-string) type t :ascent 'center))
	  (progn
	    (set-buffer-multibyte t)
	    (w3m-process-do
		(resized (w3m-resize-image-by-rate
			  (plist-get (cdr image) :data)
			  rate
			  handler))
	      (if resized (plist-put (cdr image) :data resized))
	      image)))))))

(defun w3m-insert-image (beg end image &rest args)
  "Display image on the current buffer.
Buffer string between BEG and END are replaced with IMAGE."
  (let ((faces (get-text-property beg 'face))
	(idx 0)
	orig len face)
    (add-text-properties beg end (list 'display image
				       'intangible image
				       'invisible nil))
    ;; Hide underlines behind inline images.
    ;; Gerd Moellmann <gerd@gnu.org>, the maintainer of Emacs 21, wrote in
    ;; the article <86heyi7vks.fsf@gerd.segv.de> in the list emacs-pretest-
    ;; bug@gnu.org on 18 May 2001 that to show an underline of a text even
    ;; if it has an image as a text property is the feature of Emacs 21.
    ;; However, that behavior is not welcome to the w3m buffers, so we do
    ;; to fix it with the following stuffs.
    (when faces
      (unless (listp faces)
	(setq faces (list faces)))
      (setq orig (copy-sequence faces)
	    len (length orig))
      (while (< idx len)
	(when (face-underline-p (setq face (nth idx orig)))
	  (setq faces (delq face faces)))
	(setq idx (1+ idx)))
      (when (< (length faces) len)
	(put-text-property beg end 'face faces)
	(put-text-property beg end 'w3m-faces-with-underline orig)))))

(defun w3m-remove-image (beg end)
  "Remove an image which is inserted between BEG and END."
  (remove-text-properties beg end '(display nil intangible nil))
  (let ((underline (get-text-property beg 'w3m-faces-with-underline)))
    (when underline
      (add-text-properties
       beg end (list 'face underline 'w3m-faces-with-underline nil)))))

(defun w3m-image-type-available-p (image-type)
  "Return non-nil if an image with IMAGE-TYPE can be displayed inline."
  (and (display-images-p)
       (image-type-available-p image-type)))

;;; Form buttons
(defface w3m-form-button
  '((((type x w32 mac ns) (class color))
     :background "lightgrey" :foreground "black"
     :box (:line-width 2 :style released-button))
    (((class color) (background light)) (:foreground "cyan" :underline t))
    (((class color) (background dark)) (:foreground "red" :underline t))
    (t (:underline t)))
  "*Face to fontify buttons in forms."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-form-button-face 'face-alias 'w3m-form-button)

(defface w3m-form-button-mouse
  '((((type x w32 mac ns) (class color))
     :background "DarkSeaGreen1" :foreground "black"
     :box (:line-width 2 :style released-button))
    (((class color) (background light)) (:foreground "cyan" :underline t))
    (((class color) (background dark)) (:foreground "red" :underline t))
    (t (:underline t)))
  "*Face to fontify focused buttons in forms."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-form-button-mouse-face 'face-alias 'w3m-form-button-mouse)

(defface w3m-form-button-pressed
  '((((type x w32 mac ns) (class color))
     :background "lightgrey" :foreground "black"
     :box (:line-width 2 :style pressed-button))
    (((class color) (background light)) (:foreground "cyan" :underline t))
    (((class color) (background dark)) (:foreground "red" :underline t))
    (t (:underline t)))
  "*Face to fontify pressed buttons in forms."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-form-button-pressed-face 'face-alias 'w3m-form-button-pressed)

(defvar w3m-form-button-keymap
  (let ((map (copy-keymap widget-keymap)))
    (substitute-key-definition 'widget-forward nil map)
    (substitute-key-definition 'widget-backward nil map)
    map))

(define-widget 'w3m-form-button 'push-button
  "Widget for w3m form button."
  :keymap w3m-form-button-keymap
  :action (function (lambda (widget &optional e)
		      (eval (widget-get widget :w3m-form-action)))))

(defun w3m-form-make-button (start end properties &optional readonly)
  "Make button on the region from START to END."
  (cond (readonly
	 (w3m-add-text-properties
	  start end
	  (append '(face w3m-form-inactive w3m-form-readonly t) properties)))
	(w3m-form-use-fancy-faces
	 (unless (memq (face-attribute 'w3m-form-button :box)
		       '(nil unspecified))
	   (and (eq ?\[ (char-after start))
		(eq ?\] (char-before end))
		(save-excursion
		  (goto-char start)
		  (delete-char 1)
		  (insert " ")
		  (goto-char end)
		  (delete-char -1)
		  (insert " ")
		  (setq start (1+ start)
			end (1- end)))))
	 ;; Empty text won't be buttonized, so we fill it with something.
	 ;; "submit" seems to be a proper choice in nine cases out of ten.
	 (when (= start end)
	   (goto-char start)
	   (insert "submit")
	   (setq end (point)))
	 (let ((w (widget-convert-button
		   'w3m-form-button start end
		   :w3m-form-action (plist-get properties 'w3m-action))))
	   (overlay-put (widget-get w :button-overlay) 'evaporate t))
	 (add-text-properties start end properties))
	(t
	 (w3m-add-text-properties start end
				  (append '(face w3m-form) properties)))))

(defun w3m-setup-widget-faces ()
  (make-local-variable 'widget-button-face)
  (make-local-variable 'widget-mouse-face)
  (make-local-variable 'widget-button-pressed-face)
  (setq widget-button-face 'w3m-form-button)
  (setq widget-mouse-face 'w3m-form-button-mouse)
  (setq widget-button-pressed-face 'w3m-form-button-pressed))

;;; Menu bar
(defun w3m-menu-on-forefront (arg &optional curbuf)
  "Place emacs-w3m menus on the forfront of the menu bar if ARG is non-nil.
If CURBUF is given, this function works only in the current buffer,
otherwise works in all the emacs-w3m buffers."
  (if curbuf
      (if arg
	  (let ((items (mapcar 'car (cdr (lookup-key global-map [menu-bar])))))
	    (when items
	      (set (make-local-variable 'menu-bar-final-items) items)))
	(kill-local-variable 'menu-bar-final-items))
    (save-current-buffer
      (dolist (buffer (w3m-list-buffers t))
	(set-buffer buffer)
	(w3m-menu-on-forefront arg t)))))

;;; Toolbar
(defcustom w3m-use-toolbar
  (and (featurep 'tool-bar)
       ;; Emacs 22 and greater return t for `(featurep 'tool-bar)'
       ;; even if being launched with the -nw option.
       (display-images-p)
       (or (featurep 'gtk)
	   (image-type-available-p 'xpm)))
  "Non-nil activates toolbar of w3m."
  :group 'w3m
  :type 'boolean)

(defcustom w3m-toolbar-icon-preferred-image-types
  (if (featurep 'gtk)
      '(png)
    '(xpm))
  "List of image types that you prefer to use for the tool bar icons.
By default, `png' is most preferred for Emacs built with GTK and `xpm'
is for others."
  :group 'w3m
  :type '(repeat (symbol :tag "Image type"))
  :set (lambda (symbol value)
	 (prog1
	     (custom-set-default symbol value)
	   (when (and (not noninteractive) (boundp 'w3m-toolbar-buttons))
	     (w3m-update-toolbars)))))

(defcustom w3m-toolbar-use-single-image-per-icon nil
  "Non-nil means use single image (named *-up) per icon.
If it is nil, subsidiaries, e.g., *-down and *-disabled, if any, are
used together.

Note that this option will be ignored if running Emacs built with Gtk+
and every button will use a single icon image."
  :group 'w3m
  :type 'boolean
  :set (lambda (symbol value)
	 (prog1
	     (custom-set-default symbol value)
	   (when (and (not noninteractive) (boundp 'w3m-toolbar-buttons))
	     (w3m-update-toolbars)))))

(defcustom w3m-toolbar-configurations
  `((tool-bar-button-margin . global)
    ,@(unless (featurep 'gtk)
	'((tool-bar-button-relief . global))))
  "Alist of the variables and the values controls the tool bar appearance.
The value `global' means to use the global value of the variable.

If you're annoyed with changing of the frame height of Emacs built for
GTK because of the difference of the sizes between the emacs-w3m tool
bar icons and the ones that Emacs natively uses, try customizing this
variable or both the value of this variable and the global value of
`tool-bar-button-margin'.  For examples:

;; The case where the emacs-w3m icons are smaller than the others.
\(setq w3m-toolbar-configurations '((tool-bar-button-margin . 5)))

;; The case where the emacs-w3m icons are bigger than the others.
\(setq w3m-toolbar-configurations '((tool-bar-button-margin . 0))
      tool-bar-button-margin 7)"
  :group 'w3m
  :type '(repeat (cons :format "%v"
		       (symbol :tag "Variable")
		       (radio :format "%v"
			      (const :format "%v " global)
			      (sexp :tag "Local Value"))))
  :set (lambda (symbol value)
	 (prog1
	     (custom-set-default symbol value)
	   (when (and (not noninteractive) (featurep 'w3m))
	     (w3m-toolbar-set-configurations)))))

(defun w3m-toolbar-define-keys (keymap defs)
  ;; Invalidate the default bindings.
  (let ((keys (cdr (key-binding [tool-bar] t)))
	item)
    (unless (eq (caar keys) 'keymap) ;; Emacs >= 24
      (while (setq item (pop keys))
	(when (setq item (car-safe item))
	  (define-key keymap (vector 'tool-bar item) 'undefined)))))
  (let ((n (length defs))
	def)
    (while (>= n 0)
      (setq n (1- n)
	    def (nth n defs))
      (define-key keymap (vector 'tool-bar (aref def 1))
	(list 'menu-item (aref def 3) (aref def 1)
	      :enable (aref def 2)
	      :image (symbol-value (aref def 0)))))))

(defun w3m-find-image (name &optional directory)
  "Find image file for NAME and return cons of file name and type.
This function searches only in DIRECTORY, that defaults to the value of
`w3m-icon-directory', for an image file of which the base name is NAME.
Files of types that Emacs does not support are ignored."
  (unless directory
    (setq directory w3m-icon-directory))
  (when (and directory
	     (file-directory-p directory)
	     (display-images-p))
    (let* ((case-fold-search nil)
	   (files (directory-files directory t
				   (concat "\\`" (regexp-quote name) "\\.")))
	   (types (append w3m-toolbar-icon-preferred-image-types image-types))
	   file type rest)
      (while files
	(when (string-match "\\.\\([^.]+\\)\\'" (setq file (pop files)))
	  (setq type (intern (downcase (match-string 1 file))))
	  (setq type (or (cdr (assq type '((tif . tiff)
					   (jpg . jpeg)
					   (ps . postscript)
					   (pgm . pbm)
					   (ppm . pbm))))
			 type))
	  (push (cons file (memq type types)) rest)))
      (setq rest (car (sort rest (lambda (a b) (> (length a) (length b))))))
      (when (cdr rest)
	(cons (car rest) (cadr rest))))))

(defun w3m-toolbar-make-buttons (buttons &optional force)
  (let ((xpm-props '(:color-symbols (("backgroundToolBarColor" . "None"))))
	button icon down disabled up)
    (while buttons
      (setq button (pop buttons)
	    icon (intern (concat "w3m-toolbar-" button "-icon")))
      (when (or force (not (boundp icon)))
	(setq down (w3m-find-image (concat button "-down"))
	      disabled (w3m-find-image (concat button "-disabled")))
	(if (setq up (or (w3m-find-image (concat button "-up"))
			 (prog1
			     (or down disabled (w3m-find-image button))
			   (setq down nil
				 disabled nil))))
	    (progn
	      (setq up (apply 'create-image (car up) (cdr up) nil
			      :ascent 'center
			      (when (eq (cdr up) 'xpm)
				xpm-props)))
	      (if (or (boundp 'gtk-version-string)
		      w3m-toolbar-use-single-image-per-icon
		      (not (or down disabled)))
		  (set icon up)
		(when down
		  (setq down (apply 'create-image (car down) (cdr down) nil
				    :ascent 'center
				    (when (eq (cdr up) 'xpm)
				      xpm-props))))
		(when disabled
		  (setq disabled (apply 'create-image
					(car disabled) (cdr disabled) nil
					:ascent 'center
					(when (eq (cdr disabled) 'xpm)
					  xpm-props))))
		(set icon (vector down up disabled disabled))))
	  (error "Icon file %s-up.* not found" button))))))

(defun w3m-toolbar-set-configurations (&optional curbuf)
  "Set values of variables according to `w3m-toolbar-configurations'.
If CURBUF is given, this function works only in the current buffer,
otherwise works in all the emacs-w3m buffers."
  (if curbuf
      (dolist (config w3m-toolbar-configurations)
	(if (eq (cdr config) 'global)
	    (kill-local-variable (car config))
	  (set (make-local-variable (car config)) (cdr config))))
    (let ((cur (selected-frame))
	  buffer buffers)
      (walk-windows
       (lambda (window)
	 (setq buffer (window-buffer window))
	 (unless (memq buffer buffers)
	   (set-buffer buffer)
	   (when (eq major-mode 'w3m-mode)
	     (push buffer buffers)
	     (select-frame (window-frame window))
	     ;;(set-buffer buffer)
	     (w3m-toolbar-set-configurations t))))
       'ignore 'visible)
      (select-frame-set-input-focus cur)
      (save-current-buffer
	(dolist (buffer (w3m-list-buffers t))
	  (unless (memq buffer buffers)
	    (set-buffer buffer)
	    (w3m-toolbar-set-configurations t))))
      (select-frame-set-input-focus cur))))

(defun w3m-setup-toolbar ()
  (when (and w3m-use-toolbar
	     (w3m-find-image "antenna-up"))
    (w3m-toolbar-make-buttons w3m-toolbar-buttons)
    (w3m-toolbar-set-configurations t)
    (w3m-toolbar-define-keys w3m-mode-map w3m-toolbar)))

(defalias 'w3m-update-toolbar 'ignore)

(defun w3m-update-toolbars ()
  (when (and w3m-use-toolbar
	     (w3m-find-image "antenna-up"))
    (w3m-toolbar-make-buttons w3m-toolbar-buttons t)
    (w3m-toolbar-set-configurations)
    (w3m-toolbar-define-keys w3m-mode-map w3m-toolbar)))

;;; Header line & Tabs
(defcustom w3m-tab-width 16
  "w3m tab width."
  :group 'w3m
  :set (lambda (symbol value)
	 (custom-set-default symbol
			     (if (and (numberp value) (> value 0))
				 value
			       16)))
  :type '(integer :size 0))

(defface w3m-tab-unselected
  '((((type x w32 mac ns) (class color))
     :background "Gray70" :foreground "Gray20"
     :box (:line-width -1 :style released-button))
    (((class color))
     (:background "blue" :foreground "black")))
  "*Face to fontify unselected tabs."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-unselected-face 'face-alias 'w3m-tab-unselected)

(defface w3m-tab-unselected-retrieving
  '((((type x w32 mac ns) (class color))
     :background "Gray70" :foreground "OrangeRed"
     :box (:line-width -1 :style released-button))
    (((class color))
     (:background "blue" :foreground "OrangeRed")))
  "*Face to fontify unselected tabs which are retrieving their pages."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-unselected-retrieving-face
     'face-alias 'w3m-tab-unselected-retrieving)

(defface w3m-tab-unselected-unseen
  '((((type x w32 mac ns) (class color))
     :background "Gray70" :foreground "Gray20"
     :box (:line-width -1 :style released-button))
    (((class color))
     (:background "blue" :foreground "gray60")))
  "*Face to fontify unselected and unseen tabs."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-unselected-unseen-face 'face-alias 'w3m-tab-unselected-unseen)

(defface w3m-tab-selected
  '((((type x w32 mac ns) (class color))
     :background "Gray90" :foreground "black"
     :box (:line-width -1 :style released-button))
    (((class color))
     (:background "cyan" :foreground "black"))
    (t (:underline t)))
  "*Face to fontify selected tab."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-selected-face 'face-alias 'w3m-tab-selected)

(defface w3m-tab-selected-retrieving
  '((((type x w32 mac ns) (class color))
     :background "Gray90" :foreground "red"
     :box (:line-width -1 :style released-button))
    (((class color))
     (:background "cyan" :foreground "red"))
    (t (:underline t)))
  "*Face to fontify selected tab which is retrieving its page."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-selected-retrieving-face
     'face-alias 'w3m-tab-selected-retrieving)

(defface w3m-tab-background
  '((((type x w32 mac ns) (class color))
     :background "LightSteelBlue" :foreground "black")
    (((class color))
     (:background "white" :foreground "black")))
  "*Face to fontify background of tab line."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-background-face 'face-alias 'w3m-tab-background)

(defface w3m-tab-selected-background
  '((((type x w32 mac ns) (class color))
     :background "LightSteelBlue" :foreground "black")
    (((class color))
     (:background "white" :foreground "black")))
  "*Face to fontify selected background tab."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-selected-background-face
     'face-alias 'w3m-tab-selected-background)

(defface w3m-tab-mouse
  '((((type x w32 mac ns) (class color))
     :background "Gray75" :foreground "white"
     :box (:line-width -1 :style released-button)))
  "*Face used to highlight tabs under the mouse."
  :group 'w3m-face)
;; backward-compatibility alias
(put 'w3m-tab-mouse-face 'face-alias 'w3m-tab-mouse)

(defvar w3m-modeline-spinner-map nil
  "Keymap used on the spinner in the mode-line.")

(defvar w3m-spinner-map-help-echo "mouse-2 kills the current process"
  "String used for the :help-echo property on the spinner.")

(defun w3m-setup-header-line ()
  (setq header-line-format
	(cond (w3m-use-tab
	       '(:eval (w3m-tab-line)))
	      (w3m-use-header-line
	       (list
		(if w3m-use-header-line-title
		    (list
		     (propertize
		      "Title: "
		      'face (list 'w3m-header-line-location-title))
		     `(:eval
		       (propertize
			(replace-regexp-in-string "%" "%%" (w3m-current-title))
			'face (list 'w3m-header-line-location-content)
			'mouse-face '(highlight :foreground
						,(face-foreground 'default))
			'local-map (let ((map (make-sparse-keymap)))
				     (define-key map [header-line mouse-2]
				       'w3m-goto-url)
				     map)
			'help-echo "mouse-2 prompts to input URL"))
		     ", ")
		  "")
		 (propertize
		  "Location: "
		  'face (list 'w3m-header-line-location-title))
		 `(:eval
		  (propertize
		   (if (stringp w3m-current-url)
		       (replace-regexp-in-string "%" "%%" w3m-current-url)
		     "")
		   'face (list 'w3m-header-line-location-content)
		   'mouse-face '(highlight :foreground
					   ,(face-foreground 'default))
		   'local-map (let ((map (make-sparse-keymap)))
				(define-key map [header-line mouse-2]
				  'w3m-goto-url)
				map)
		   'help-echo "mouse-2 prompts to input URL")))))))

(eval-when-compile
  ;; Shut up the byte-compiler for old Emacsen.
  (unless (fboundp 'force-window-update)
    (defalias 'force-window-update 'ignore)))

(eval-and-compile
  (defalias 'w3m-force-window-update
    (if (and (fboundp 'force-window-update)
	     (not (eq (symbol-function 'force-window-update) 'ignore)))
	(lambda (&optional window) "\
Force redisplay of WINDOW which defaults to the selected window."
	  (force-window-update (or window (selected-window)))
	  (sit-for 0))
      (lambda (&optional ignore) "\
Wobble the selected window to force redisplay of the header-line."
	(save-window-excursion
	  (split-window-vertically))))))

(defun w3m-tab-drag-mouse-function (event buffer)
  (let ((window (posn-window (event-end event)))
	mpos)
    (when (framep window) ; dropped at outside of the frame.
      (setq window nil
	    mpos (mouse-position))
      (and (framep (car mpos))
	   (car (cdr mpos))
	   (cdr (cdr mpos))
	   (setq window (window-at (car (cdr mpos))
				   (cdr (cdr mpos))
				   (car mpos))))
      (unless window
	(when (one-window-p 'nomini)
	  (split-window))
	(setq window (next-window))))
    (unless (eq (window-buffer window) buffer)
      (select-window window)
      (switch-to-buffer buffer)
      (w3m-force-window-update window))))

(defun w3m-tab-click-mouse-function (event buffer)
  (let ((window (posn-window (event-start event))))
    (select-window window)
    (switch-to-buffer buffer)
    (w3m-force-window-update window)))

(defun w3m-tab-double-click-mouse1-function (event buffer)
  (let ((window (posn-window (event-start event))))
    (when (eq major-mode 'w3m-mode)
      (if w3m-new-session-in-background
	  (save-window-excursion
	    (w3m-copy-buffer))
	(w3m-copy-buffer)))
    (w3m-force-window-update window)))

(defun w3m-tab-double-click-mouse2-function (event buffer)
  (let ((window (posn-window (event-start event))))
    (when (eq major-mode 'w3m-mode)
      (w3m-delete-buffer))
    (w3m-force-window-update window)))

(defcustom w3m-tab-track-mouse t
  "Say whether to make the mouse track the selected tab.
It controls the behavior of the commands `w3m-tab-previous-buffer',
`w3m-tab-next-buffer', `w3m-tab-move-right', and `w3m-tab-move-left'
invoked by the mouse.

You may want to set this to nil if you use a proportional font for the
tab faces.  See also `w3m-tab-mouse-position-adjuster'."
  :group 'w3m
  :type 'boolean)

(defcustom w3m-tab-mouse-position-adjuster '(0.5 . -4)
  "Values used to adjust the mouse position on tabs.
It is used when the command `w3m-tab-previous-buffer',
`w3m-tab-next-buffer', `w3m-tab-move-right', or `w3m-tab-move-left' is
invoked by the mouse.  The value consists of the cons of a floating
point number M and an integer N that are applied to calculating of the
mouse position, which is given in pixel units, as follows:

  (TAB_WIDTH + M) * ORDER + N

Where TAB_WIDTH is the pixel width of a tab and ORDER is the order
number in tabs.  The result is rounded towards zero.

Note that the calculation will always fail if you use a proportional
font for the tab faces.  See also `w3m-tab-track-mouse'."
  :group 'w3m
  :type '(cons (number :tag "M") (integer :tag "N")))

(defun w3m-tab-mouse-track-selected-tab (event order &optional decelerate)
  "Make the mouse track the selected tab.
EVENT is a command event.  ORDER is the order number in tabs.
The optional DECELERATE if it is non-nil means not to respond to too
fast operation of mouse wheel."
  (when (and w3m-use-tab window-system w3m-tab-track-mouse
	     (consp event) (symbolp (car event)))
    (let ((e (get (car event) 'event-symbol-elements))
	  (len (* (car w3m-tab-mouse-position-adjuster) order))
	  (fcw (frame-char-width))
	  posn tab start end disp next)
      (when (and (consp e) (symbolp (car e))
		 (or (memq (car e) '(mouse-4 mouse-5 wheel-up wheel-down))
		     (string-match "\\`mouse-" (symbol-name (car e)))))
	;; Ignore values gotten by the mouse pointing to other frames.
	;; It might happen if the frame in question gets out of focus
	;; by a certain desktop tool such as unclutter.
	(let ((frame (selected-frame)))
	  (while (not (cadr (setq posn (mouse-pixel-position))))
	    (select-frame-set-input-focus frame)))
	;; Update the header line.
	(setq tab (w3m-tab-line))
	(with-temp-buffer
	  (insert tab)
	  (setq start (point-min)
		end (point))
	  (while (and (> order  0)
		      (setq start (text-property-any start end
						     'tab-separator t))
		      (setq start (text-property-not-all start end
							 'tab-separator t)))
	    (setq order (1- order)))
	  (setq end (1- start)
		start (point-min)
		next start
		disp (get-text-property start 'display))
	  (while (and (< next end)
		      (setq next (next-single-property-change
				  start 'display nil end)))
	    (setq len (+ (cond
			  ((eq (car disp) 'image)
			   (or (car w3m-favicon-size) (frame-char-height)))
			  ((eq (car disp) 'space)
			   (* (or (plist-get (cdr disp) :width) 1) fcw))
			  (t
			   (* (string-width (buffer-substring start next))
			      fcw)))
			 len)
		  start next
		  disp (get-text-property start 'display))))
	(set-mouse-pixel-position
	 (car posn)
	 (truncate (+ len (cdr w3m-tab-mouse-position-adjuster)))
	 (cddr posn))
	(when decelerate
	  (sleep-for 0.1))
	(discard-input)))))

(defun w3m-tab-next-buffer (&optional n event)
  "Turn N pages of emacs-w3m buffers ahead."
  (interactive (list (prefix-numeric-value current-prefix-arg)
		     last-command-event))
  (unless n (setq n 1))
  (when (and (/= n 0) (eq major-mode 'w3m-mode))
    (let ((buffers (w3m-list-buffers)))
      (switch-to-buffer
       (nth (mod (+ n (w3m-buffer-number (current-buffer)) -1)
		 (length buffers))
	    buffers))
      (run-hooks 'w3m-select-buffer-hook)
      (w3m-select-buffer-update)
      (w3m-tab-mouse-track-selected-tab
       event (w3m-buffer-number (current-buffer))))))

(defun w3m-tab-previous-buffer (&optional n event)
  "Turn N pages of emacs-w3m buffers behind."
  (interactive (list (prefix-numeric-value current-prefix-arg)
		     last-command-event))
  (w3m-tab-next-buffer (- (or n 1)) event))

(defun w3m-tab-move-right (&optional n event)
  "Move this tab N times to the right (to the left if N is negative)."
  (interactive (list (prefix-numeric-value current-prefix-arg)
		     last-command-event))
  (unless n (setq n 1))
  (when (and (/= n 0) (eq major-mode 'w3m-mode))
    (let* ((buffers (if (> n 0)
			(w3m-list-buffers)
		      (setq n (- n))
		      (nreverse (w3m-list-buffers))))
	   (dest (or (nth n (memq (current-buffer) buffers))
		     (car (last buffers))))
	   (next (w3m-buffer-number dest))
	   (cur (w3m-buffer-number (current-buffer)))
	   e posn start)
      (rename-buffer "*w3m*<0>")
      (w3m-buffer-set-number dest cur)
      (w3m-buffer-set-number (current-buffer) next)
      (w3m-select-buffer-update)
      (w3m-tab-mouse-track-selected-tab event next t))))

(defun w3m-tab-move-left (&optional n event)
  "Move this tab N times to the left (to the right if N is negative)."
  (interactive (list (prefix-numeric-value current-prefix-arg)
		     last-command-event))
  (w3m-tab-move-right (- n) event))

(defvar w3m-tab-map nil)
(make-variable-buffer-local 'w3m-tab-map)

(defvar w3m-tab-spinner-map nil)
(make-variable-buffer-local 'w3m-tab-spinner-map)

(defun w3m-tab-make-keymap ()
  (unless w3m-tab-map
    (setq w3m-tab-map (make-sparse-keymap))
    (let* ((cur (current-buffer))
	   (f1 (lambda (fn) `(lambda (e) (interactive "e") (,fn e ,cur))))
	   (f2 (lambda (fn) `(lambda (e)
			       (interactive "e")
			       (select-window (posn-window (event-start e)))
			       (switch-to-buffer ,cur)
			       (setq this-command ',fn)
			       (,fn 1 e))))
	   (drag-action (funcall f1 'w3m-tab-drag-mouse-function))
	   (single-action (funcall f1 'w3m-tab-click-mouse-function))
	   (double-action1 (funcall f1 'w3m-tab-double-click-mouse1-function))
	   (double-action2 (funcall f1 'w3m-tab-double-click-mouse2-function))
	   (menu-action (funcall f1 'w3m-tab-button-menu))
	   (menu-action2 (funcall f1 'w3m-tab-button-menu2))
	   (next-buffer-action (funcall f2 'w3m-tab-next-buffer))
	   (previous-buffer-action (funcall f2 'w3m-tab-previous-buffer))
	   (move-left-action (funcall f2 'w3m-tab-move-left))
	   (move-right-action (funcall f2 'w3m-tab-move-right)))
      (define-key w3m-tab-map [header-line down-mouse-1] 'ignore)
      (define-key w3m-tab-map [header-line down-mouse-2] 'ignore)
      (define-key w3m-tab-map [header-line mouse-1] single-action)
      (define-key w3m-tab-map [header-line mouse-2] single-action)
      (define-key w3m-tab-map [header-line drag-mouse-1] drag-action)
      (define-key w3m-tab-map [header-line drag-mouse-2] drag-action)
      (define-key w3m-tab-map [header-line double-mouse-1] double-action1)
      (define-key w3m-tab-map [header-line double-mouse-2] double-action2)
      (define-key w3m-tab-map [header-line mouse-3] menu-action)
      (define-key w3m-tab-map [header-line wheel-up] previous-buffer-action)
      (define-key w3m-tab-map [header-line wheel-down] next-buffer-action)
      (define-key w3m-tab-map [header-line mouse-4] previous-buffer-action)
      (define-key w3m-tab-map [header-line mouse-5] next-buffer-action)
      (define-key w3m-tab-map [header-line C-wheel-up] move-left-action)
      (define-key w3m-tab-map [header-line C-wheel-down] move-right-action)
      (define-key w3m-tab-map [header-line C-mouse-4] move-left-action)
      (define-key w3m-tab-map [header-line C-mouse-5] move-right-action)
      (define-key w3m-mode-map [header-line double-mouse-1]
	'w3m-goto-new-session-url)
      (define-key w3m-mode-map [header-line mouse-3] menu-action2)
      ;; The following bindings in `w3m-mode-map', not `w3m-tab-map',
      ;; are required for some platforms, in which mouse wheel events
      ;; sometimes pass by `w3m-tab-map' for the unresolved reason and
      ;; see `w3m-mode-map', or else the `undefined' errors will arise.
      (define-key w3m-mode-map [header-line mouse-4] 'w3m-tab-previous-buffer)
      (define-key w3m-mode-map [header-line mouse-5] 'w3m-tab-next-buffer)
      (define-key w3m-mode-map [header-line wheel-up] 'w3m-tab-previous-buffer)
      (define-key w3m-mode-map [header-line wheel-down] 'w3m-tab-next-buffer)
      (define-key w3m-mode-map [header-line C-wheel-up] 'w3m-tab-move-left)
      (define-key w3m-mode-map [header-line C-wheel-down] 'w3m-tab-move-right)
      (define-key w3m-mode-map [header-line C-mouse-4] 'w3m-tab-move-left)
      (define-key w3m-mode-map [header-line C-mouse-5] 'w3m-tab-move-right))
    (unless w3m-tab-spinner-map
      (setq w3m-tab-spinner-map (make-sparse-keymap))
      (define-key w3m-tab-spinner-map [header-line mouse-2]
	`(lambda (e)
	   (interactive "e")
	   (save-current-buffer
	     ;; Why the `(w3m-process-stop BUFFER)' doesn't work?
	     (set-buffer ,(current-buffer))
	     (call-interactively 'w3m-process-stop)))))))

(defvar w3m-tab-half-space
  (propertize " " 'display '(space :width 0.5))
  "The space of half width.")

(defvar w3m-tab-separator-map nil)

(unless w3m-tab-separator-map
  (let ((map (make-sparse-keymap)))
    (setq w3m-tab-separator-map map)
    (define-key map [header-line wheel-up] 'w3m-tab-previous-buffer)
    (define-key map [header-line wheel-down] 'w3m-tab-next-buffer)
    (define-key map [header-line mouse-4] 'w3m-tab-previous-buffer)
    (define-key map [header-line mouse-5] 'w3m-tab-next-buffer)
    (define-key map [header-line C-wheel-up] 'w3m-tab-move-left)
    (define-key map [header-line C-wheel-down] 'w3m-tab-move-right)
    (define-key map [header-line C-mouse-4] 'w3m-tab-move-left)
    (define-key map [header-line C-mouse-5] 'w3m-tab-move-right)))

(defvar w3m-tab-separator
  (propertize " "
	      'face (list 'w3m-tab-background)
	      'mouse-face 'w3m-tab-selected-background
	      'display '(space :width 0.5)
	      'tab-separator t
	      'local-map w3m-tab-separator-map)
  "String used to separate tabs.")

(defun w3m-tab-line ()
  (let* ((current (current-buffer))
	 (buffers (w3m-list-buffers))
	 (breadth 1)
	 (number 0)
	 (fringes (window-fringes))
	 (width (+ (window-width)
		   (/ (float (+ (or (car fringes) 0)
				(or (nth 1 fringes) 0)))
		      (frame-char-width))
		   ;; Assume that the vertical scroll-bar has
		   ;; the width of two space characters.
		   (if (car (frame-current-scroll-bars)) 2 0)))
	 (nbuf (length buffers))
	 (graphic (and window-system
		       w3m-show-graphic-icons-in-header-line))
	 (margin (if window-system
		     (+ (if graphic 3.0 0.5)
			;; Right and left shadows.
			(/ 2.0 (frame-char-width)))
		   1))
	 (spinner (when w3m-process-queue
		    (w3m-make-spinner-image)))
	 buffer title data datum process unseen favicon keymap face icon
	 line)
    (save-current-buffer
      (while buffers
	(set-buffer (setq buffer (pop buffers)))
	(setq number (1+ number))
	(setq title (if w3m-add-tab-number
			(format "%d.%s" number (w3m-current-title))
		      (w3m-current-title)))
	(setq breadth
	      (max breadth
		   ;; There may be a wide character in the beginning of
		   ;; the title.
		   (if (> (length title) 0)
		       (char-width (aref title 0))
		     0)))
	(push (list (eq current buffer)
		    w3m-current-process
		    (w3m-unseen-buffer-p buffer)
		    title
		    (when w3m-use-favicon w3m-favicon-image)
		    w3m-tab-map)
	      data)))
    (setq width (if (> (* nbuf (+ margin w3m-tab-width)) width)
		    (max (truncate (- (/ width nbuf) margin)) breadth)
		  w3m-tab-width))
    (while data
      (setq datum (pop data)
	    current (car datum)
	    process (nth 1 datum)
	    unseen (nth 2 datum)
	    title (nth 3 datum)
	    favicon (nth 4 datum)
	    keymap (nth 5 datum)
	    face (list
		  (if process
		      (if current
			  'w3m-tab-selected-retrieving
			'w3m-tab-unselected-retrieving)
		    (if current
			'w3m-tab-selected
		      (if unseen
			  'w3m-tab-unselected-unseen
			'w3m-tab-unselected))))
	    icon (when graphic
		   (cond
		    (process
		     (when spinner
		       (propertize
			" "
			'display spinner
			'face face
			'local-map w3m-tab-spinner-map
			'help-echo w3m-spinner-map-help-echo)))
		    (favicon
		     (propertize
		      " "
		      'display favicon
		      'face face
		      'local-map keymap
		      'help-echo title))))
	    breadth (cond (icon width)
			  (graphic (+ 2 width))
			  (t width)))
      (push
       (list
	icon
	(propertize
	 (concat
	  (when graphic w3m-tab-half-space)
	  (replace-regexp-in-string
	   "%" "%%"
	   (if (and (> (string-width title) breadth)
		    (> breadth 6))
	       (truncate-string-to-width
		(concat (truncate-string-to-width title (- breadth 3))
			"...")
		breadth nil ?.)
	     (truncate-string-to-width title breadth nil ?\ ))))
	 'face face
	 'mouse-face 'w3m-tab-mouse
	 'local-map keymap
	 'help-echo title)
	w3m-tab-separator)
       line))
    (concat (apply 'concat (apply 'nconc line))
	    (propertize (make-string (window-width) ?\ )
			'face (list 'w3m-tab-background)
			'mouse-face 'w3m-tab-selected-background
			'local-map w3m-tab-separator-map))))

(add-hook 'w3m-mode-setup-functions 'w3m-tab-make-keymap)
(add-hook 'w3m-mode-setup-functions 'w3m-setup-header-line)
(add-hook 'w3m-mode-setup-functions 'w3m-setup-widget-faces)
(add-hook 'w3m-select-buffer-hook 'w3m-force-window-update)

;; Graphic icons.
(defcustom w3m-space-before-modeline-icon ""
  "String of space character(s) to be put in front of the mode-line icon.
It may be better to use one or more spaces if you are using oblique or
italic font in the modeline."
  :group 'w3m
  :type 'string)

(defvar w3m-spinner-image-file nil
  "Image file used to show a spinner in the header-line.")

(defvar w3m-spinner-image-frames 3
  "Number of frames which the spinner image contains.")

(defvar w3m-spinner-image-index 0
  "Counter used to rotate spinner images.  This is a buffer-local variable.")
(make-variable-buffer-local 'w3m-spinner-image-index)

;; Images to be displayed in the modeline.
(defvar w3m-modeline-process-status-on-icon nil)
(defvar w3m-modeline-image-status-on-icon nil)
(defvar w3m-modeline-status-off-icon nil)
(defvar w3m-modeline-ssl-image-status-on-icon nil)
(defvar w3m-modeline-ssl-status-off-icon nil)

(defun w3m-initialize-graphic-icons (&optional force)
  "Make icon images which will be displayed in the mode-line."
  (interactive "P")
  (when (or (image-type-available-p 'xpm)
	    (image-type-available-p 'png))
    ;; Prefer xpm icons rather than png icons since Emacs doesn't display
    ;; background colors of icon images other than xpm images transparently
    ;; in the mode line.
    (let* ((w3m-toolbar-icon-preferred-image-types
	    (if (image-type-available-p 'xpm)
		'(xpm)
	      '(png)))
	   (defs `((w3m-modeline-status-off-icon
		    ,(w3m-find-image "state-00")
		    w3m-modeline-status-off)
		   (w3m-modeline-image-status-on-icon
		    ,(w3m-find-image "state-01")
		    w3m-modeline-image-status-on)
		   (w3m-modeline-ssl-status-off-icon
		    ,(w3m-find-image "state-10")
		    w3m-modeline-ssl-status-off)
		   (w3m-modeline-ssl-image-status-on-icon
		    ,(w3m-find-image "state-11")
		    w3m-modeline-ssl-image-status-on)))
	   def icon file type status keymap)
      (while defs
	(setq def (car defs)
	      defs (cdr defs)
	      icon (car def)
	      file (car (nth 1 def))
	      type (cdr (nth 1 def))
	      status (nth 2 def))
	(if (and w3m-show-graphic-icons-in-mode-line file)
	    (progn
	      (when (or force (not (symbol-value icon)))
		(unless keymap
		  (setq keymap
			(make-mode-line-mouse-map 'mouse-2
						  'w3m-reload-this-page)))
		(set icon (propertize
			   "  "
			   'display (create-image file type nil
						  :ascent 'center)
			   'local-map keymap
			   'mouse-face 'mode-line-highlight
			   'help-echo "mouse-2 reloads this page"))
		(put icon 'risky-local-variable t)
		(put status 'risky-local-variable t))
	      (when (stringp (symbol-value status))
		;; Save the original status strings as properties.
		(put status 'string (symbol-value status)))
	      (set status (list "" 'w3m-space-before-modeline-icon icon)))
	  ;; Don't use graphic icons.
	  (when (get status 'string)
	    (set status (get status 'string)))))))
    (let (file)
      ;; Spinner
      (when (and (or force (not w3m-spinner-image-file))
		 (image-type-available-p 'gif)
		 w3m-icon-directory
		 (file-directory-p w3m-icon-directory)
		 (file-exists-p
		  (setq file (expand-file-name "spinner.gif"
					       w3m-icon-directory))))
	(setq w3m-spinner-image-file file)
	(define-key (setq w3m-modeline-spinner-map (make-sparse-keymap))
	  [mode-line mouse-2]
	  'w3m-process-stop)
	(put 'w3m-modeline-process-status-on 'risky-local-variable t)
	(put 'w3m-modeline-process-status-on-icon 'risky-local-variable t))
      (if (and window-system
	       w3m-show-graphic-icons-in-mode-line
	       w3m-spinner-image-file)
	  (progn
	    (when (stringp w3m-modeline-process-status-on)
	      ;; Save the original status strings as properties.
	      (put 'w3m-modeline-process-status-on 'string
		   w3m-modeline-process-status-on))
	    (setq w3m-modeline-process-status-on
		  '(""
		    w3m-space-before-modeline-icon
		    w3m-modeline-process-status-on-icon)))
	(when (get 'w3m-modeline-process-status-on 'string)
	  (setq w3m-modeline-process-status-on
		(get 'w3m-modeline-process-status-on 'string))))))

(defun w3m-make-spinner-image ()
  "Make an image used to show a spinner.
It should be called periodically in order to spin the spinner."
  (when w3m-spinner-image-file
    (unless (< (incf w3m-spinner-image-index) w3m-spinner-image-frames)
      (setq w3m-spinner-image-index 0))
    (let ((image (create-image w3m-spinner-image-file 'gif nil
			       :ascent 'center :mask 'heuristic
			       :index w3m-spinner-image-index)))
      (setq w3m-modeline-process-status-on-icon
	    (propertize "  "
			'display image
			'local-map w3m-modeline-spinner-map
			'help-echo w3m-spinner-map-help-echo))
      image)))

(defun w3m-form-coding-system-accept-region-p (&optional from to coding-system)
  "Check whether `coding-system' can encode specified region."
  (let ((from (or from (point-min)))
	(to (or to   (point-max)))
	(coding-system (or coding-system
			   w3m-form-input-textarea-coding-system)))
    (if (fboundp 'unencodable-char-position)
	(let ((pos (unencodable-char-position from to coding-system)))
	  (or (not pos)
	      (y-or-n-p (format "\"%c\" would not be accepted. Continue? "
				(char-after pos)))))
      (let ((select-safe-coding-system-accept-default-p nil))
	(or (eq (select-safe-coding-system from to coding-system)
		coding-system)
	    (y-or-n-p
	     "This text may cause coding-system problem. Continue? "))))))

(provide 'w3m-ems)

;;; w3m-ems.el ends here