Source

xwem / lisp / xwem-keyboard.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
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
;;; xwem-keyboard.el --- Keyboard support for XWEM.

;; Copyright (C) 2003 by Free Software Foundation, Inc.

;; Authors: Zajcev Evgeny <zevlg@yandex.ru>
;;	    Alex Ott <ottalex@narod.ru>
;; Created: 21 Mar 2003
;; Keywords: xwem, xlib
;; X-CVS: $Id$

;; This file is part of XWEM.

;; XWEM 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.

;; XWEM 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 XEmacs; see the file COPYING.  If not, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
;; 02111-1307, USA.

;;; Synched up with: Not in FSF

;;; Commentary:
;;
;; `xwem-global-map' is normal keymap used by xwem.
;;
;; Set `xwem-keyboard-echo-keystrokes' to t if you want echoing of
;; incomplete commands in echo area.

;;; Code:


(eval-when-compile
  (require 'xwem-clients))
(require 'xlib-xtest)
(require 'xwem-compat)

;;{{{ [-] Custamizable xwem-keyboard group

;;; Customize variables
(defgroup xwem-keyboard nil
  "Group to customize keyboard in XWEM."
  :prefix "xwem-"
  :group 'xwem)

(defcustom xwem-pre-command-hook nil
  "*Hooks to run just before executing command.
This may examine `xwem-this-command' variable to find out which
command is about to be run, or may change it to cause a different
command to run."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

(defcustom xwem-post-command-hook nil
  "*Hooks to run after command execution."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

(defcustom xwem-keyboard-echo-keystrokes t
  "*If non-nil than echo unfinished commands in echo area."
  :type 'boolean
  :group 'xwem-keyboard)

(defcustom xwem-hyper-modifier 'hyper
  "*This is a little trick of how ``H'' interpretted in `xwem-kbd' specification."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)

(defcustom xwem-meta-modifier 'meta
  "*This is a little trick of how ``M'' interpretted in `xwem-kbd' specification."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)
		 
(defcustom xwem-control-modifier 'control
  "*This is a little trick of how ``C'' interpretted in `xwem-kbd'."
  :type '(choice (const :tag "Meta" meta)
		 (const :tag "Control" control)
		 (const :tag "Super" super)
		 (const :tag "Hyper" hyper))
  :group 'xwem-keyboard)

(defcustom xwem-kbd-evillocks (list XK-NumLock XK-Caps-Lock)
  "List of evil locks."
  :type `(repeat (choice (const :tag "NumLock" ,XK-NumLock)
                         (const :tag "CapsLock" ,XK-Caps-Lock)
                         ;; TODO: add others .. which?
                         ))
  :group 'xwem-keyboard)

(defvar xwem-kbd-evilmasks (list 0)
  "List of evil masks.
Internal variable, DO NOT MODIFY.")

(defcustom xwem-quit-key [(hyper ?g)]
  "Quit command key."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-quit-command 'xwem-keyboard-quit
  "Default command to be called when `xwem-quit-key' pressed."
  :type 'function
  :group 'xwem-keyboard)

(defcustom xwem-help-key [(hyper ?h)]
  "Help command key."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-prefix-help-command 'xwem-describe-prefix-bindings
  "Default command to be called when `xwem-help-key' pressed."
  :type 'function
  :group 'xwem-keys)

(defcustom xwem-universal-key [(hyper ?u)]
  "Key for universal argument commands."
  :type 'sexp
  :group 'xwem-keyboard)

(defcustom xwem-kbd-quit-hook nil
  "*Hooks to be runned when KBD exits.
Runned only on \\<xwem-global-map>\\[xwem-kbd-quit], but not on
\\<xwem-global-map>\\[xwem-keyboard-quit]."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

;;}}}

;;{{{ [-] Internal variables

;;;###autoload
(defvar xwem-override-global-map nil
  "Keymap that overrides only `xwem-global-map'.
But can't override `xwem-kbd-private-prefix-map'!
You should *bind* this, not set it.")

;;;###autoload
(defvar xwem-override-map nil
  "Keymap that overrides all other keymaps.
But can't override `xwem-kbd-private-prefix-map'!
You should *bind* this, not set it.")

;;;###autoload
(defvar xwem-kbd-now-grabbing nil
  "Non-nil indicates that we now grabbing keyboard.
Internal variable, do not modify.")

(defvar xwem-xkeys-mapping nil
  "X KeyMapping fetched from X server.
Internal variable, do not modify.")

(defvar xwem-kbd-private-modifiers (make-vector 7 nil)
  "Private modifers [shift lock control meta hyper super numlocks].
Internal variable, do not modify.")

(defvar xwem-xmods-mapping nil
  "X ModifierMapping fetched from X server.
Internal variable, do not modify.")

;;;###autoload
(defvar xwem-event-window nil "Window that receive last keypress event.")
;;;###autoload
(defvar xwem-last-event nil "Last keypress event.")
;;;###autoload
(defvar xwem-last-xevent nil "Last keypress/buttonpress X Event.")
;;;###autoload
(defvar xwem-this-command-keys [] "List of pressed keys to execute command.")
;;;###autoload
(defvar xwem-this-command nil "The command now being executed.")
;;;###autoload
(defvar xwem-last-command nil "The last command executed.")

;; Private variables
(defvar xwem-kbd-private-prefix-map nil
  "Private variable holds prefix keymap or symbol that holds keymap.
Internal variable, do not modify.")

(defvar xwem-kbd-last-prefix-map nil "Last value of `xwem-kbd-private-prefix-map'.")

;; Special modes for reading key or keysequence
(defvar xwem-kbd-reading-key nil
  "Non-nil mean we are reading for key.
Actually references symbol to which save readed key.
Internal variable, do not modify.")

(defvar xwem-kbd-reading-keyseq nil
 "Non-nil mean we are reading key sequence.
Actually references symbol to which save readed key sequence.
Internal variable, do not modify.")

;;}}}


;;{{{ [-] Reading key and keysequence

(defvar xwem-saved-this-command-keys nil
  "Saved value of `xwem-this-command-keys'.")

;;;###autoload
(defun xwem-kbd (spec)
  "Just like `kbd' but take into account values of `xwem-hyper-modifier' and `xwem-meta-modifier'."
  (let ((keys (key-sequence-list-description (kbd spec))))
    (mapvector (lambda (key)
		 (let ((rkey (last key))
		       (rmods (butlast key)))
		   (when (member 'meta key)
		     (setq rmods (delete 'meta rmods))
		     (setq rkey (cons xwem-meta-modifier rkey)))
		   (when (member 'hyper key)
		     (setq rmods (delete 'hyper rmods))
		     (setq rkey (cons xwem-hyper-modifier rkey)))
                   (when (member 'control key)
                     (setq rmods (delete 'control rmods))
                     (setq rkey (cons xwem-control-modifier rkey)))

		   (when rmods
		     (setq rkey (nconc rmods rkey)))
		   rkey))
	       keys)))

(defun xwem-read-keys-start (keyseq-p keyvar)
  "Start reading key or key sequence.
KEYSEQ-P is non-nil when staring reading key sequence.
KEYVAR is place where to store readed key or key sequence."
  (xwem-kbd-start-grabbing)

  (setq xwem-saved-this-command-keys xwem-this-command-keys)
  (setq xwem-this-command-keys [])
  (if keyseq-p
      (setq xwem-kbd-reading-keyseq keyvar)
    (setq xwem-kbd-reading-key keyvar))

  (xwem-recursive-edit))

(defun xwem-read-keys-stop (keyseq-p)
  "Stop reading key or key sequence.
If KEYSEQ-P is non-nil than stop reading key sequence."
  (set (if keyseq-p xwem-kbd-reading-keyseq xwem-kbd-reading-key)
       xwem-this-command-keys)
  (if keyseq-p
    (setq xwem-kbd-reading-keyseq nil)
    (setq xwem-kbd-reading-key nil))

  (xwem-kbd-set-current-prefix-keymap nil)
  (setq xwem-this-command-keys xwem-saved-this-command-keys)

  (xwem-exit-recursive-edit))

;; Read key, install active grab
;;;###autoload
(defun xwem-read-key (&optional prompt no-minib-focus-p)
  "Read single key press, prompting PROMPT in `xwem-minibuffer'.
If NO-MINIB-FOCUS-P is non-nil, focus `xwem-minibuffer' while reading."
  (let ((xwem-keyboard-echo-keystrokes t)
	key)

    (when prompt
      (xwem-message 'msg prompt))

    (if no-minib-focus-p
	(xwem-read-keys-start nil 'key)

      (xwem-under-minib-focus
       (xwem-read-keys-start nil 'key)))

    (aref key 0)))

;; Read keysequence which binds to command
;;;###autoload
(defun xwem-read-key-sequence (&optional prompt)
  "Read key sequence that call command prompting PROMPT."
  (let ((xwem-keyboard-echo-keystrokes t)
	keys)
    (xwem-under-minib-focus
     (when prompt
       (xwem-message 'msg prompt))

     (xwem-read-keys-start t 'keys))
    keys))

;;}}}

;;{{{ [-] Defining new key

;;;###autoload
(defun xwem-define-key (win keymap key command)
  "Add KEY to KEYMAP to execute COMMAND and grab KEY on WIN.
When command is `nil', then undefine KEY in KEYMAP and ungrab KEY."
  (define-key keymap key command)
  (xwem-kbd-graugra-key key win (if command 'grab 'ungrab)))

;;;###autoload
(defun xwem-global-set-key (key command)
  "Define KEY to call COMMAND, when xwem is already run.
If command is `nil' then undefine KEY in `xwem-global-map' and ungrab KEY."
  (define-key xwem-global-map key command)
  (mapc (lambda (frm)
	  (xwem-kbd-graugra-key key (xwem-frame-xwin frm)
				(if command 'grab 'ungrab)))
	xwem-frames-list))

;;}}}

;;{{{ [-] local keymap

;;;###autoload
(defun xwem-local-map (cl)
  "Return local map for CL."
  (and (xwem-cl-p cl) (xwem-cl-get-prop cl 'xwem-local-keymap)))

;;;###autoload
(defun xwem-local-set-key (key command &optional cl)
  "Set KEY to call COMMAND in CL's local keymap.
If COMMAND is `nil' then undefine KEY in CL's local map and ungrab KEY.
If CL is ommited `xwem-cl-selected' assumed."
  (let* ((ccl (or cl (xwem-cl-selected)))
         (kmap (xwem-local-map ccl)))

    (unless (keymapp kmap)
      ;; Create new local keymap for client
      (setq kmap (make-sparse-keymap))
      (set-keymap-parents kmap (list xwem-global-map))
      (xwem-cl-put-prop ccl 'xwem-local-keymap kmap))

    (define-key kmap key command)
    (xwem-kbd-graugra-key key (xwem-cl-xwin ccl)
                          (if command 'grab 'ungrab))))

;;}}}

;;{{{ [-] Undefined command processing

;;;###autoload(autoload 'xwem-undefined-command "xwem-keyboard" "" t)
(define-xwem-command xwem-undefined-command ()
  "Called when key is not binded."
  (xwem-interactive)
  (xwem-message 'warn "Command undefined for key %S." xwem-last-event))

;;;###autoload(autoload 'xwem-self-insert-or-undefined "xwem-keyboard" "" t)
(define-xwem-command xwem-self-insert-or-undefined (arg)
  "Self insert or undefined command.
Prefix ARG specifies how many characters to insert."
  (xwem-interactive "*_p")
  
  (let ((lev xwem-last-event))
    ;; TODO:
    ;;   * Check is LEV is actually self insertable event
    (if arg
	(xwem-key-send-ekeys (make-vector arg lev))
      
      (xwem-message 'warn "%s is not defined, prefix arg is %S."
		    (key-description xwem-this-command-keys) arg)
    )))

;;}}}

;;{{{ [-] Quiting keyboarding

;;;###autoload(autoload 'xwem-keyboard-quit "xwem-keyboard" "" t)
(define-xwem-command xwem-keyboard-quit ()
  "Send quit signal."
  (xwem-interactive)
  
  (signal 'quit '(xwem))
  (xwem-message 'info "quit."))

;;;###autoload(autoload 'xwem-kbd-quit "xwem-keyboard" "" t)
(define-xwem-command xwem-kbd-quit ()
  "Quit from keyboard haldling."
  (xwem-interactive)

  (xwem-kbd-stop-grabbing)
  (setq xwem-kbd-private-prefix-map nil)
  (XSetInputFocus (xwem-dpy) X-PointerRoot X-RevertToPointerRoot X-CurrentTime)
  (xwem-message 'note "[kbd-quit] InputFocus is PonterRoot, prfxmap is nil.")

  (run-hooks 'xwem-kbd-quit-hook)
  )

;;}}}

;;{{{ [-] Initializators

(defun xwem-kbd-initialize-private-modifiers ()
  "Create internal modifier representation to speedup futher work.
Also update `xwem-kbd-evilmasks' if `xwem-kbd-evillocks' is non-nil."
  (setq xwem-kbd-private-modifiers (make-vector 7 nil))
  (let* ((ctrls (list (car (xwem-kbd-xksym->xkcode XK-Control-L))
		      (car (xwem-kbd-xksym->xkcode XK-Control-R))))
         (locks (list (car (xwem-kbd-xksym->xkcode XK-Caps-Lock))))
	 (shifts (list (car (xwem-kbd-xksym->xkcode XK-Shift-L))
		       (car (xwem-kbd-xksym->xkcode XK-Shift-R))))
	 (metas (list (car (xwem-kbd-xksym->xkcode XK-Meta-L))
		      (car (xwem-kbd-xksym->xkcode XK-Meta-R))))
	 (hypers (list (car (xwem-kbd-xksym->xkcode XK-Hyper-L))
		       (car (xwem-kbd-xksym->xkcode XK-Hyper-R))))
	 (supers (list (car (xwem-kbd-xksym->xkcode XK-Super-L))
		       (car (xwem-kbd-xksym->xkcode XK-Super-R))))
         (numlocks (list (car (xwem-kbd-xksym->xkcode XK-NumLock))))
         (evils (mapcar (lambda (ks)
                          (car (xwem-kbd-xksym->xkcode ks))) xwem-kbd-evillocks))
	 (mlist (mapcar 'truncate (list X-Shift X-Lock X-Control X-Mod1 X-Mod2
                                        X-Mod3 X-Mod4 X-Mod5)))
	 (slist (car (last xwem-xmods-mapping))))
    
    (while slist
      ;; Update some private modifier mask
      (when (intersection (car slist) shifts)
	(aset xwem-kbd-private-modifiers 0 (cons (car mlist) (aref xwem-kbd-private-modifiers 0))))
      (when (intersection (car slist) locks)
	(aset xwem-kbd-private-modifiers 1 (cons (car mlist) (aref xwem-kbd-private-modifiers 1))))
      (when (intersection (car slist) ctrls)
	(aset xwem-kbd-private-modifiers 2 (cons (car mlist) (aref xwem-kbd-private-modifiers 2))))
      (when (intersection (car slist) metas)
	(aset xwem-kbd-private-modifiers 3 (cons (car mlist) (aref xwem-kbd-private-modifiers 3))))
      (when (intersection (car slist) hypers)
	(aset xwem-kbd-private-modifiers 4 (cons (car mlist) (aref xwem-kbd-private-modifiers 4))))
      (when (intersection (car slist) supers)
	(aset xwem-kbd-private-modifiers 5 (cons (car mlist) (aref xwem-kbd-private-modifiers 5))))
      (when (intersection (car slist) numlocks)
	(aset xwem-kbd-private-modifiers 6 (cons (car mlist) (aref xwem-kbd-private-modifiers 6))))

      ;; Update Evil locks
      (when (intersection (car slist) evils)
        (push (car mlist) xwem-kbd-evilmasks))

      (setq slist (cdr slist))
      (setq mlist (cdr mlist)))))

;;;###autoload
(defun xwem-kbd-init ()
  "Init part for keys.
Fetches KeyboardMapping from the X server and stores it in
`xwem-xkeys-mapping'"
  (xwem-message 'msg "Initializing keyboard ... wait")
  (xwem-kbd-set-current-prefix-keymap nil)

  ;; Hmm FSFmacs issued "invalid instraction" in `XGetKeyboardMapping'
  (setq xwem-xkeys-mapping
 	(XGetKeyboardMapping (xwem-dpy)
 			     (X-Dpy-min-keycode (xwem-dpy))
 			     (- (X-Dpy-max-keycode (xwem-dpy))
				(X-Dpy-min-keycode (xwem-dpy)))))

  (setq xwem-xmods-mapping
	(XGetModifierMapping (xwem-dpy)))

  ;; Initialize `xwem-kbd-private-modifiers'
  (xwem-kbd-initialize-private-modifiers)

  ;; Initialize keyboard macrosing
  (xwem-keymacro-init)
  )

;;}}}

;;{{{ [-] Converters

;; Convertors
(defun xwem-kbd-xksym->emacs (ksym)
  "Convert KSYM to Emacs key symbol."
  (cond
   ;; ksym is list for buttons
   ((listp ksym)
    (let ((kval (car ksym)))
      (cond ((= kval 1) 'button1)
	    ((= kval 2) 'button2)
	    ((= kval 3) 'button3)
	    ((= kval 4) 'button4)
	    ((= kval 5) 'button5)
	    (t nil))))			;can't be!!!

   ((= ksym XK-BackSpace) 'backspace)
   ((= ksym XK-Tab) 'tab)
   ((= ksym XK-Linefeed) 'linefeed)
   ((= ksym XK-Return) 'return)
   ((= ksym XK-Escape) 'escape)
   ((= ksym XK-Delete) 'delete)

   ((= ksym XK-Home) 'home)
   ((= ksym XK-End) 'end)
   ((= ksym XK-Left) 'left)
   ((= ksym XK-Right) 'right)
   ((= ksym XK-Up) 'up)
   ((= ksym XK-Down) 'down)

   ((= ksym XK-Insert) 'insert)
   ((= ksym XK-Pause) 'pause)
   ((= ksym XK-Space) 'space)
   ;; TODO: add more

   ((= ksym XK-F1) 'f1)
   ((= ksym XK-F2) 'f2)
   ((= ksym XK-F3) 'f3)
   ((= ksym XK-F4) 'f4)
   ((= ksym XK-F5) 'f5)
   ((= ksym XK-F6) 'f6)
   ((= ksym XK-F7) 'f7)
   ((= ksym XK-F8) 'f8)
   ((= ksym XK-F9) 'f9)
   ((= ksym XK-F10) 'f10)
   ((= ksym XK-F11) 'f11)
   ((= ksym XK-F12) 'f12)

   ((= ksym 0) nil)

   (t (XCharacter ksym))))		;nil or proper character

(defun xwem-kbd-emacs->xksym (ksym)
  "Convert back from Emacs key symbol KSYM to proper X key symbol."
  (cond ((null ksym) 0)			;hmm

	((symbolp ksym)
	 (let ((osymname (symbol-name ksym))
	       (symname (downcase (symbol-name ksym))))
	   (cond ((string= symname "backspace") XK-BackSpace)
		 ((string= symname "tab") XK-Tab)
		 ((string= symname "linefeed") XK-Return) ;XXX
		 ((string= symname "linefeed") XK-Linefeed)
		 ((string= symname "return") XK-Return)
		 ((string= symname "escape") XK-Escape)
		 ((string= symname "delete") XK-Delete)
		 ((string= symname "space") XK-Space)

		 ((string= symname "home") XK-Home)
		 ((string= symname "end") XK-End)
		 ((string= symname "left") XK-Left)
		 ((string= symname "right") XK-Right)
		 ((string= symname "up") XK-Up)
		 ((string= symname "down") XK-Down)

		 ((string= symname "insert") XK-Insert)
		 ((string= symname "pause") XK-Pause)

		 ;; Mouse buttons
		 ((string= symname "button1") (list X-XButton1))
		 ((string= symname "button2") (list X-XButton2))
		 ((string= symname "button3") (list X-XButton3))
		 ((string= symname "button4") (list X-XButton4))
		 ((string= symname "button5") (list X-XButton5))

		 ;; Functional keys
		 ((string-match "[fF]\\([0-9]+\\)" symname)
		  (symbol-value
		   (intern
		    (concat "XK-F"
			    (substring symname (match-beginning 1)
				       (match-end 1))))))

		 (t (Xforcenum (string-to-char osymname))))))

	((characterp ksym) (Xforcenum ksym)) ;Should not be there

	(t 0)))				;HMM!

(defun xwem-kbd-emods->xmodmask (emods)
  "Convert Emacs modifiers list EMODS to X modifers mask."
  (Xmask-or
   (if (member 'control emods) (xwem-kbd-controlmask) 0)
   (if (member 'shift emods) (xwem-kbd-shiftmask) 0)
   (if (member 'meta emods) (xwem-kbd-metamask) 0)
   (if (member 'hyper emods) (xwem-kbd-hypermask) 0)
   (if (member 'super emods) (xwem-kbd-supermask) 0)))

(defun xwem-kbd-xmodmask->emods (mmask)
  "Convert X modifiers mask MMASK to Emacs modifiers list."
  (let (rmods)
    (when (Xtest mmask (xwem-kbd-controlmask))
      (push 'control rmods))
    (when (Xtest mmask (xwem-kbd-shiftmask))
      (push 'shift rmods))
    (when (Xtest mmask (xwem-kbd-hypermask))
      (push 'hyper rmods))
    (when (Xtest mmask (xwem-kbd-metamask))
      (push 'meta rmods))
    (when (Xtest mmask (xwem-kbd-supermask))
      (push 'super rmods))
    rmods))

;; keysyms and keycodes converters
(defun xwem-kbd-xksym->xkcode (ksym)
  "Convert keysym KSYM to keycode.
Convert keysym to cons cell where car is keycode and cdr is modifiers
list, using `xwem-xkeys-mapping' list.
NOTE: only 'shift modifier supported."
  (setq ksym (float ksym))		; for sure
  (let ((kslist (car (last xwem-xkeys-mapping)))
	(kcode (X-Dpy-min-keycode (xwem-dpy)))
	(kmods nil)
	kel)

    (while kslist
      (setq kel (car kslist))
      (if (member ksym kel)
	  (progn
	    (cond ((= ksym (nth 0 kel)) nil)
		  ((= ksym (nth 1 kel))
		   (setq kmods (cons 'shift kmods)))
		  (t nil))
	    (setq kslist nil))

	(setq kslist (cdr kslist))
	(setq kcode (1+ kcode))
	))
    (cons kcode kmods)))

(defun xwem-kbd-xkcode->xksym (kcode)
  "Convert key code KCODE to keysym.
KeyCode -> KeySyms list in form (base shift caps ShiftCaps)."
  (nth (- kcode (X-Dpy-min-keycode (xwem-dpy))) (car (last xwem-xkeys-mapping)))
  )

;;; Various subroutines
;;;###autoload
(defun xwem-kbd-emod->kcode (emod &optional any)
  "Convert Emacs modifier EMOD to X keycode.
Behaviour is undefined If ANY argument is supplied.
DO NOT RELY ON THIS FUNCTION."
  (let* ((mods (car (last xwem-xmods-mapping)))
	 (rmod (cond ((eq emod 'shift) (nth 0 mods))
		     ;; locks skiped
		     ((eq emod 'control) (nth 2 mods))
		     ((eq emod 'meta) (nth 3 mods))
		     ;; numlock skiped
		     ((eq emod 'hyper) (nth 5 mods))
		     ((eq emod 'super) (nth 6 mods))
		     (t (error (format "Bad modifier `%S'" emod))))))
    (if any
	rmod
      (car rmod))))

;;;###autoload
(defun xwem-kbd-kcode->emod (kcode)
  "Convert key code KCODE to Emacs modifier, if KCODE is actually a modifier.
See also `xwem-kbd-kcode-modifier-p'."
  (let* ((mods (car (last xwem-xmods-mapping)))
	 (rmod (cond ((member kcode (nth 0 mods)) 'shift)
		     ;; locks skiped
		     ((member kcode (nth 2 mods)) 'control)
		     ((member kcode (nth 3 mods)) 'meta)
		     ;; numlock skiped
		     ((member kcode (nth 5 mods)) 'hyper)
		     ((member kcode (nth 6 mods)) 'super)
		     (t nil))))
    rmod))

;;;###autoload
(defun xwem-kbd-kcode-modifier-p (kcode)
  "Return non-nil if key code KCODE is modifier."
  (let ((mods (car (last xwem-xmods-mapping))))
    (while (and mods
		(not (member kcode (car mods))))
      (setq mods (cdr mods)))
    (car mods)))

(defun xwem-kbd-adjust-keycode (keycode modifiers)
  "Convert KEYCODE to keysym according to MODIFIERS."
  ;; XXX only 'shift modifier supported
  (if (and (member 'shift modifiers)
	   (> (cadr (xwem-kbd-xkcode->xksym keycode)) 0))
      (cadr (xwem-kbd-xkcode->xksym keycode))

    (car (xwem-kbd-xkcode->xksym keycode))))

(defun xwem-kbd-adjust-modifiers (keycode modifiers)
  "According to KEYCODE adjust MODIFIERS, i.e. remove 'shift."
  (if (and (member 'shift modifiers)
	   keycode (> (cadr (xwem-kbd-xkcode->xksym keycode)) 0))
      ;; 'shift in modifiers and keysym is valid, so we remove 'shift
      (remove 'shift modifiers)
    
    modifiers))

;;;###autoload
(defun xwem-kbd-xevents->emacs-events (xevs &optional trust-modbits)
  "Convert X-Events XEVS to Emacs events.

If TRUST-MODBITS is non-nil than we can trust modifier bits in
X-Event, otherwise we are trying to keep track of modifiers presses
and releases.  This is needed because core X events obtained from
RECORD extension does not have valid inforamtion about modifiers
bits."

  ;; NOTE: events garbbed using RECORD extension does not have correct
  ;; state field.
  (let ((rxevs (cond ((listp xevs) (vconcat xevs))
		     ((vectorp xevs) xevs)
		     (t xevs)))
	eevs xevtype kcode mbutton current-modifiers)

    ;; TODO:
    ;;   - Change `mapcar' to `mapvector'
    (setq eevs
	  (mapcar (lambda (xev)
		    (setq xevtype (X-Event-type xev))

		    (unless (member xevtype (list X-KeyPress X-KeyRelease X-ButtonPress X-ButtonRelease X-MotionNotify))
		      (error "Invalid event type: %s" (X-Event-name xev)))

		    (setq kcode nil
			  mbutton nil)
		    (cond ((member xevtype (list X-KeyPress X-KeyRelease))
			   (setq kcode (X-Event-xkey-keycode xev)))
			  ((member xevtype (list X-ButtonPress X-ButtonRelease))
			   (setq mbutton (X-Event-xbutton-button xev))))

		    (if (xwem-kbd-kcode-modifier-p kcode)
			;; KCODE is actually modifier
			(if (= (X-Event-type xev) X-KeyPress)
			    (setq current-modifiers (cons (xwem-kbd-kcode->emod kcode) current-modifiers))
			  (setq current-modifiers (delete (xwem-kbd-kcode->emod kcode) current-modifiers)))

		      ;; Skip normal key realese events
		      (unless (eq xevtype X-KeyRelease)

			;; If we can trust modifier bits, get information about
			;; modifiers currently pressed from state field.
			(when trust-modbits
			  (setq current-modifiers
				(xwem-kbd-xmodmask->emods
				 (cond ((eq xevtype X-KeyPress) (X-Event-xkey-state xev))
				       ((member xevtype (list X-ButtonPress X-ButtonRelease))
					(X-Event-xbutton-state xev))
				       ((eq xevtype X-MotionNotify) (X-Event-xmotion-state xev))))))

			(make-event (cond ((eq xevtype X-KeyPress) 'key-press)
					  ((eq xevtype X-ButtonPress) 'button-press)
					  ((eq xevtype X-ButtonRelease) 'button-release)
					  ((eq xevtype X-MotionNotify) 'motion)
					  (t (error "Unknown event: %s" (X-Event-name xev))))
				    (nconc (when (member xevtype (list X-ButtonPress X-ButtonRelease X-MotionNotify))
					     (list 'x (cond ((member xevtype (list X-ButtonPress X-ButtonRelease))
							     (X-Event-xbutton-root-x xev)) ; XXX what about 'channel?
							    (t (X-Event-xmotion-root-x xev)))
						   'y (cond ((member xevtype (list X-ButtonPress X-ButtonRelease))
							     (X-Event-xbutton-root-y xev)) ; XXX what about 'channel?
							    (t (X-Event-xmotion-root-y xev)))))
					   (list 'modifiers (xwem-kbd-adjust-modifiers kcode current-modifiers))
					   (when (eq xevtype X-KeyPress)
					     (list 'key (xwem-kbd-xksym->emacs
							 (xwem-kbd-adjust-keycode kcode current-modifiers))))
					   (when (member xevtype (list X-ButtonPress X-ButtonRelease))
					     (list 'button mbutton)))))
		      ))
		  rxevs))
    
    ;; Remove non-events from list
    (delete* nil eevs :test (lambda (el1 el2) (not (eventp el2))))
    ))

(defun xwem-kbd-emacs-events->xevents (events)
  "Convert Emacs EVENTS list to X events list."
  )

;;;###autoload
(defun xwem-kbd-ekeys->eevents (ekeys)
  "Convert Emacs keys sequence EKEYS to Emacs events vector."
  (mapvector (lambda (key)
	       (let (mods keychar)

		 (if (listp key)
		     (progn
		       (setq keychar (car (last key)))
		       (setq mods (butlast key)))
		   (setq keychar key))

		 (make-event 'key-press (list 'modifiers mods
					      'key keychar))))
	     ekeys))

;;}}}

;;{{{ [-] Sending

;; Sending(using XTEST)
(defun xwem-key-sendseq (keycode-seq)
  "Emulate KEYCODE-SEQ.
KEYCODE-SEQ is list of cons cells where car is event type and cdr is keycode.
Supported event types are `X-Xtest-KeyPress' and `X-Xtest-KeyRelease'."
  (mapc (lambda (ksel)
	  (let ((ktype (car ksel))
		(kcode nil)
		(ktime nil))
	    (cond ((vectorp (cdr ksel))
		   (setq kcode (aref (cdr ksel) 0))
		   (setq ktime (aref (cdr ksel) 1)))
		  (t
		   (setq kcode (cdr ksel))
		   (setq ktime X-CurrentTime)))
	    (X-XTest-FakeInput (xwem-dpy) ktype kcode X-None 0 0 ktime)))
	keycode-seq))

;;;###autoload
(defun xwem-key-send-ekeys (keys)
  "Send Emacs key sequence KEYS using XTEST extension."
  (let (lseq)
    (mapc (lambda (key)
	    (let (mods code)
	      (setq mods (mapcar (lambda (mm)
				   (xwem-kbd-emod->kcode mm))
				 (butlast key)))

		;; Now calculade key CODE maybe add shift modifier
		(setq code (xwem-kbd-xksym->xkcode
			    (xwem-kbd-emacs->xksym (car (last key)))))
		(setq mods (nconc mods (mapcar (lambda (mm)
						 (xwem-kbd-emod->kcode mm))
					       (cdr code))))
		(setq code (car code))

		(mapc (lambda (mod)
			(setq lseq (cons (cons X-Xtest-KeyPress mod) lseq)))
		      mods)
		(setq lseq (cons (cons X-Xtest-KeyPress code) lseq))
		(setq lseq (cons (cons X-Xtest-KeyRelease code) lseq))
		(mapc (lambda (mod)
			(setq lseq (cons (cons X-Xtest-KeyRelease mod) lseq)))
		      mods)
		))
	  (key-sequence-list-description keys))
    
    (setq lseq (nreverse lseq))
    (xwem-key-sendseq lseq)))

;;;###autoload
(defun xwem-kbd-wait-key-release (keycode)
  "Wait for key with KEYCODE for release."
  (unless xwem-executing-kbd-macro

    ;; Increase events queue protecs so no events will be
    ;; processed inside `XIfEvent'.
    (incf (X-Dpy-evq-protects (xwem-dpy)))

    ;; Wait for a keyrelease
    (unwind-protect
	(XIfEvent (xwem-dpy)
		  (lambda (xev)
		    (and (= (X-Event-type xev) X-KeyRelease)
			 (= (X-Event-xkey-keycode xev) keycode))))
		
      ;; Allow later events processing
      (decf (X-Dpy-evq-protects (xwem-dpy))))))

;;;###autoload
(defun xwem-kbd-force-mods-release ()
  "Force release of some modifiers."
  (let* ((xmods (car (last xwem-xmods-mapping)))
	 (mods (list (car (nth 0 xmods))        ; shift
		     (car (nth 2 xmods))	; control
		     (car (nth 3 xmods))	; meta
		     (car (nth 5 xmods))	; hyper
		     (car (nth 6 xmods)))))	; super
    (mapc (lambda (mod)
	    (X-XTest-FakeInput (xwem-dpy) X-Xtest-KeyRelease mod (xwem-rootwin) 0 0))
	  (delete 0 mods))
    ))

(defun xwem-kbd-wait-button-release (button)
  "Wait for BUTTON for release."
  )

;;}}}

;;{{{ [-] keypress/KeyRelease processing

(defun xwem-kbd-echolastkey ()
  "Echo key sequence already pressed in xwem minibuffer."
  (when xwem-keyboard-echo-keystrokes
    ;; XXX if there message from XWEM in minibuffer than add, otherwise
    (if (xwem-interactive-p)
	(append-message 'command (concat (single-key-description xwem-last-event) " "))

      (xwem-clear-message)
      (display-message 'command (key-description xwem-this-command-keys)))))

;;;###autoload
(defun xwem-kbd-current-map ()
  "Return current prefix map."
  (let ((cm (or xwem-kbd-private-prefix-map xwem-override-map
                (xwem-kbd-current-local-map)
                xwem-override-global-map xwem-global-map)))
    (when (symbolp cm)
      (setq cm (symbol-function cm)))
    cm))

;;;###autoload
(defun xwem-kbd-global-map-current-p ()
  "Return non-nil if `xwem-global-map' is current prefix map."
  (eq (xwem-kbd-current-map) (or xwem-override-global-map xwem-global-map)))

;;;###autoload
(defun xwem-kbd-current-local-map ()
  "Return current local keymap."
  (let* ((xwin (X-Event-CASE xwem-last-xevent
                 (:X-KeyPress
                  (X-Event-xkey-child xwem-last-xevent))
                 ((:X-ButtonPress :X-ButtonRelease)
                  (X-Event-xbutton-child xwem-last-xevent))
                 (:X-MotionNotify
                  (X-Event-xmotion-child xwem-last-xevent))))
         (cl (xwem-find-client xwin)))
    (unless (xwem-cl-p cl)
      ;; Last chance
      (setq cl (xwem-find-client xwem-event-window)))

    (and (xwem-cl-p cl) (xwem-local-map cl))))

;;;###autoload
(defun xwem-kbd-set-current-prefix-keymap (newkeymap)
  "Set current keymap to NEWKEYMAP.

Use (xwem-kbd-set-current-prefix-keymap nil) to set current keymap
to `xwem-global-keymap' instead of
(xwem-kbd-set-current-prefix-keymap xwem-global-map)."
  (setq xwem-kbd-private-prefix-map newkeymap))

(defun xwem-kbd-handle-keyrelease (xdpy win xev)
  "On XDPY and window WIN handle KeyRelease event XEV."
  ;; TODO:
  ;;  - modifiers tracker
  nil)

;;;###autoload
(defun xwem-kbd-key-binding (keys &optional keymap accept-default)
  "Return key binding corresponding to KEYS in KEYMAP.
If KEYMAP is ommited, `xwem-global-map' will be used.
`xwem-kbd-key-binding' omits default KEYMAP binding unless
ACCEPT-DEFAULT is non-nil."

  (lookup-key (or keymap (xwem-kbd-current-map)) keys accept-default))

;;;###autoload
(defun xwem-kbd-key-binding-evs (evs &optional keymap accept-default)
  "Return key binding corresponding to Emacs events EVS in KEYMAP.
If KEYMAP is ommited, `xwem-global-map' will be used.
ACCEPT-DEFAULT is the same as for `xwem-kbd-key-binding'."
  (xwem-kbd-key-binding (events-to-keys evs) keymap accept-default))

;;;###autoload
(defun xwem-kbd-handle-keybutton (xev)
  "On display XDPY and window WIN handle KeyPress or ButtonPress event XEV."
  (if (and (= (X-Event-type xev) X-KeyPress)
	   (xwem-kbd-kcode-modifier-p (X-Event-xkey-keycode xev)))
      ;; Seems that we are grabbing keyboard now and modifier
      ;; pressed or it is case when some smart modifier pressed.
      nil

    (xwem-kbd-handle-keybutton-from-emacs
     (car (xwem-kbd-xevents->emacs-events (list xev) t)) xev)))

;;;###autoload
(defun xwem-kbd-handle-keybutton-from-emacs (eev &optional xev)
  "Handle Emacs event EEV originated from XWEM.
Optional X-Event XEV, if passed to obtain X specific information."
  (let (lkm)

    ;; Remember some information about XEV event.
    (when (X-Event-p xev)
      (setq xwem-event-window (X-Event-win xev))
      (setq xwem-last-xevent xev))

    (setq xwem-last-event eev)

    (setq xwem-this-command-keys
	  (vconcat xwem-this-command-keys (vector xwem-last-event)))

    (setq lkm (xwem-kbd-key-binding-evs (vector xwem-last-event)))
    (X-Dpy-log (xwem-dpy) "LOCAL KEYMAP=%S, bind=%S"
               '(xwem-kbd-current-local-map)
               '(xwem-kbd-key-binding (events-to-keys (vector xwem-last-event)))
               )

    ;; XXX -- maybe echoing should be done in `xwem-kbd-process-after-lookup'?
    (xwem-kbd-echolastkey)

    (xwem-kbd-process-after-lookup lkm)))
  
(defun xwem-kbd-process-after-lookup (lkm)
  "Process keymap or command entry LKM after `lookup-key'."
  (X-Dpy-log (xwem-dpy) "lkm = %S\n" 'lkm)

  (let ((slkm lkm)			;save lkm
	(prfx-plist (when (and xwem-kbd-private-prefix-map
			       (symbolp xwem-kbd-private-prefix-map))
		      (symbol-plist xwem-kbd-private-prefix-map)))
	(splist (when (symbolp lkm) (symbol-plist lkm))))

    (when (and (symbolp lkm)
	       (functionp lkm)
	       (keymapp (symbol-function lkm)))
      (setq lkm (symbol-function lkm)))

    (X-Dpy-log (xwem-dpy) "PRFX-PLIST = %S, SPLIST = %S\n" 'prfx-plist 'splist)

    ;; Check for special mode, when we just reading single keystroke
    (when xwem-kbd-reading-key
      (xwem-read-keys-stop nil))

    ;; Last chance to try default command
    (when (null lkm)
      (setq lkm (keymap-default-binding (xwem-kbd-current-map)))
      (setq splist (and (symbolp lkm) (symbol-plist lkm))))

    ;; Check is there need for prefix help or quit command
    (when (and (null lkm)
               xwem-kbd-now-grabbing)
      (setq lkm
	    (let ((etk (events-to-keys (vector xwem-last-event))))
	      (cond ((equal etk xwem-help-key) xwem-prefix-help-command)
		    ((equal etk xwem-quit-key) xwem-quit-command)
		    (t nil)))))

    ;; Now take a look at lkm
    (cond ((null lkm)
	   ;; Check are we reading keysequence now
	   (when xwem-kbd-reading-keyseq
	     (xwem-read-keys-stop t))

           (unless (eq (event-type xwem-last-event) 'button-release)
             (xwem-play-sound 'undefined-key)
             (xwem-message 'info "%s not binded." (key-description xwem-this-command-keys)))

	   (xwem-kbd-stop-grabbing)
	   (xwem-kbd-set-current-prefix-keymap nil)
	   (setq xwem-this-command-keys [])
	   (setq xwem-kbd-reading-key nil)
	   (setq xwem-kbd-reading-keyseq nil)

	   (let ((ex-fun (plist-get prfx-plist 'exit-fun)))
	     (when ex-fun (funcall ex-fun)))
	   )

	  ;; Prefix map
	  ((keymapp lkm)

	   (xwem-kbd-set-current-prefix-keymap slkm)
	   (let ((enter-fun (plist-get splist 'enter-fun)))
	     (when enter-fun (funcall enter-fun)))

	   (xwem-kbd-start-grabbing))

	  ;; Binded command or something else
	  (t

	   ;; Check are we reading keysequence now
	   (when xwem-kbd-reading-keyseq
	     (xwem-read-keys-stop t))

           ;; Reset privat keymap prefix
           (xwem-kbd-set-current-prefix-keymap nil)

	   ;; Now run command or keyboard macro
	   (unwind-protect
	       (condition-case err
		   (cond ((vectorp lkm)
                          ;; Keyboard macro.
                          ;; Wait for keyrelease, ungrab keyboard, than play it.
                          (when (= (X-Event-type xwem-last-xevent) X-KeyPress)
                            (xwem-kbd-wait-key-release (X-Event-xkey-keycode xwem-last-xevent)))
                          (xwem-kbd-stop-grabbing)
                          (xwem-keymacro-internal-play lkm (prefix-numeric-value xwem-prefix-arg)))

			 ((commandp lkm)
                          ;; Execute command
                          (setq xwem-this-command lkm)
                          (run-hooks 'xwem-pre-command-hook)

                          (call-interactively xwem-this-command)

                          (setq xwem-last-command xwem-this-command))

			 (t (error "Unknown lkm %S" lkm)))

		 (error
		  (xwem-play-sound 'command-fail)
		  (xwem-message 'err-nobeep "In cmd(%S): %s" lkm (error-message-string err)))

		 (quit
		  (if (and (boundp 'xwem-bypass-quit)
			   (symbol-value 'xwem-bypass-quit))
		      (signal 'quit (list 'xwem-bypass-quit (symbol-value 'xwem-bypass-quit)))

		  (xwem-play-sound 'quit)
		  (xwem-message 'info "Quit: %s" err))))

             ;; XXX Generic post command processing
             (when (xwem-kbd-global-map-current-p)
               (xwem-kbd-stop-grabbing)
               (setq xwem-this-command-keys []))
             )

	   ;; Run post command hook
	   (run-hooks 'xwem-post-command-hook)
	   )

	  (t (error
	      (format "Hm .. strange lkm=%S" lkm))))))

;;}}}

;;{{{ [-] Grabbing

(defun xwem-kbd-graugra-key (key win mode &optional button-mask)
  "Grab or Ungrab KEY on WIN.
MODE is either 'grab or 'ungrab.
BUTTON-MASK is mask passed to `XGrabButton' if MODE is 'grab and key
is actually a mouse key."
  (let* ((key (aref (key-sequence-list-description key) 0))
	 (kmods (butlast key))
	 (ksyko (xwem-kbd-emacs->xksym (car (last key))))
	 mouse)

    (if (listp ksyko)
	(setq mouse (car ksyko))
      
      (setq ksyko (xwem-kbd-xksym->xkcode ksyko))
      (when (eq (cadr ksyko) 'shift)
	(setq kmods (cons 'shift kmods)))
      (setq ksyko (car ksyko)))

    (setq kmods (xwem-kbd-emods->xmodmask kmods))

    ;; Take into account evil masks
    (mapc (lambda (m1)
            (mapc (lambda (m2)
                    (if mouse
                        (if (eq mode 'grab)
                            (XGrabButton (xwem-dpy) mouse (Xmask-or kmods m1 m2) win
                                         (or button-mask (Xmask-or XM-ButtonPress XM-ButtonRelease)) nil t)
                          (XUngrabButton (xwem-dpy) mouse (Xmask-or kmods m1 m2) win))

                      (if (eq mode 'grab)
                          (XGrabKey (xwem-dpy) ksyko (Xmask-or kmods m1 m2) win t)
                        (XUngrabKey (xwem-dpy) ksyko (Xmask-or kmods m1 m2) win))))
                  xwem-kbd-evilmasks))
          xwem-kbd-evilmasks)
    ))

(defun xwem-kbd-grab-key (key win)
  "Grab KEY on WIN."
  (xwem-kbd-graugra-key key win 'grab))

(defun xwem-kbd-ungrab-key (key win)
  "Stop grabbing KEY on WIN."
  (xwem-kbd-graugra-key key win 'ungrab))

;;;###autoload
(defun xwem-kbd-install-grab (keymap win)
  "Install KEYMAP grabs on X window WIN."
  (map-keymap (lambda (key unused)
		(xwem-kbd-grab-key key win))
	      keymap))

;;;###autoload
(defun xwem-kbd-uninstall-grab (keymap win)
  "Uninstall KEYMAP grabs on X window WIN."
  (map-keymap (lambda (key unused)
		(xwem-kbd-ungrab-key key win))
	      keymap))

;;;###autoload
(defun xwem-kbd-start-grabbing (&optional cursor)
  "Begin grabbing keyboard (some key-prefix is entered).
Optionally you can specify CURSOR to be used, while grabbing."
  (unless xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XGrabKeyboard (xwem-dpy) (or (xwem-focus-xcurrent) (xwem-rootwin)) nil)
      (xwem-mouse-grab (or cursor xwem-cursor-wait)))
    
    (setq xwem-kbd-now-grabbing t)))

;;;###autoload
(defun xwem-kbd-start-grabbing-sync (&optional cursor)
  "Same as `xwem-kbd-start-grabbing', but initiate grabs in Sync mode.
CURSOR argument is same is for `xwem-kbd-start-grabbing'."
  (unless xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XGrabKeyboard (xwem-dpy) (or (xwem-focus-xcurrent) (xwem-rootwin))
                     nil X-GrabModeSync X-GrabModeSync)
      (xwem-mouse-grab (or cursor xwem-cursor-wait))
      )

    (setq xwem-kbd-now-grabbing t)))

;;;###autoload
(defun xwem-kbd-stop-grabbing ()
  "Stop grabbing keyboard."
  (when xwem-kbd-now-grabbing
    (unless xwem-executing-kbd-macro
      (XUngrabKeyboard (xwem-dpy))
      (xwem-mouse-ungrab))

    (setq xwem-kbd-now-grabbing nil)))

;;; FIXME: this does bad, naughty things.
;; ;;;###autoload(autoload 'xwem-kbd-quote-command "xwem-keyboard" "" t)
;; (define-xwem-command xwem-kbd-quote-command ()
;;   "Pass event EV to currently active window.
;; DOES NOT WORK."
;;   (xwem-interactive "_")

;;   (let ((xwin (xwem-focus-xcurrent)))
;;     (when (X-Win-p xwin)
;;       (XGrabKeyboard (xwem-dpy) xwin nil X-GrabModeAsync X-GrabModeSync)
;;       (XGrabPointer (xwem-dpy) xwin (Xmask-or XM-ButtonPress XM-ButtonRelease)
;; 		    xwem-cursor-quote nil X-GrabModeSync)
;;       (XAllowEvents (xwem-dpy) X-SyncBoth)

;;       (xwem-message 'info "[Quote key]")
;;       (unwind-protect
;; 	  (let ((done nil)
;; 		xev)
;; 	    (while (not done)
;; 	      (setq xev (xwem-next-event 1))
;;               (cond ((X-Event-p xev)
;;                      (if (and (member (X-Event-type xev)
;;                                       (list X-KeyPress X-ButtonPress X-ButtonRelease))
;;                               (xwem-kbd-xevents->emacs-events (list xev) t))
;;                          (progn
;;                            (xwem-message 'info "here")
;;                            (XAllowEvents (xwem-dpy) X-ReplayKeyboard)
;;                            (XAllowEvents (xwem-dpy) X-ReplayPointer)
;;                            (xwem-clear-message)
;;                            (setq done t))

;;                        (XAllowEvents (X-Event-dpy xev) X-SyncBoth)))
;;                     (t (setq done t)))))

;; 	(XUngrabKeyboard (xwem-dpy))
;; 	(XUngrabPointer (xwem-dpy))
;; 	))))

;;}}}

;;{{{ [-] Universal argument

;;;###autoload
(defvar xwem-prefix-arg nil
"The value of the prefix argument for this editing command.

It may be a number, or the symbol `-' for just a minus sign as arg, or
a list whose car is a number for just one or more
\\<xwem-global-map>\\[xwem-universal-argument] or `nil' if no argument
has been specified.  This is what `\\(xwem-interactive \"P\"\\)'
returns.")

(defconst xwem-universal-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-default-binding map 'xwem-universal-command)
    (define-key map xwem-universal-key 'xwem-universal-more)
    (define-key map [?-] 'xwem-universal-minus)
    (define-key map [?0] 'xwem-universal-digit)
    (define-key map [?1] 'xwem-universal-digit)
    (define-key map [?2] 'xwem-universal-digit)
    (define-key map [?3] 'xwem-universal-digit)
    (define-key map [?4] 'xwem-universal-digit)
    (define-key map [?5] 'xwem-universal-digit)
    (define-key map [?6] 'xwem-universal-digit)
    (define-key map [?7] 'xwem-universal-digit)
    (define-key map [?8] 'xwem-universal-digit)
    (define-key map [?9] 'xwem-universal-digit)
    map)
  "Keymap used while processing \\<xwem-global-map>\\[xwem-universal-argument].")

(defun xwem-universal-common-begin ()
  "Common begin for universal argument."
  (if xwem-kbd-now-grabbing
      (setq xwem-override-map xwem-universal-map)

    ;; Start grabbing
    (xwem-kbd-start-grabbing)
    (setq xwem-override-map xwem-universal-map)))

;;;###autoload(autoload 'xwem-universal-argument "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-argument ()
  "Begin a numeric argument for the following command.
Digits or minus sign following
\\<xwem-global-map>\\[xwem-universal-argument] make up the numeric
argument.  \\<xwem-global-map>\\[xwem-universal-argument] following the
digits or minus sign ends the argument.
\\<xwem-global-map>\\[xwem-universal-argument] without digits or minus
sign provides 4 as argument.
Repeating \\<xwem-global-map>\\[xwem-universal-argument] without digits or
minus sign multiplies the argument by 4 each time."
  (xwem-interactive)

  (setq xwem-prefix-arg (list 4))
  (xwem-universal-common-begin))

;; A subsequent H-u means to multiply the factor by 4 if we've typed
;; nothing but H-u's otherwise it means to terminate the prefix arg.
;;;###autoload(autoload 'xwem-universal-more "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-more (arg)
  "A subsequent \\<xwem-universal-map>\\[xwem-universal-more] means to
  multiply the factor by 4 if we've typed nothing but
  \\<xwem-universal-map>\\[xwem-universal-more]'s; otherwise it means
  to terminate the prefix arg."
  (xwem-interactive "P")

  (if (consp arg)
      (setq xwem-prefix-arg (list (* 4 (car arg))))
    
    (setq xwem-prefix-arg arg)
    (setq xwem-override-map nil)))

;;;###autoload(autoload 'xwem-universal-minus "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-minus (arg)
  "Begin a negative numeric argument for the next command.
\\<xwem-global-map>\\[xwem-universal-argument] following digits or
minus sign ends the argument."
  (xwem-interactive "P")

  (setq xwem-prefix-arg (cond ((integerp arg) (- arg))
			      ((eq arg '-) nil)
			      (t '-)))
  (xwem-universal-common-begin))

;;;###autoload(autoload 'xwem-universal-digit "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-digit (arg)
  "Part of the numeric argument for the next command.
\\<xwem-global-map>\\[xwem-universal-argument] following digits or
minus sign ends the argument."
  (xwem-interactive "P")

  (let* ((num (event-key xwem-last-event))
	 (digit (- num ?0)))
    (cond ((integerp arg)
	   (setq xwem-prefix-arg (+ (* arg 10) (if (< arg 0) (-  digit) digit))))
	  ((eq arg '-)
	   ;; Treat -0 as just -, so that -01 will work.
	   (setq xwem-prefix-arg (if (zerop digit) '- (- digit))))

	  (t (setq xwem-prefix-arg digit)))

    (xwem-universal-common-begin)))

(defun xwem-reset-this-command-lengths ()
  "For some documentation look at `reset-this-command-lengths'."
  ;; This brokes some things, like H-1 H-2 H-3 will not be properly
  ;; displayed in minibuffer, so i disabled it.

  ;; Also there is notice in event-stream.c to
  ;; `reset-this-command-lengths':
  ;;
  ;;   /* #### I don't understand this at all, so currently it does nothing.
  ;;   If there is ever a problem, maybe someone should investigate. */

  ; (setq xwem-this-command-keys (vector xwem-last-event))
  )

;;;###autoload(autoload 'xwem-universal-command "xwem-keyboard" "" t)
(define-xwem-command xwem-universal-command (arg)
  "Handle universal argument functionality."
  (xwem-interactive "P")

  (setq xwem-prefix-arg arg)
  (xwem-reset-this-command-lengths)
  (xwem-kbd-set-current-prefix-keymap nil)

  (setq xwem-override-map nil)

  (xwem-kbd-process-after-lookup
   (xwem-kbd-key-binding-evs (vector xwem-last-event)))
  )

;;}}}


(provide 'xwem-keyboard)

;;; xwem-keyboard.el ends here