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
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
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
;;; xwem-keyboard.el --- Keyboard support for XWEM.

;; Copyright (C) 2003-2005 by XWEM Org.

;; Authors: Zajcev Evgeny <zevlg@yandex.ru>
;;          Steve Youngs  <steve@youngs.au.com>
;;          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:

(require 'xlib-xlib)
(require 'xlib-xtest)
(require 'xlib-keysymdb)

(require 'xwem-load)
(require 'xwem-misc)

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

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

;;;###autoload
(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)

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

;;;###autoload
(defcustom xwem-keyboard-echo-keystrokes 1
  "*If non-nil than echo unfinished commands in echo area after this many seconds of pause."
  :type 'number
  :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)
                 (const :tag "Alt" alt))
  :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)
                 (const :tag "Alt" alt))
  :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)
                 (const :tag "Alt" alt))
  :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.")

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

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

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

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

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

;;;###autoload
(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)

;;;###autoload
(defcustom xwem-keyboard-init-hook nil
  "*Hooks called after xwem keyboard initialization."
  :type 'hook
  :group 'xwem-keyboard
  :group 'xwem-hooks)

(defcustom xwem-keyboard-use-synth-events nil
  "*Non-nil mean use XSendEvent instead of XTEST's FakeInput.
Useful to set it to non-nil when using sticky modifiers or in any
other case when xwem can't properly force modifiers releasing.
However if having `xwem-keyboard-use-synth-events' to non-nil, make
sure you've configured clients to accept synthetic X events (f.i. set
`x-allow-sendevents' to non-nil to make XEmacs accept synthetic
events).
This is client local variable.  Each client have its own value for it."
  :type 'boolean
  :group 'xwem-keyboard)
(xwem-make-variable-client-local 'xwem-keyboard-use-synth-events)

;;; Internal variables

;;;###autoload
(defvar xwem-override-map nil
  "Keymap that overrides all other keymaps.
And did not considered as global map.  You should control end of
command execution for yourself if using it.
You should *bind* this, not set it.")

;;;###autoload
(defvar xwem-override-local-map nil
  "Keymap that overrides all local keymaps.
You should *bind* it, not set it.
Normally you should use `xwem-overriding-local-map' function.")

(defvar xwem-override-global-map nil
  "Keymap that is lookuped straight after local map.
You should *bind* it, 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-xmods-mapping nil
  "List of keycodes for modifiers.
Corresponds to Shift, Lock,Control, Mod1, Mod2, Mod3, Mod4, and Mod5, in order.
INTERNAL VARIABLE, do not modify.")

;;;###xwem-autoload
(defvar xwem-event-client nil "Client where last key/mouse event occured.")
;;;###xwem-autoload
(defvar xwem-last-event nil "Last key/mouse event(Emacs event).")
;;;###xwem-autoload
(defvar xwem-last-xevent nil "Last key/mouse X Event.")
;;;###xwem-autoload
(defvar xwem-this-command-keys []
  "Vector of events that were used to invoke this command.")
;;;###xwem-autoload
(defvar xwem-this-command nil "The command now being executed.")
;;;###xwem-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.")

;;}}}


;;{{{ [-] Defining new key

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

PGRAB-MODE and KGRAB-MODE specifies grabbing mode for pointer and
keyboard respectively."
  (define-key keymap key command)
  (xwem-kbd-graugra-key key win (if command 'grab 'ungrab) nil pgrab-mode kgrab-mode))

;;;###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 (cl)
            (xwem-kbd-graugra-key key (xwem-cl-xwin cl) (if command 'grab 'ungrab)))
        (xwem-clients-list))
  nil)

;;}}}

;;{{{ [-] 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."
  (car (if no-minib-focus-p
           (xwem-next-command-event prompt)
         (xwem-under-minibuffer
          (xwem-next-command-event prompt)))))

(defun xwem-read-key-sequence-1 (&optional continue-echo)
  (xwem-kbd-stop-command-keys-echoing)
  (let ((xwem-kbd-reading-keyseq t)
        (done nil)
        xev eev eevs bind)
    (while (not done)
      (setq xev (xwem-next-event))
      (when (setq eev (xwem-xevents->emacs-events (list xev) t))
        (setq xwem-last-xevent xev
;              xwem-event-client (xwem-event-client xev)
              xwem-last-event (car eev)
              xwem-this-command-keys (vconcat xwem-this-command-keys eev)
              eevs (vconcat eevs eev)
              bind (xwem-kbd-fixup-keymap (xwem-lookup-key xwem-event-client (events-to-keys eevs) t)))
        (xwem-kbd-schedule-command-keys-echoing)
        (unless (keymapp bind)
          (xwem-kbd-stop-command-keys-echoing)
          (setq done t))))
    eevs))
  
;; Read keysequence which binds to command
;;;###autoload
(defun xwem-read-key-sequence (&optional prompt no-minib-focus-p)
  "Read key sequence that call command prompting PROMPT."
  (when prompt
    (xwem-message 'prompt prompt))

  (let ((keys (if no-minib-focus-p
                  (xwem-read-key-sequence-1)
                (xwem-under-minibuffer
                 (xwem-read-key-sequence-1)))))
    (when prompt
      (xwem-clear-message))
    keys))

;;}}}

;;{{{ [-] local keymap

;;;###autoload
(defun xwem-local-map (cl)
  "Return CL's local keymap."
  (when (xwem-cl-p cl)
    (xwem-kbd-fixup-keymap (xwem-client-property cl 'xwem-local-keymap))))
(defsetf xwem-local-map (cl) (keymap)
  "Set CL's local keymap to KEYMAP."
  `(let ((nkeymap (xwem-kbd-fixup-keymap ,keymap))
         (okeymap (xwem-local-map ,cl)))
     (when (keymapp okeymap)
       (xwem-focus-mode-invoke ,cl 'before-keymap-change)
       ;; But avoid ungrabbing keymaps!  Because it can use prefix
       ;; keymap of some other command.
       (xwem-kbd-uninstall-grab okeymap (xwem-cl-xwin ,cl)
                                #'(lambda (key def)
                                    (not (keymapp (xwem-kbd-fixup-keymap def))))))

     ;; Install new keymap
     (xwem-client-set-property ,cl 'xwem-local-keymap nkeymap)
     (when (keymapp nkeymap)
       (xwem-kbd-install-grab nkeymap (xwem-cl-xwin ,cl))
       (xwem-focus-mode-invoke ,cl 'after-keymap-change))))

;;;###autoload
(defun xwem-local-set-key (key command &optional cl pgrab-mode kgrab-mode)
  "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."
  (unless cl
    (setq cl (xwem-cl-selected)))

  ;; Create new local keymap for client if needed
  (unless (keymapp (xwem-local-map cl))
    (setf (xwem-local-map cl) (make-sparse-keymap)))

  (xwem-define-key (xwem-cl-xwin cl) (xwem-local-map cl) key command pgrab-mode kgrab-mode))

;;;###xwem-autoload
(defun xwem-use-local-map (keymap &optional cl)
  "Select KEYMAP as  local CL's keymap."
  (unless cl
    (setq cl (xwem-cl-selected)))

  (setf (xwem-local-map cl) keymap))

;;}}}

;;{{{ [-] 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)
  (signal 'undefined-keystroke-sequence xwem-this-command-keys))

;;;###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 ((self-insert-p nil))
    (cond ((and (> (length xwem-this-command-keys) 1)
                (eq (aref xwem-this-command-keys 0) 'self-insert))
           ;; Adjust xwem-this-command-keys by removing leading 'self-insert
           (setq xwem-this-command-keys
                 (vconcat (cdr (append xwem-this-command-keys nil))))
           (setq self-insert-p t))

          ((= (length xwem-this-command-keys) 1)
           (setq self-insert-p t)))

    (if (not self-insert-p)
        (error 'xwem-error (format "%s is undefined"
                                   (key-description xwem-this-command-keys)))

      ;; Self insert command allowed only for normal clients to avoid
      ;; infinite loops.
      (unless (xwem-dummy-client-p (xwem-cl-selected))
        (xwem-kbd-add-pending-keys
         (apply 'vconcat (make-list (prefix-numeric-value arg) xwem-this-command-keys))
         (xwem-cl-selected))))))

;;}}}

;;{{{ [-] Quiting keyboarding

;;;###autoload(autoload 'xwem-keyboard-quit "xwem-keyboard" "" t)
(define-xwem-command xwem-keyboard-quit ()
  "Send quit signal."
  (xwem-interactive)
  
  (setq xwem-override-map nil)
  (signal 'quit '(xwem))

  ;; NOT REACHED
  (xwem-message 'error "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 set PointerRoot")

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

;;}}}

;;{{{ [-] 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)

   ((= ksym XK-Next) 'next)
   ((= ksym XK-Prior) 'prior)
   ;; 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 (or (X-XKeysymDB-keysym->sym ksym)
          (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)

                 ((string= symname "next") XK-Next)
                 ((string= symname "prior") XK-Prior)

                 ;; 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 (or (X-XKeysymDB-sym->keysym ksym)
         (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."
  (apply 'Xmask-or 0 (mapcar #'(lambda (mod)
                                 (or (get mod 'x-mod-mask) 0))
                             emods)))

(defun xwem-kbd-xmodmask->emods (mmask)
  "Convert X modifiers mask MMASK to Emacs modifiers list."
  (delq nil (mapcar #'(lambda (mod)
                        (and (Xtest mmask (or (get mod 'x-mod-mask) 0))
                             mod))
                    '(shift control alt meta hyper super))))

;; 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."
  (let* ((kcode (X-Dpy-min-keycode (xwem-dpy)))
         (kslist (car (last xwem-xkeys-mapping)))
         (ksyms-per-kcode (length (car kslist)))
         (ksym-off 0)
         (kmods nil))
    (while kslist
      (cond ((= ksym (nth ksym-off (car kslist)))
             (setq kslist nil))
            ((= ksym (nth (1+ ksym-off) (car kslist)))
             (setq kslist nil
                   kmods (cons 'shift kmods)))
            (t (setq kslist (cdr kslist)
                     kcode (1+ kcode))
               (when (and (null kslist)
                          (setq ksym-off (+ 2 ksym-off))
                          (< ksym-off ksyms-per-kcode))
                 (setq kslist (car (last xwem-xkeys-mapping))
                       kcode (X-Dpy-min-keycode (xwem-dpy)))))))
    (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
(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."
  (funcall (if any 'identity 'car) (get emod 'x-key-codes)))

(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 ((emods '(shift control alt meta super hyper)))
    (while (and emods (not (member kcode (get (car emods) 'x-key-codes))))
      (setq emods (cdr emods)))
    (car emods)))

;;;###xwem-autoload
(defun xwem-kbd-kcode-modifier-p (kcode)
  "Return non-nil if key code KCODE is modifier."
  (member kcode (apply 'append xwem-xmods-mapping)))

(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))

(defun xwem-kbd-hack-mouse (xev)
  "Return (X . Y) to be used in mouse Emacs event."
  (let ((cl (xwem-misc-find-cl-by-emacs-frame (last-nonminibuf-frame)))
        xpnt x y)

    (if (member (X-Event-type xev) (list X-ButtonPress X-ButtonRelease))
        (setq x (X-Event-xbutton-root-x xev)
              y (X-Event-xbutton-root-y xev))
      (setq x (X-Event-xmotion-root-x xev)
            y (X-Event-xmotion-root-y xev)))

    (when cl
      (setq xpnt (car (XTranslateCoordinates (xwem-dpy) (xwem-cl-xwin cl) (xwem-rootwin) 0 0))))

    (when xpnt
      (setq x (- x (X-Point-x xpnt)))
      (setq y (- y (X-Point-y xpnt))))
    (cons x y)))

;;;###xwem-autoload
(defun xwem-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 'xwem-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 'xwem-error "Unknown event: %s" (X-Event-name xev))))
                                      (nconc (when (member xevtype (list X-ButtonPress X-ButtonRelease X-MotionNotify))
                                               (let ((xm (xwem-kbd-hack-mouse xev)))
                                                 (list 'x (car xm) 'y (cdr xm))))
                                             (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."
  )

(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-send-xtest-internal (&optional keycode-seq)
  "Emulate key presses/releases of KEYCODE-SEQ sequence using XTEST extension."
  (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))

(defun xwem-key-send-xtest (keys)
  "Send Emacs key sequence KEYS using XTEST extension."
  (let (lseq)
    (mapc #'(lambda (key)
              (let (mods code)
                (setq mods (mapcar 'xwem-kbd-emod->kcode (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 'xwem-kbd-emod->kcode (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-send-xtest-internal lseq)))

;; Sending (using XSendEvent)
(defun xwem-key-send-synth (keys &optional client)
  "Send synthesize KEYS to CLIENT.
If CLIENT is ommited, selected client is used."
  (unless client
    (setq client (xwem-cl-selected)))

  (when (xwem-cl-alive-p client)
    ;; Fix KEYS
    (setq keys (key-sequence-list-description keys))

    (let (keycode keymods)
      (mapc #'(lambda (key)
                (setq keymods (butlast key))
                ;; Now calculade key KEYCODE maybe add shift modifier
                (setq keycode (xwem-kbd-xksym->xkcode
                               (xwem-kbd-emacs->xksym (car (last key)))))
                (setq keymods (nconc keymods (cdr keycode)))
                (setq keycode (car keycode))

                (XSendEvent (xwem-dpy) (xwem-cl-xwin client)
                            nil XM-KeyPress
                            (X-Create-message
                             (list [1 X-KeyPress] ;type
                                   [1 keycode] ;detail
                                   [2 2806] ; XXX seq
                                   [4 X-CurrentTime] ; time
                                   [4 (X-Win-id (xwem-rootwin))] ; root
                                   [4 (X-Win-id (xwem-cl-xwin client))] ; event
                                   [4 X-None] ; child
                                   [2 0] ; root-x
                                   [2 0] ; root-y
                                   [2 0] ; event-x
                                   [2 0] ; event-y
                                   [2 (xwem-kbd-emods->xmodmask keymods)] ; state
                                   [1 t] ; same-screen
                                   [1 nil]))))
            keys))))

;;;###xwem-autoload
(defun xwem-kbd-wait-key-release (keycode)
  "Wait for key with KEYCODE for release."
  (unless (xwem-keymacro-executing-p)
    ;; Now wait key release event
    (XNextEvent (xwem-dpy) nil
                #'(lambda (xev)
                    (and (= (X-Event-type xev) X-KeyRelease)
                         (= (X-Event-xkey-keycode xev) keycode))))))

;;;###xwem-autoload
(defun xwem-kbd-force-mods-release (&optional mods)
  "Force release of MODS modifiers."
  (unless xwem-keyboard-use-synth-events
    ;; Only needed when using XSendEvent for emulating keys 
    (xwem-key-send-xtest-internal
     (mapcar #'(lambda (el) (cons X-Xtest-KeyRelease el))
	     (apply 'append
		    (mapcar #'(lambda (mod)
                                (get mod 'x-key-codes))
			    (or mods '(shift control meta super hyper))))))
    (XFlush (xwem-dpy))))

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

(define-xwem-deffered xwem-cl-apply-pending-keys (cl)
  "Apply pending keys to CL."
  (when (and (xwem-cl-alive-p cl)
             (xwem-cl-get-sys-prop cl 'pending-keys))
    (if (xwem-client-local-variable-value cl 'xwem-keyboard-use-synth-events)
        ;; Using XSendEvent
        (xwem-key-send-synth (xwem-cl-get-sys-prop cl 'pending-keys) cl)
      
      ;; Using XTEST
      (let ((xattr (XGetWindowAttributes (xwem-dpy) (xwem-cl-xwin cl)))
            qt)
        (unless (= (X-Attr-mapstate xattr) X-Viewable)
          (setq qt (XQueryTree (xwem-dpy) (xwem-cl-xwin cl)))
          ;; Make CL viewable
          (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl)
                           (xwem-cl-xwin (xwem-dummy-client)) 0 0)
          (XMapWindow (xwem-dpy) (xwem-cl-xwin cl)))

        (xwem-focus-push-set (xwem-cl-xwin cl))
        (xwem-key-send-xtest (xwem-cl-get-sys-prop cl 'pending-keys))
        (xwem-focus-pop-set)
        (XFlush (xwem-dpy))

        (unless (= (X-Attr-mapstate xattr) X-Viewable)
          ;; Restore mapping
          (when (= (X-Attr-mapstate xattr) X-Unmapped)
            (XUnmapWindow (xwem-dpy) (xwem-cl-xwin cl)))
          ;; Restore parent back to its parent
          (XReparentWindow (xwem-dpy) (xwem-cl-xwin cl) (nth 3 qt)
                           (X-Geom-x (xwem-cl-xgeom cl))
                           (X-Geom-y (xwem-cl-xgeom cl))))))

    ;; Remove pending keys
    (xwem-cl-rem-sys-prop cl 'pending-keys)))

;;;###xwem-autoload
(defun xwem-kbd-add-pending-keys (keys &optional cl)
  "Add KEYS as pending to be pressed in CL.
If CL is ommited selected client considered."
  (unless cl
    (setq cl (xwem-cl-selected)))
  (xwem-cl-put-sys-prop cl 'pending-keys
    (vconcat (xwem-cl-get-sys-prop cl 'pending-keys)
             keys))
  (xwem-cl-apply-pending-keys cl))

;;}}}

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

;;;###xwem-autoload
(defun xwem-kbd-add-default-keymap (keymap)
  "Add KEYMAP to default keymaps.
KEYMAP MUST NOT HAS PARENTS!"
  (unless (memq keymap (keymap-parents xwem-default-parent-map))
    (set-keymap-parents xwem-default-parent-map
                        (cons keymap (keymap-parents xwem-default-parent-map)))))


;;; Keys echoing
(defvar xwem-kbd-echoing-keys nil "Non-nil mean we are echoing command keys.")
(defvar xwem-kbd-scheduled-keys [] "Keys scheduled for echoing.")
(defvar xwem-kbd-scheduled-timer nil)

(defun xwem-kbd-echo-command-keys (&optional skip)
  "Echo keys."
  (xwem-clear-message 'keys-continuator)
  ;; Clear echo area if not yet reading, otherwise remove continuator
  (if (and (not xwem-kbd-echoing-keys)
           (not (eq (current-message-label) 'prompt)))
      (xwem-clear-message)
    (xwem-clear-message 'keys))
  (xwem-message-append 'keys "%s " (key-description xwem-kbd-scheduled-keys))
  (unless skip
    (xwem-message-append 'keys-continuator "-"))

  (setq xwem-kbd-echoing-keys t))

(defun xwem-kbd-echo-keys-timer (&rest not-used)
  "Timer to call when there a need to show command keys."
  (when (> (length xwem-kbd-scheduled-keys) 0)
    (xwem-kbd-echo-command-keys))
  (setq xwem-kbd-scheduled-timer nil))

;;;###xwem-autoload
(defun xwem-kbd-schedule-command-keys-echoing ()
  "Schedule echoing pressed KEY in minibuffer."
  (when (X-Event-p xwem-last-xevent)
    ;; Echo only for events which has corresponding X Event.
    (when xwem-kbd-scheduled-timer
      (disable-timeout xwem-kbd-scheduled-timer)
      (setq xwem-kbd-scheduled-timer nil))
    (when (numberp xwem-keyboard-echo-keystrokes)
      (setq xwem-kbd-scheduled-keys
            (vconcat xwem-kbd-scheduled-keys (list xwem-last-event)))
      (if xwem-kbd-echoing-keys
          (xwem-kbd-echo-command-keys t)
        (xwem-deffered-funcall
         #'(lambda ()
             (when (numberp xwem-keyboard-echo-keystrokes)
               (setq xwem-kbd-scheduled-timer
                     (add-timeout xwem-keyboard-echo-keystrokes
                                  'xwem-kbd-echo-keys-timer nil)))))))))

;;;###xwem-autoload
(defun xwem-kbd-stop-command-keys-echoing ()
  "Stop echoing."
  (when xwem-kbd-scheduled-timer
    (disable-timeout xwem-kbd-scheduled-timer)
    (setq xwem-kbd-scheduled-timer nil))
  
  (unless xwem-kbd-echoing-keys
    (xwem-clear-message 'keys))
  (xwem-clear-message 'keys-continuator)

  (setq xwem-kbd-scheduled-keys []
        xwem-kbd-echoing-keys nil))

;;;###xwem-autoload
(defun xwem-kbd-fixup-keymap (keymap)
  "Return fixed KEYMAP.
KEYMAP might be valid keymap or symbol, which `symbol-function' is keymap.
If KEYMAP can't be fixed, just return it."
  (unless (null keymap)
    (let (done kmap)
      (while (not done)
        (condition-case nil
            (setq kmap (indirect-function keymap))
          (t (setq kmap nil)))
        (cond ((keymapp kmap)
               (setq done t))

              ;; Handle autoload
              ((and (symbolp keymap)
                    (consp kmap)
                    (eq (car kmap) 'autoload)
                    (eq (car (cdr (cdr (cdr (cdr kmap))))) 'keymap))
               (load (cadr kmap)))

              (t (setq done t))))
      kmap)))

(defun xwem-kbd-keymap-plist (keymap)
  "Return KEYMAP's plist."
  (when (and (symbolp keymap)
             (keymapp (xwem-kbd-fixup-keymap keymap)))
    (symbol-plist keymap)))
  
;;;###xwem-autoload
(defun xwem-kbd-current-map ()
  "Return current prefix map."
  (let ((cm (or xwem-kbd-private-prefix-map
                xwem-override-map
                xwem-override-local-map
                (and (xwem-cl-p xwem-event-client)
                     (xwem-local-map xwem-event-client))
                xwem-override-global-map
                xwem-global-map)))
    (xwem-kbd-fixup-keymap cm)))

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

;;;###xwem-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)

;;;###xwem-autoload
(defun xwem-lookup-map (client keys &optional accept-default)
  "Lookup keymap where KEYS command is defined."
  (unless client
    (setq client (xwem-cl-selected)))

  (let (lkmap bind)
    (cond ((setq lkmap (or xwem-kbd-private-prefix-map
                           xwem-override-map
                           xwem-override-local-map))
           (and (lookup-key (xwem-kbd-fixup-keymap lkmap) keys accept-default)
                lkmap))

          ;; Try local keymap
          ((and (setq lkmap (xwem-local-map client))
                (setq bind (lookup-key (xwem-kbd-fixup-keymap lkmap) keys accept-default)))
           (and bind lkmap))

          ;; Try minor modes keymaps and global keymap
          (t (let* ((mm-bind (xwem-minor-mode-key-binding client keys accept-default))
                    (mm-km-sym (and mm-bind
                                    (cdr (assq (car mm-bind) xwem-minor-mode-map-alist))))
                    (mm-km (and mm-km-sym
                                (if (xwem-client-local-variable-p mm-km-sym)
                                    (xwem-client-local-variable-value client mm-km-sym)
                                  (symbol-value mm-km-sym)))))
               ;; If no minor mode keymap, use global map
               (or mm-km
                   (and (lookup-key (xwem-kbd-fixup-keymap xwem-global-map)
                                    keys accept-default)
                        xwem-global-map)))))))

;;;###xwem-autoload
(defun xwem-global-key-binding (cl keys &optional accept-default)
  "Return global binding for KEYS."
  (lookup-key xwem-global-map keys accept-default))
  
;;;###xwem-autoload
(defun xwem-local-key-binding (cl keys &optional accept-default)
  "Return local binding for KEYS."
  (let ((lkmap (xwem-local-map cl)))
    (and (keymapp lkmap)
         (lookup-key lkmap keys accept-default))))

;;;###xwem-autoload
(defun xwem-minor-mode-key-binding (cl keys &optional accept-default)
  "Return CL's minor mode binding for KEYS.
Retun cons cell in form `(MODENAME . BINDING)'."
  (let ((mlist xwem-minor-mode-map-alist)
        (bind nil))
    ;; Scan minor modes for binding
    (while (and mlist (not bind))
      (let ((mode-sym (car (car mlist)))
            (km-sym (cdr (car mlist)))
            kmap)
        (when (if (xwem-client-local-variable-p mode-sym)
                  (xwem-client-local-variable-value cl mode-sym)
                (symbol-value mode-sym))
          (setq kmap (if (xwem-client-local-variable-p km-sym)
                         (xwem-client-local-variable-value cl km-sym)
                       (symbol-value km-sym)))
          (when (keymapp kmap)
            (setq bind (lookup-key kmap keys accept-default)))))
      (unless bind
        (setq mlist (cdr mlist))))
    (when bind
      (cons (car (car mlist)) bind))))

;;;###xwem-autoload
(defun xwem-lookup-key (client keys &optional accept-default)
  "In CLIENT's context, lookup for KEYS binding.
`xwem-lookup-key' omits default binding unless ACCEPT-DEFAULT is
non-nil."
  (unless client
    (setq client (xwem-cl-selected)))

  (let (lkmap)
    (if (setq lkmap (or (and (= (length keys) 1)
                             xwem-kbd-private-prefix-map)
                        xwem-override-map
                        xwem-override-local-map))
        (lookup-key (xwem-kbd-fixup-keymap lkmap) keys accept-default)

      ;; Try looking up in next order:
      ;;   - Minor modes map
      ;;   - Local map
      ;;   - Default parent map
      ;;   - Global map
      (or (cdr (xwem-minor-mode-key-binding client keys accept-default))
          (xwem-local-key-binding client keys accept-default)
          (xwem-global-key-binding client keys accept-default)))))

;;;###xwem-autoload
(defun xwem-kbd-get-binding (keys &optional client reject-default)
  "Get binding value for KEYS for CLIENT.
By default CLIENT is currently selected client.
If optional REJECT-DEFAULT is non-nil, skip looking up default binding
\(pass `nil' as ACCEPT-DEFAULT to `lookup-key'\)."
  (xwem-lookup-key client keys (not reject-default)))

(defun xwem-kbd-fixate-current-lkm (lkm)
  "In case LKM is not usable, fixate it.
Return fixated LKM."
  (when (null lkm)
    (let ((etk (events-to-keys (vector xwem-last-event))))
      (cond ((equal etk xwem-help-key)
             (setq lkm xwem-prefix-help-command))
            ((equal etk xwem-quit-key)
             (setq lkm xwem-quit-command))

            ;; Last chance in re-lookup command keys
            (t (setq lkm (or (xwem-lookup-key xwem-event-client xwem-this-command-keys)
                             (xwem-lookup-key xwem-event-client xwem-this-command-keys t)))))))
  lkm)
  
;;;###xwem-autoload
(defun xwem-kbd-dispatch-binding (lkm)
  "Process keymap or command entry LKM after `lookup-key'.
Return non-nil if some action was performed."
  ;; Check for special mode, when we just reading single keystroke
  (when xwem-kbd-reading-key
    (xwem-read-keys-stop nil))

  ;; Fixate LKM, if it is bad
  (setq lkm (xwem-kbd-fixate-current-lkm lkm))

  (xwem-debug 'xwem-event "KBD Dispatcher: %S, lkm = %S"
              'xwem-this-command-keys 'lkm)

  (if (keymapp (xwem-kbd-fixup-keymap lkm))
      (progn
        ;; Subkeymap
        (xwem-kbd-set-current-prefix-keymap lkm)
        (xwem-kbd-start-grabbing (eval (plist-get (xwem-kbd-keymap-plist lkm) 'cursor)))

        ;; Show keymap's prompt
        (let ((prompt (or (eval (plist-get (xwem-kbd-keymap-plist lkm) 'prompt))
                          (keymap-prompt lkm))))
          (if prompt
              (xwem-message 'prompt "%s" prompt)
            (xwem-kbd-schedule-command-keys-echoing))))

    ;; 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
    (xwem-unwind-protect
        (cond ((or (vectorp lkm) (stringp lkm))
               ;; Keyboard macro.
               ;; Wait for keyrelease, ungrab keyboard, than play it.
               (when (and (X-Event-p xwem-last-xevent)
                          (= (X-Event-type xwem-last-xevent) X-KeyPress))
                 (xwem-kbd-wait-key-release (X-Event-xkey-keycode xwem-last-xevent)))
               (xwem-kbd-schedule-command-keys-echoing)
               (xwem-kbd-stop-grabbing)
               (xwem-keymacro-internal-play lkm (prefix-numeric-value xwem-prefix-arg)))

              ((commandp lkm)
               ;; Fix LKM in case it is frame command
               (when (and (symbolp lkm)
                          (get lkm 'xwem-frame-command)
                          (not (or (xwem-frame-p (xwem-cl-frame xwem-event-client))
                                   (eq (xwem-dummy-client) xwem-event-client))))
                 (setq lkm 'ignore))
               (xwem-kbd-schedule-command-keys-echoing)

               ;; Execute LKM command
               (setq xwem-this-command lkm)
               (run-hooks 'xwem-pre-command-hook)
               (call-interactively xwem-this-command)
               (setq xwem-last-command xwem-this-command)
               (run-hooks 'xwem-post-command-hook))

              ((null lkm)
               ;; Just echo key
               (xwem-kbd-schedule-command-keys-echoing))

              (t (error 'xwem-error (format "Unknown command: '%S'" lkm))))
     
      ;; XXX Generic post command processing
      (when (xwem-kbd-global-map-current-p)
        (setq xwem-this-command-keys []))
      ;; Do it deffering, becase there maybe pending command events
      ;; which need to be processed.
      (xwem-deffered-funcall
       #'(lambda ()
           (when (xwem-kbd-global-map-current-p)
             (xwem-kbd-stop-command-keys-echoing)
             (xwem-kbd-stop-grabbing)))))

    (and lkm 'done)))

;;}}}

;;{{{ [-] Grabbing

;;;###xwem-autoload
(defun xwem-kbd-graugra-key (key win mode &optional button-mask pgrab-mode kgrab-mode)
  "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."
  (xwem-keyboard-init)                  ; make sure keyboard initialised

  (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 pgrab-mode kgrab-mode)
                              (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 pgrab-mode kgrab-mode)
                            (XUngrabKey (xwem-dpy) ksyko (Xmask-or kmods m1 m2) win))))
                    xwem-kbd-evilmasks))
          xwem-kbd-evilmasks)
    ))

(defun xwem-kbd-grab-key (key win &optional pgrab kgrab)
  "Grab KEY on WIN."
  (xwem-kbd-graugra-key key win 'grab nil pgrab kgrab))

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

;;;###xwem-autoload
(defun xwem-kbd-install-grab (keymap win &optional pgrab kgrab)
  "Install KEYMAP grabs on X window WIN."
  (map-keymap #'(lambda (key bind)
                  (unless (and (symbolp bind) (get bind 'xwem-no-grab))
                    (xwem-kbd-grab-key key win pgrab kgrab)))
              (xwem-kbd-fixup-keymap keymap))

  ;; Also grab KEYMAP's parents
  (mapc #'(lambda (pkeymap)
            (xwem-kbd-install-grab pkeymap win pgrab kgrab))
        (keymap-parents (xwem-kbd-fixup-keymap keymap))))

;;;###xwem-autoload
(defun xwem-kbd-uninstall-grab (keymap win &optional predict)
  "Uninstall KEYMAP grabs on X window WIN.

Optionally you can specify PREDICT to decide for which keys grabbing
should be uinstalled.  PREDICT must accept two arguments - KEY and
BINDING, and return non-nil if this KEY must be ungrabbed.

By default all keys are ungrabbed."
  (map-keymap #'(lambda (key bind)
                  (when (or (not predict)
                            (funcall predict key bind))
                    (xwem-kbd-ungrab-key key win)))
              (xwem-kbd-fixup-keymap keymap))

  ;; Also ungrab KEYMAP's parents
  (mapc #'(lambda (pkeymap)
            (xwem-kbd-uninstall-grab pkeymap win predict))
        (keymap-parents (xwem-kbd-fixup-keymap keymap))))

(defun xwem-kbd-apply-grabbing ()
  "Start/stop grabbing according to `xwem-kbd-now-grabbing'."
  (if xwem-kbd-now-grabbing
      (unless (xwem-keymacro-executing-p)
        (XGrabKeyboard (xwem-dpy) (or (xwem-cl-xwin (xwem-dummy-client))
                                      (xwem-rootwin)))
        (xwem-mouse-grab xwem-kbd-now-grabbing)
        (XAllowEvents (xwem-dpy) X-SyncBoth))
    (unless (xwem-keymacro-executing-p)
      (XUngrabKeyboard (xwem-dpy))
      (xwem-mouse-ungrab))))
    
;;;###xwem-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
    (setq xwem-kbd-now-grabbing (or cursor xwem-cursor-wait))
    (xwem-kbd-apply-grabbing)))

;;;###xwem-autoload
(defun xwem-kbd-stop-grabbing ()
  "Stop grabbing keyboard."
  (when xwem-kbd-now-grabbing
    (setq xwem-kbd-now-grabbing nil)
    (xwem-kbd-apply-grabbing)))

;;;###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))
        xev)
    (when (X-Win-p xwin)
      (XGrabKeyboard (xwem-dpy) xwin nil X-GrabModeSync X-GrabModeSync)
      (XGrabPointer (xwem-dpy) xwin (Xmask-or XM-ButtonPress XM-ButtonRelease)
                    xwem-cursor-quote nil X-GrabModeSync X-GrabModeSync)
      (XAllowEvents (xwem-dpy) X-SyncBoth)

      (xwem-message 'prompt "[Quote key]")
      (xwem-unwind-protect
          (while (and (setq xev (xwem-next-event nil
                                                 (list X-KeyPress X-KeyRelease X-ButtonPress X-ButtonRelease)))
                      (not (xwem-xevents->emacs-events (list xev) t) ))
            (XAllowEvents (xwem-dpy) X-SyncBoth))
        (XAllowEvents (xwem-dpy) X-ReplayKeyboard)
        (XAllowEvents (xwem-dpy) X-ReplayPointer)
        (XUngrabKeyboard (xwem-dpy))
        (XUngrabPointer (xwem-dpy))
        (xwem-clear-message)))))

;;}}}

;;{{{ [-] Initializators

(defun xwem-kbd-filter-keycodes (keycodes)
  "Filter valid keycodes from KEYCODES list."
  (delq nil (mapcar #'(lambda (kc)
                        (and (>= kc (X-Dpy-min-keycode (xwem-dpy)))
                             (<= kc (X-Dpy-max-keycode (xwem-dpy)))
                             kc))
		    keycodes)))

;;;###xwem-autoload
(defun xwem-kbd-initialize-modifiers ()
  "Create internal modifier representation to speedup futher work.
Also update `xwem-kbd-evilmasks' if `xwem-kbd-evillocks' is non-nil."
  (setq xwem-xmods-mapping
        (car (last (XGetModifierMapping (xwem-dpy)))))

  (let* ((alts (list (car (xwem-kbd-xksym->xkcode XK-Alt-L))
                     (car (xwem-kbd-xksym->xkcode XK-Alt-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 (list X-Mod1 X-Mod2 X-Mod3 X-Mod4 X-Mod5))
         (slist (nthcdr 3 xwem-xmods-mapping)))

    ;; Clear modifiers info
    (mapc #'(lambda (mod-sym)
              (put mod-sym 'x-key-codes nil)
              (put mod-sym 'x-mod-mask nil))
          '(shift lock control alt meta hyper super numlock))

    ;; Shift
    (put 'shift 'x-key-codes
	 (xwem-kbd-filter-keycodes (nth 0 xwem-xmods-mapping)))
    (put 'shift 'x-mod-mask X-Shift)
    ;; Lock
    (put 'lock 'x-key-codes
	 (xwem-kbd-filter-keycodes (nth 1 xwem-xmods-mapping)))
    (put 'lock 'x-mod-mask X-Lock)
    ;; Control
    (put 'control 'x-key-codes
	 (xwem-kbd-filter-keycodes (nth 2 xwem-xmods-mapping)))
    (put 'control 'x-mod-mask X-Control)

    (while slist
      ;; Update some private modifier mask
      (mapc #'(lambda (mods mod-sym)
                (let ((ism (xwem-kbd-filter-keycodes
                            (intersection (car slist) mods))))
                  (when ism
                    (put mod-sym 'x-key-codes
                         (nconc ism (get mod-sym 'x-key-codes)))
                    (put mod-sym 'x-mod-mask
                         (Xmask-or (car mlist)
                                   (or (get mod-sym 'x-mod-mask) 0))))))
            (list alts metas hypers supers numlocks)
            (list 'alt 'meta 'hyper 'super 'numlock))

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

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

    ;; Hack over Alt-Meta problem
    (when (eql (get 'alt 'x-mod-mask) (get 'meta 'x-mod-mask))
      (put 'alt 'x-mod-mask 0))))

(defun xwem-keyboard-init ()
  "Initialize xwem keyboard.
Fetches KeyboardMapping from the X server and stores it in
`xwem-xkeys-mapping'"
  (unless (get 'xwem-keyboard 'initialized)
    (xwem-message 'init "Initializing keyboard ...")

    (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)))))

    ;; Initialize modifiers
    (xwem-kbd-initialize-modifiers)

    ;; Some messaging configuration
    (add-to-list 'xwem-messages-ignore-labels 'keys)
    (add-to-list 'xwem-messages-ignore-labels 'keys-continuator)

    (run-hooks 'xwem-keyboard-init-hook)
    (put 'xwem-keyboard 'initialized t)
    (xwem-message 'init "Initializing keyboard ... done")))

;;}}}

;;{{{ [-] 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].")

(defvar xwem-universal-argument-num-events nil
  "Number of argument-specifying events read by
`xwem-universal-argument'.")

(defun xwem-universal-common-begin ()
  "Common begin for universal argument."
  (setq xwem-universal-argument-num-events
        (length xwem-this-command-keys))
  (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))
  (setq xwem-universal-argument-num-events (length xwem-this-command-keys)))

;;;###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 (or (and (key-press-event-p xwem-last-event)
                       (event-key xwem-last-event))
                  (and (listp xwem-last-event)
                       (car (last 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)))

;;;###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)
  (setq xwem-override-map nil)

  ;; Reprocess last event
  ;; XXX Avoid double keys echoing
  (setq xwem-kbd-scheduled-keys
        (vconcat (butlast (append xwem-kbd-scheduled-keys nil))))
  (xwem-dispatch-command-event xwem-last-event xwem-last-xevent))

;;}}}


(provide 'xwem-keyboard)

;;;; On-load actions:
(if xwem-started
    (xwem-keyboard-init)
  (add-hook 'xwem-before-init-wins-hook 'xwem-keyboard-init))

;;; xwem-keyboard.el ends here