(Vw32_pass_optional_keys_to_system): Variable removed.
[bpt/emacs.git] / src / w32fns.c
index 7850e20..c11c3d5 100644 (file)
@@ -28,6 +28,8 @@ Boston, MA 02111-1307, USA.  */
 #include <errno.h>
 
 #include "lisp.h"
+#include "charset.h"
+#include "fontset.h"
 #include "w32term.h"
 #include "frame.h"
 #include "window.h"
@@ -38,6 +40,7 @@ Boston, MA 02111-1307, USA.  */
 #include "paths.h"
 #include "w32heap.h"
 #include "termhooks.h"
+#include "coding.h"
 
 #include <commdlg.h>
 #include <shellapi.h>
@@ -47,6 +50,8 @@ extern void free_frame_menubar ();
 extern struct scroll_bar *x_window_to_scroll_bar ();
 extern int quit_char;
 
+extern char *lispy_function_keys[];
+
 /* The colormap for converting color names to RGB values */
 Lisp_Object Vw32_color_map;
 
@@ -57,9 +62,34 @@ Lisp_Object Vw32_pass_alt_to_system;
    to alt_modifier.  */
 Lisp_Object Vw32_alt_is_meta;
 
-/* Non nil if left window, right window, and application key events
-   are passed on to Windows.  */
-Lisp_Object Vw32_pass_optional_keys_to_system;
+/* Non nil if left window key events are passed on to Windows (this only
+   affects whether "tapping" the key opens the Start menu).  */
+Lisp_Object Vw32_pass_lwindow_to_system;
+
+/* Non nil if right window key events are passed on to Windows (this
+   only affects whether "tapping" the key opens the Start menu).  */
+Lisp_Object Vw32_pass_rwindow_to_system;
+
+/* Modifier associated with the left "Windows" key, or nil to act as a
+   normal key.  */
+Lisp_Object Vw32_lwindow_modifier;
+
+/* Modifier associated with the right "Windows" key, or nil to act as a
+   normal key.  */
+Lisp_Object Vw32_rwindow_modifier;
+
+/* Modifier associated with the "Apps" key, or nil to act as a normal
+   key.  */
+Lisp_Object Vw32_apps_modifier;
+
+/* Value is nil if Num Lock acts as a function key.  */
+Lisp_Object Vw32_enable_num_lock;
+
+/* Value is nil if Caps Lock acts as a function key.  */
+Lisp_Object Vw32_enable_caps_lock;
+
+/* Modifier associated with Scroll Lock, or nil to act as a normal key.  */
+Lisp_Object Vw32_scroll_lock_modifier;
 
 /* Switch to control whether we inhibit requests for italicised fonts (which
    are synthesized, look ugly, and are trashed by cursor movement under NT). */
@@ -97,6 +127,12 @@ static int w32_in_use;
 /* Search path for bitmap files.  */
 Lisp_Object Vx_bitmap_file_path;
 
+/* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.  */
+Lisp_Object Vx_pixel_size_width_font_regexp;
+
+/* A flag to control how to display unibyte 8-bit character.  */
+int unibyte_display_via_language_environment;
+
 /* Evaluate this expression to rebuild the section of syms_of_w32fns
    that initializes and staticpros the symbols declared below.  Note
    that Emacs 18 has a bug that keeps C-x C-e from being able to
@@ -189,11 +225,14 @@ extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
 
 extern Lisp_Object Vwindow_system_version;
 
+Lisp_Object Qface_set_after_frame_default;
+
 extern Lisp_Object last_mouse_scroll_bar;
 extern int last_mouse_scroll_bar_pos;
 
 /* From w32term.c. */
 extern Lisp_Object Vw32_num_mouse_buttons;
+extern Lisp_Object Vw32_recognize_altgr;
 
 \f
 /* Error if we are not connected to MS-Windows.  */
@@ -440,6 +479,9 @@ x_create_bitmap_from_file (f, file)
   fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
   if (fd < 0)
     return -1;
+  /* LoadLibraryEx won't handle special files handled by Emacs handler.  */
+  if (fd == 0)
+    return -1;
   close (fd);
 
   filename = (char *) XSTRING (found)->data;
@@ -1264,6 +1306,38 @@ w32_to_x_color (rgb)
     return Qnil;
 }
 
+COLORREF
+w32_color_map_lookup (colorname)
+     char *colorname;
+{
+  Lisp_Object tail, ret = Qnil;
+
+  BLOCK_INPUT;
+
+  for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
+    {
+      register Lisp_Object elt, tem;
+
+      elt = Fcar (tail);
+      if (!CONSP (elt)) continue;
+
+      tem = Fcar (elt);
+
+      if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
+       {
+         ret = XUINT (Fcdr (elt));
+         break;
+       }
+
+      QUIT;
+    }
+
+
+  UNBLOCK_INPUT;
+
+  return ret;
+}
+
 COLORREF 
 x_to_w32_color (colorname)
      char * colorname;
@@ -1428,27 +1502,30 @@ x_to_w32_color (colorname)
   /* I am not going to attempt to handle any of the CIE color schemes
      or TekHVC, since I don't know the algorithms for conversion to
      RGB.  */
-  
-  for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
+
+  /* If we fail to lookup the color name in w32_color_map, then check the
+     colorname to see if it can be crudely approximated: If the X color 
+     ends in a number (e.g., "darkseagreen2"), strip the number and
+     return the result of looking up the base color name.  */
+  ret = w32_color_map_lookup (colorname);
+  if (NILP (ret)) 
     {
-      register Lisp_Object elt, tem;
+      int len = strlen (colorname);
 
-      elt = Fcar (tail);
-      if (!CONSP (elt)) continue;
+      if (isdigit (colorname[len - 1])) 
+       {
+         char *ptr, *approx = alloca (len);
 
-      tem = Fcar (elt);
+         strcpy (approx, colorname);
+         ptr = &approx[len - 1];
+         while (ptr > approx && isdigit (*ptr)) 
+             *ptr-- = '\0';
 
-      if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
-       {
-         ret = XUINT(Fcdr (elt));
-         break;
+         ret = w32_color_map_lookup (approx);
        }
-
-      QUIT;
     }
   
   UNBLOCK_INPUT;
-  
   return ret;
 }
 
@@ -2039,6 +2116,7 @@ x_set_icon_name (f, arg, oldval)
 }
 
 extern Lisp_Object x_new_font ();
+extern Lisp_Object x_new_fontset();
 
 void
 x_set_font (f, arg, oldval)
@@ -2046,11 +2124,17 @@ x_set_font (f, arg, oldval)
      Lisp_Object arg, oldval;
 {
   Lisp_Object result;
+  Lisp_Object fontset_name;
+  Lisp_Object frame;
 
   CHECK_STRING (arg, 1);
 
+  fontset_name = Fquery_fontset (arg, Qnil);
+
   BLOCK_INPUT;
-  result = x_new_font (f, XSTRING (arg)->data);
+  result = (STRINGP (fontset_name)
+            ? x_new_fontset (f, XSTRING (fontset_name)->data)
+            : x_new_font (f, XSTRING (arg)->data));
   UNBLOCK_INPUT;
   
   if (EQ (result, Qnil))
@@ -2064,6 +2148,9 @@ x_set_font (f, arg, oldval)
     }
   else
     abort ();
+
+  XSETFRAME (frame, f);
+  call1 (Qface_set_after_frame_default, frame);
 }
 
 void
@@ -2828,7 +2915,7 @@ w32_init_class (hinst)
   wc.hInstance = hinst;
   wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
   wc.hCursor = LoadCursor (NULL, IDC_ARROW);
-  wc.hbrBackground = NULL; // GetStockObject (WHITE_BRUSH);
+  wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH);  */
   wc.lpszMenuName = NULL;
   wc.lpszClassName = EMACS_CLASS;
 
@@ -2900,17 +2987,6 @@ w32_createwindow (f)
     }
 }
 
-/* Convert between the modifier bits W32 uses and the modifier bits
-   Emacs uses.  */
-unsigned int
-w32_get_modifiers ()
-{
-  return (((GetKeyState (VK_SHIFT)&0x8000)   ? shift_modifier  : 0) |
-         ((GetKeyState (VK_CONTROL)&0x8000) ? ctrl_modifier   : 0) |
-          ((GetKeyState (VK_MENU)&0x8000)    ? 
-          ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
-}
-
 void 
 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
      W32Msg * wmsg;
@@ -3057,7 +3133,7 @@ sync_modifiers ()
 static int
 modifier_set (int vkey)
 {
-  if (vkey == VK_CAPITAL)
+  if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
     return (GetKeyState (vkey) & 0x1);
   if (!modifiers_recorded)
     return (GetKeyState (vkey) & 0x8000);
@@ -3072,56 +3148,215 @@ modifier_set (int vkey)
       return modifiers[EMACS_LMENU];
     case VK_RMENU:
       return modifiers[EMACS_RMENU];
-    default:
-      break;
     }
   return (GetKeyState (vkey) & 0x8000);
 }
 
+/* Convert between the modifier bits W32 uses and the modifier bits
+   Emacs uses.  */
+
+unsigned int
+w32_key_to_modifier (int key)
+{
+  Lisp_Object key_mapping;
+
+  switch (key)
+    {
+    case VK_LWIN:
+      key_mapping = Vw32_lwindow_modifier;
+      break;
+    case VK_RWIN:
+      key_mapping = Vw32_rwindow_modifier;
+      break;
+    case VK_APPS:
+      key_mapping = Vw32_apps_modifier;
+      break;
+    case VK_SCROLL:
+      key_mapping = Vw32_scroll_lock_modifier;
+      break;
+    default:
+      key_mapping = Qnil;
+    }
+
+  if (EQ (key_mapping, intern ("hyper")))
+    return hyper_modifier;
+  if (EQ (key_mapping, intern ("super")))
+    return super_modifier;
+  if (EQ (key_mapping, intern ("meta")))
+    return meta_modifier;
+  if (EQ (key_mapping, intern ("alt")))
+    return alt_modifier;
+  if (EQ (key_mapping, intern ("ctrl")))
+    return ctrl_modifier;
+  if (EQ (key_mapping, intern ("control"))) /* synonym for ctrl */
+    return ctrl_modifier;
+  if (EQ (key_mapping, intern ("shift")))
+    return shift_modifier;
+
+  /* Don't generate any modifier if not explicitly requested.  */
+  return 0;
+}
+
+unsigned int
+w32_get_modifiers ()
+{
+  return ((modifier_set (VK_SHIFT)   ? shift_modifier : 0) |
+         (modifier_set (VK_CONTROL) ? ctrl_modifier  : 0) |
+         (modifier_set (VK_LWIN)    ? w32_key_to_modifier (VK_LWIN) : 0) |
+         (modifier_set (VK_RWIN)    ? w32_key_to_modifier (VK_RWIN) : 0) |
+         (modifier_set (VK_APPS)    ? w32_key_to_modifier (VK_APPS) : 0) |
+         (modifier_set (VK_SCROLL)  ? w32_key_to_modifier (VK_SCROLL) : 0) |
+          (modifier_set (VK_MENU)    ?
+          ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
+}
+
 /* We map the VK_* modifiers into console modifier constants
    so that we can use the same routines to handle both console
    and window input.  */
 
 static int
-construct_modifiers (unsigned int wparam, unsigned int lparam)
+construct_console_modifiers ()
 {
   int mods;
 
-  if (wparam != VK_CONTROL && wparam != VK_MENU)
-    mods = GetLastError ();
-
   mods = 0;
   mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
   mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
+  mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
+  mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
   mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
   mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
   mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
   mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
+  mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
+  mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
+  mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
 
   return mods;
 }
 
-static unsigned int
-map_keypad_keys (unsigned int wparam, unsigned int lparam)
+static int
+w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
 {
-  unsigned int extended = (lparam & 0x1000000L);
+  int mods;
 
-  if (wparam < VK_CLEAR || wparam > VK_DELETE)
-    return wparam;
+  /* Convert to emacs modifiers.  */
+  mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
 
-  if (wparam == VK_RETURN)
+  return mods;
+}
+
+unsigned int
+map_keypad_keys (unsigned int virt_key, unsigned int extended)
+{
+  if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
+    return virt_key;
+
+  if (virt_key == VK_RETURN)
     return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
 
-  if (wparam >= VK_PRIOR && wparam <= VK_DOWN)
-    return (!extended ? (VK_NUMPAD_PRIOR + (wparam - VK_PRIOR)) : wparam);
+  if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
+    return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
+
+  if (virt_key == VK_INSERT || virt_key == VK_DELETE)
+    return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
+
+  if (virt_key == VK_CLEAR)
+    return (!extended ? VK_NUMPAD_CLEAR : virt_key);
+
+  return virt_key;
+}
+
+/* List of special key combinations which w32 would normally capture,
+   but emacs should grab instead.  Not directly visible to lisp, to
+   simplify synchronization.  Each item is an integer encoding a virtual
+   key code and modifier combination to capture.  */
+Lisp_Object w32_grabbed_keys;
+
+#define HOTKEY(vk,mods)       make_number (((vk) & 255) | ((mods) << 8))
+#define HOTKEY_ID(k)          (XFASTINT (k) & 0xbfff)
+#define HOTKEY_VK_CODE(k)     (XFASTINT (k) & 255)
+#define HOTKEY_MODIFIERS(k)   (XFASTINT (k) >> 8)
+
+/* Register hot-keys for reserved key combinations when Emacs has
+   keyboard focus, since this is the only way Emacs can receive key
+   combinations like Alt-Tab which are used by the system.  */
+
+static void
+register_hot_keys (hwnd)
+     HWND hwnd;
+{
+  Lisp_Object keylist;
 
-  if (wparam == VK_INSERT || wparam == VK_DELETE)
-    return (!extended ? (VK_NUMPAD_INSERT + (wparam - VK_INSERT)) : wparam);
+  /* Use GC_CONSP, since we are called asynchronously.  */
+  for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
+    {
+      Lisp_Object key = XCAR (keylist);
 
-  if (wparam == VK_CLEAR)
-    return (!extended ? VK_NUMPAD_CLEAR : wparam);
+      /* Deleted entries get set to nil.  */
+      if (!INTEGERP (key))
+       continue;
 
-  return wparam;
+      RegisterHotKey (hwnd, HOTKEY_ID (key),
+                     HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
+    }
+}
+
+static void
+unregister_hot_keys (hwnd)
+     HWND hwnd;
+{
+  Lisp_Object keylist;
+
+  /* Use GC_CONSP, since we are called asynchronously.  */
+  for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
+    {
+      Lisp_Object key = XCAR (keylist);
+
+      if (!INTEGERP (key))
+       continue;
+
+      UnregisterHotKey (hwnd, HOTKEY_ID (key));
+    }
+}
+
+static void
+post_character_message (hwnd, msg, wParam, lParam, modifiers)
+     HWND hwnd;
+     UINT msg;
+     WPARAM wParam;
+     LPARAM lParam;
+     DWORD  modifiers;
+
+{
+  W32Msg wmsg;
+
+  wmsg.dwModifiers = modifiers;
+
+  /* Detect quit_char and set quit-flag directly.  Note that we
+     still need to post a message to ensure the main thread will be
+     woken up if blocked in sys_select(), but we do NOT want to post
+     the quit_char message itself (because it will usually be as if
+     the user had typed quit_char twice).  Instead, we post a dummy
+     message that has no particular effect. */
+  {
+    int c = wParam;
+    if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
+      c = make_ctrl_char (c) & 0377;
+    if (c == quit_char)
+      {
+       Vquit_flag = Qt;
+
+       /* The choice of message is somewhat arbitrary, as long as
+          the main thread handler just ignores it. */
+       msg = WM_NULL;
+
+       /* Interrupt any blocking system calls.  */
+       signal_quit ();
+      }
+  }
+
+  my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
 }
 
 /* Main message dispatch loop. */
@@ -3130,6 +3365,8 @@ static void
 w32_msg_pump (deferred_msg * msg_buf)
 {
   MSG msg;
+  int result;
+  HWND focus_window;
 
   msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
   
@@ -3148,9 +3385,31 @@ w32_msg_pump (deferred_msg * msg_buf)
              SetThreadLocale (msg.wParam);
              /* Reply is not expected.  */
              break;
+           case WM_EMACS_SETKEYBOARDLAYOUT:
+             result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
+             if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
+                                     result, 0))
+               abort ();
+             break;
+           case WM_EMACS_REGISTER_HOT_KEY:
+             focus_window = GetFocus ();
+             if (focus_window != NULL)
+               RegisterHotKey (focus_window,
+                               HOTKEY_ID (msg.wParam),
+                               HOTKEY_MODIFIERS (msg.wParam),
+                               HOTKEY_VK_CODE (msg.wParam));
+             /* Reply is not expected.  */
+             break;
+           case WM_EMACS_UNREGISTER_HOT_KEY:
+             focus_window = GetFocus ();
+             if (focus_window != NULL)
+               UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
+             /* Mark item as erased.  */
+             XCAR ((Lisp_Object) msg.lParam) = Qnil;
+             if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
+               abort ();
+             break;
            default:
-             /* No need to be so draconian!  */
-             /* abort (); */
              DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
            }
        }
@@ -3267,8 +3526,6 @@ w32_msg_worker (dw)
 
 /* Main window procedure */
 
-extern char *lispy_function_keys[];
-
 LRESULT CALLBACK 
 w32_wnd_proc (hwnd, msg, wParam, lParam)
      HWND hwnd;
@@ -3333,6 +3590,43 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
        return (0);
       }
 
+    case WM_INPUTLANGCHANGE:
+      /* Inform lisp thread of keyboard layout changes.  */
+      my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
+
+      /* Clear dead keys in the keyboard state; for simplicity only
+         preserve modifier key states.  */
+      {
+       int i;
+       BYTE keystate[256];
+
+       GetKeyboardState (keystate);
+       for (i = 0; i < 256; i++)
+         if (1
+             && i != VK_SHIFT
+             && i != VK_LSHIFT
+             && i != VK_RSHIFT
+             && i != VK_CAPITAL
+             && i != VK_NUMLOCK
+             && i != VK_SCROLL
+             && i != VK_CONTROL
+             && i != VK_LCONTROL
+             && i != VK_RCONTROL
+             && i != VK_MENU
+             && i != VK_LMENU
+             && i != VK_RMENU
+             && i != VK_LWIN
+             && i != VK_RWIN)
+           keystate[i] = 0;
+       SetKeyboardState (keystate);
+      }
+      goto dflt;
+
+    case WM_HOTKEY:
+      /* Synchronize hot keys with normal input.  */
+      PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
+      return (0);
+
     case WM_KEYUP:
     case WM_SYSKEYUP:
       record_keyup (wParam, lParam);
@@ -3340,40 +3634,161 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
 
     case WM_KEYDOWN:
     case WM_SYSKEYDOWN:
+      /* Ignore keystrokes we fake ourself; see below.  */
+      if (dpyinfo->faked_key == wParam)
+       {
+         dpyinfo->faked_key = 0;
+         return 0;
+       }
+
       /* Synchronize modifiers with current keystroke.  */
       sync_modifiers ();
-
       record_keydown (wParam, lParam);
-
-      wParam = map_keypad_keys (wParam, lParam);
+      wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
 
       windows_translate = 0;
-      switch (wParam) {
-      case VK_LWIN:
-      case VK_RWIN:
-      case VK_APPS:
-       /* More support for these keys will likely be necessary.  */
-       if (!NILP (Vw32_pass_optional_keys_to_system))
+
+      switch (wParam)
+       {
+       case VK_LWIN:
+         if (NILP (Vw32_pass_lwindow_to_system))
+           {
+             /* Prevent system from acting on keyup (which opens the
+                Start menu if no other key was pressed) by simulating a
+                press of Space which we will ignore.  */
+             if (GetAsyncKeyState (wParam) & 1)
+               {
+                 dpyinfo->faked_key = VK_SPACE;
+                 keybd_event (VK_SPACE,
+                              (BYTE) MapVirtualKey (VK_SPACE, 0), 0, 0);
+               }
+           }
+         if (!NILP (Vw32_lwindow_modifier))
+           return 0;
+         break;
+       case VK_RWIN:
+         if (NILP (Vw32_pass_rwindow_to_system))
+           {
+             if (GetAsyncKeyState (wParam) & 1)
+               {
+                 dpyinfo->faked_key = VK_SPACE;
+                 keybd_event (VK_SPACE,
+                              (BYTE) MapVirtualKey (VK_SPACE, 0), 0, 0);
+               }
+           }
+         if (!NILP (Vw32_rwindow_modifier))
+           return 0;
+         break;
+       case VK_APPS:
+         if (!NILP (Vw32_apps_modifier))
+           return 0;
+         break;
+       case VK_MENU:
+         if (NILP (Vw32_pass_alt_to_system)) 
+           return 0;
          windows_translate = 1;
-       break;
-      case VK_MENU:
-       if (NILP (Vw32_pass_alt_to_system)) 
+         break;
+       case VK_CAPITAL: 
+         /* Decide whether to treat as modifier or function key.  */
+         if (NILP (Vw32_enable_caps_lock))
+           goto disable_lock_key;
          return 0;
-       windows_translate = 1;
-       break;
-      case VK_CONTROL: 
-      case VK_CAPITAL: 
-      case VK_SHIFT:
-      case VK_NUMLOCK:
-      case VK_SCROLL: 
-       windows_translate = 1;
-       break;
-      default:
-       /* If not defined as a function key, change it to a WM_CHAR message. */
-       if (lispy_function_keys[wParam] == 0)
-         msg = WM_CHAR;
-       break;
-      }
+       case VK_NUMLOCK:
+         /* Decide whether to treat as modifier or function key.  */
+         if (NILP (Vw32_enable_num_lock))
+           goto disable_lock_key;
+         return 0;
+       case VK_SCROLL:
+         /* Decide whether to treat as modifier or function key.  */
+         if (NILP (Vw32_scroll_lock_modifier))
+           goto disable_lock_key;
+         return 0;
+       disable_lock_key:
+         /* Ensure the appropriate lock key state is off (and the
+             indicator light as well).  */
+         if (GetAsyncKeyState (wParam) & 0x8000)
+           {
+             /* Fake another press of the relevant key.  Apparently,
+                 this really is the only way to turn off the indicator.  */
+             dpyinfo->faked_key = wParam;
+             keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
+                          KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
+             keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
+                          KEYEVENTF_EXTENDEDKEY | 0, 0);
+             keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
+                          KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
+           }
+         break;
+       case VK_CONTROL: 
+       case VK_SHIFT:
+       case VK_PROCESSKEY:  /* Generated by IME.  */
+         windows_translate = 1;
+         break;
+       default:
+         /* If not defined as a function key, change it to a WM_CHAR message. */
+         if (lispy_function_keys[wParam] == 0)
+           {
+             if (!NILP (Vw32_recognize_altgr)
+                 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
+               {
+                 /* Always let TranslateMessage handle AltGr key chords;
+                    for some reason, ToAscii doesn't always process AltGr
+                    chords correctly.  */
+                 windows_translate = 1;
+               }
+             else if (modifier_set (VK_CONTROL) || modifier_set (VK_MENU))
+               {
+                 /* Handle key chords including any modifiers other than shift
+                    directly, in order to preserve as much modifier information as
+                    possible.  */
+                 if ('A' <= wParam && wParam <= 'Z')
+                   {
+                     /* Don't translate modified alphabetic keystrokes,
+                        so the user doesn't need to constantly switch
+                        layout to type control or meta keystrokes when
+                        the normal layout translates alphabetic
+                        characters to non-ascii characters.  */
+                     if (!modifier_set (VK_SHIFT))
+                       wParam += ('a' - 'A');
+                     msg = WM_CHAR;
+                   }
+                 else
+                   {
+                     /* Try to handle other keystrokes by determining the
+                        base character (ie. translating the base key plus
+                        shift modifier).  */
+                     int add;
+                     int isdead = 0;
+                     KEY_EVENT_RECORD key;
+                 
+                     key.bKeyDown = TRUE;
+                     key.wRepeatCount = 1;
+                     key.wVirtualKeyCode = wParam;
+                     key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
+                     key.uChar.AsciiChar = 0;
+                     key.dwControlKeyState = construct_console_modifiers ();
+
+                     add = w32_kbd_patch_key (&key);
+                     /* 0 means an unrecognised keycode, negative means
+                        dead key.  Ignore both.  */
+                     while (--add >= 0)
+                       {
+                         /* Forward asciified character sequence.  */
+                         post_character_message
+                           (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
+                            w32_get_key_modifiers (wParam, lParam));
+                         w32_kbd_patch_key (&key);
+                       }
+                     return 0;
+                   }
+               }
+             else
+               {
+                 /* Let TranslateMessage handle everything else.  */
+                 windows_translate = 1;
+               }
+           }
+       }
 
       if (windows_translate)
        {
@@ -3388,36 +3803,8 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
       
     case WM_SYSCHAR:
     case WM_CHAR:
-      wmsg.dwModifiers = construct_modifiers (wParam, lParam);
-
-#if 1
-      /* Detect quit_char and set quit-flag directly.  Note that we
-        still need to post a message to ensure the main thread will be
-        woken up if blocked in sys_select(), but we do NOT want to post
-        the quit_char message itself (because it will usually be as if
-        the user had typed quit_char twice).  Instead, we post a dummy
-        message that has no particular effect. */
-      {
-       int c = wParam;
-       if (isalpha (c) && (wmsg.dwModifiers == LEFT_CTRL_PRESSED 
-                           || wmsg.dwModifiers == RIGHT_CTRL_PRESSED))
-         c = make_ctrl_char (c) & 0377;
-       if (c == quit_char)
-         {
-           Vquit_flag = Qt;
-
-           /* The choice of message is somewhat arbitrary, as long as
-              the main thread handler just ignores it. */
-           msg = WM_NULL;
-
-           /* Interrupt any blocking system calls.  */
-           signal_quit ();
-         }
-      }
-#endif
-
-      my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
-
+      post_character_message (hwnd, msg, wParam, lParam,
+                             w32_get_key_modifiers (wParam, lParam));
       break;
 
       /* Simulate middle mouse button events when left and right buttons
@@ -3758,8 +4145,10 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
       goto dflt;
 #endif
 
-    case WM_ACTIVATE:
     case WM_ACTIVATEAPP:
+      dpyinfo->faked_key = 0;
+      reset_modifiers ();
+    case WM_ACTIVATE:
     case WM_WINDOWPOSCHANGED:
     case WM_SHOWWINDOW:
       /* Inform lisp thread that a frame might have just been obscured
@@ -3768,11 +4157,14 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
       goto dflt;
 
     case WM_SETFOCUS:
-      reset_modifiers ();
+      register_hot_keys (hwnd);
+      goto command;
     case WM_KILLFOCUS:
+      unregister_hot_keys (hwnd);
     case WM_MOVE:
     case WM_SIZE:
     case WM_COMMAND:
+    command:
       wmsg.dwModifiers = w32_get_modifiers ();
       my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
       goto dflt;
@@ -3892,6 +4284,7 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
        /* Remember we did a SetCapture on the initial mouse down event,
           so for safety, we make sure the capture is cancelled now.  */
        ReleaseCapture ();
+       button_state = 0;
 
        /* Use menubar_active to indicate that WM_INITMENU is from
            TrackPopupMenu below, and should be ignored.  */
@@ -3915,7 +4308,6 @@ w32_wnd_proc (hwnd, msg, wParam, lParam)
              {
                retval = 0;
              }
-           button_state = 0;
          }
        else
          {
@@ -4073,6 +4465,8 @@ This function is an internal primitive--use `make-frame' instead.")
   Lisp_Object parent;
   struct kboard *kb;
 
+  check_w32 ();
+
   /* Use this general default value to start with
      until we know if this frame has a specified name.  */
   Vx_resource_name = Vinvocation_name;
@@ -4132,6 +4526,8 @@ This function is an internal primitive--use `make-frame' instead.")
   f->output_data.w32 = (struct w32_output *) xmalloc (sizeof (struct w32_output));
   bzero (f->output_data.w32, sizeof (struct w32_output));
 
+  FRAME_FONTSET (f) = -1;
+
   f->icon_name
     = x_get_arg (parms, Qicon_name, "iconName", "Title", string);
   if (! STRINGP (f->icon_name))
@@ -4173,6 +4569,10 @@ This function is an internal primitive--use `make-frame' instead.")
       specbind (Qx_resource_name, name);
     }
 
+  /* Create fontsets from `global_fontset_alist' before handling fonts.  */
+  for (tem = Vglobal_fontset_alist; CONSP (tem); tem = XCONS (tem)->cdr)
+    fs_register_fontset (f, XCONS (tem)->car);
+
   /* Extract the window parameters from the supplied values
      that are needed to determine window geometry.  */
   {
@@ -4182,15 +4582,21 @@ This function is an internal primitive--use `make-frame' instead.")
     BLOCK_INPUT;
     /* First, try whatever font the caller has specified.  */
     if (STRINGP (font))
+      {
+        tem = Fquery_fontset (font, Qnil);
+        if (STRINGP (tem))
+          font = x_new_fontset (f, XSTRING (tem)->data);
+        else
       font = x_new_font (f, XSTRING (font)->data);
+      }
     /* Try out a font which we hope has bold and italic variations.  */
     if (!STRINGP (font))
-      font = x_new_font (f, "-*-Courier New-normal-r-*-*-13-97-*-*-c-*-*-ansi-");
+      font = x_new_font (f, "-*-Courier New-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
     if (! STRINGP (font))
-      font = x_new_font (f, "-*-Courier-normal-r-*-*-13-97-*-*-c-*-*-ansi-");
+      font = x_new_font (f, "-*-Courier-normal-r-*-*-*-97-*-*-c-*-iso8859-1");
     /* If those didn't work, look for something which will at least work.  */
     if (! STRINGP (font))
-      font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-13-97-*-*-c-*-*-ansi-");
+      font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-*-*-90-*-c-*-iso8859-1");
     UNBLOCK_INPUT;
     if (! STRINGP (font))
       font = build_string ("Fixedsys");
@@ -4357,20 +4763,70 @@ DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
 }
 
 \f
-XFontStruct *
-w32_load_font (dpyinfo,name)
-struct w32_display_info *dpyinfo;
-char * name;
+/* Load font named FONTNAME of size SIZE for frame F, and return a
+   pointer to the structure font_info while allocating it dynamically.
+   If loading fails, return NULL. */
+struct font_info *
+w32_load_font (f,fontname,size)
+struct frame *f;
+char * fontname;
+int size;
 {
-  XFontStruct * font = NULL;
-  BOOL ok;
+  struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
+  Lisp_Object font_names;
+
+#if 0   /* x_load_font attempts to get a list of fonts - presumably to
+           allow a fuzzier fontname to be specified. w32_list_fonts
+           appears to be a bit too fuzzy for this purpose. */
 
+  /* Get a list of all the fonts that match this name.  Once we
+     have a list of matching fonts, we compare them against the fonts
+     we already have loaded by comparing names.  */
+  font_names = w32_list_fonts (f, build_string (fontname), size, 100);
+
+  if (!NILP (font_names))
   {
+      Lisp_Object tail;
+      int i;
+
+#if 0 /* This code has nasty side effects that cause Emacs to crash.  */
+
+      /* First check if any are already loaded, as that is cheaper
+         than loading another one. */
+      for (i = 0; i < dpyinfo->n_fonts; i++)
+       for (tail = font_names; CONSP (tail); tail = XCONS (tail)->cdr)
+         if (!strcmp (dpyinfo->font_table[i].name,
+                      XSTRING (XCONS (tail)->car)->data)
+             || !strcmp (dpyinfo->font_table[i].full_name,
+                         XSTRING (XCONS (tail)->car)->data))
+           return (dpyinfo->font_table + i);
+#endif
+
+      fontname = (char *) XSTRING (XCONS (font_names)->car)->data;
+    }
+  else
+    return NULL;
+#endif
+
+  /* Load the font and add it to the table. */
+  {
+    char *full_name;
+    XFontStruct *font;
+    struct font_info *fontp;
     LOGFONT lf;
+    BOOL ok;
 
-    if (!name || !x_to_w32_font (name, &lf))
+    if (!fontname || !x_to_w32_font (fontname, &lf))
       return (NULL);
 
+    if (!*lf.lfFaceName)
+        /* If no name was specified for the font, we get a random font
+           from CreateFontIndirect - this is not particularly
+           desirable, especially since CreateFontIndirect does not
+           fill out the missing name in lf, so we never know what we
+           ended up with. */
+      return NULL;
+
     font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
 
     if (!font) return (NULL);
@@ -4378,30 +4834,95 @@ char * name;
     BLOCK_INPUT;
 
     font->hfont = CreateFontIndirect (&lf);
-  }
 
-  if (font->hfont == NULL) 
-    {
-      ok = FALSE;
-    } 
-  else 
-    {
-      HDC hdc;
-      HANDLE oldobj;
-
-      hdc = GetDC (dpyinfo->root_window);
-      oldobj = SelectObject (hdc, font->hfont);
-      ok = GetTextMetrics (hdc, &font->tm);
-      SelectObject (hdc, oldobj);
-      ReleaseDC (dpyinfo->root_window, hdc);
-    }
+    if (font->hfont == NULL) 
+      {
+       ok = FALSE;
+      
+    else 
+      {
+       HDC hdc;
+       HANDLE oldobj;
+
+       hdc = GetDC (dpyinfo->root_window);
+       oldobj = SelectObject (hdc, font->hfont);
+       ok = GetTextMetrics (hdc, &font->tm);
+       SelectObject (hdc, oldobj);
+       ReleaseDC (dpyinfo->root_window, hdc);
+      }
 
-  UNBLOCK_INPUT;
+    UNBLOCK_INPUT;
+
+    if (!ok)
+      {
+       w32_unload_font (dpyinfo, font);
+       return (NULL);
+      }
 
-  if (ok) return (font);
+    /* Do we need to create the table?  */
+    if (dpyinfo->font_table_size == 0)
+      {
+       dpyinfo->font_table_size = 16;
+       dpyinfo->font_table
+         = (struct font_info *) xmalloc (dpyinfo->font_table_size
+                                         * sizeof (struct font_info));
+      }
+    /* Do we need to grow the table?  */
+    else if (dpyinfo->n_fonts
+            >= dpyinfo->font_table_size)
+      {
+       dpyinfo->font_table_size *= 2;
+       dpyinfo->font_table
+         = (struct font_info *) xrealloc (dpyinfo->font_table,
+                                          (dpyinfo->font_table_size
+                                           * sizeof (struct font_info)));
+      }
 
-  w32_unload_font (dpyinfo, font);
-  return (NULL);
+    fontp = dpyinfo->font_table + dpyinfo->n_fonts;
+
+    /* Now fill in the slots of *FONTP.  */
+    BLOCK_INPUT;
+    fontp->font = font;
+    fontp->font_idx = dpyinfo->n_fonts;
+    fontp->name = (char *) xmalloc (strlen (fontname) + 1);
+    bcopy (fontname, fontp->name, strlen (fontname) + 1);
+
+    /* Work out the font's full name.  */
+    full_name = (char *)xmalloc (100);
+    if (full_name && w32_to_x_font (&lf, full_name, 100))
+        fontp->full_name = full_name;
+    else
+      {
+        /* If all else fails - just use the name we used to load it.  */
+        xfree (full_name);
+        fontp->full_name = fontp->name;
+      }
+
+    fontp->size = FONT_WIDTH (font);
+    fontp->height = FONT_HEIGHT (font);
+
+    /* The slot `encoding' specifies how to map a character
+       code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
+       the font code-points (0:0x20..0x7F, 1:0xA0..0xFF, 0:0x2020..0x7F7F,
+       the font code-points (0:0x20..0x7F, 1:0xA0..0xFF,
+       0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF, or
+       2:0xA020..0xFF7F).  For the moment, we don't know which charset
+       uses this font.  So, we set informatoin in fontp->encoding[1]
+       which is never used by any charset.  If mapping can't be
+       decided, set FONT_ENCODING_NOT_DECIDED.  */
+    fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
+
+    /* The following three values are set to 0 under W32, which is
+       what they get set to if XGetFontProperty fails under X.  */
+    fontp->baseline_offset = 0;
+    fontp->relative_compose = 0;
+    fontp->default_ascent = FONT_BASE (font);
+
+    UNBLOCK_INPUT;
+    dpyinfo->n_fonts++;
+
+    return fontp;
+  }
 }
 
 void 
@@ -4534,15 +5055,35 @@ x_to_w32_charset (lpcs)
 {
   if (!lpcs) return (0);
 
-  if (stricmp (lpcs,"ansi") == 0)               return ANSI_CHARSET;
-  else if (stricmp (lpcs,"iso8859-1") == 0)     return ANSI_CHARSET;
-  else if (stricmp (lpcs,"iso8859") == 0)       return ANSI_CHARSET;
-  else if (stricmp (lpcs,"oem") == 0)          return OEM_CHARSET;
+  if (stricmp (lpcs,"ansi") == 0)                return ANSI_CHARSET;
+  else if (stricmp (lpcs,"iso8859-1") == 0)      return ANSI_CHARSET;
+  else if (stricmp (lpcs, "symbol") == 0)        return SYMBOL_CHARSET;
+  else if (stricmp (lpcs, "jis") == 0)           return SHIFTJIS_CHARSET;
+  else if (stricmp (lpcs, "ksc5601") == 0)       return HANGEUL_CHARSET;
+  else if (stricmp (lpcs, "gb2312") == 0)        return GB2312_CHARSET;
+  else if (stricmp (lpcs, "big5") == 0)          return CHINESEBIG5_CHARSET;
+  else if (stricmp (lpcs, "oem") == 0)          return OEM_CHARSET;
+
+#ifdef EASTEUROPE_CHARSET
+  else if (stricmp (lpcs, "iso8859-2") == 0)     return EASTEUROPE_CHARSET;
+  else if (stricmp (lpcs, "iso8859-3") == 0)     return TURKISH_CHARSET;
+  else if (stricmp (lpcs, "iso8859-4") == 0)     return BALTIC_CHARSET;
+  else if (stricmp (lpcs, "iso8859-5") == 0)     return RUSSIAN_CHARSET;
+  else if (stricmp (lpcs, "koi8") == 0)          return RUSSIAN_CHARSET;
+  else if (stricmp (lpcs, "iso8859-6") == 0)     return ARABIC_CHARSET;
+  else if (stricmp (lpcs, "iso8859-7") == 0)     return GREEK_CHARSET;
+  else if (stricmp (lpcs, "iso8859-8") == 0)     return HEBREW_CHARSET;
+  else if (stricmp (lpcs, "viscii") == 0)        return VIETNAMESE_CHARSET;
+  else if (stricmp (lpcs, "vscii") == 0)         return VIETNAMESE_CHARSET;
+  else if (stricmp (lpcs, "tis620") == 0)        return THAI_CHARSET;
+  else if (stricmp (lpcs, "mac") == 0)           return MAC_CHARSET;
+#endif
+
 #ifdef UNICODE_CHARSET
-  else if (stricmp (lpcs,"unicode") == 0)       return UNICODE_CHARSET;
-  else if (stricmp (lpcs,"iso10646") == 0)      return UNICODE_CHARSET;
+  else if (stricmp (lpcs,"iso10646") == 0)       return UNICODE_CHARSET;
+  else if (stricmp (lpcs, "unicode") == 0)       return UNICODE_CHARSET;
 #endif
-  else if (lpcs[0] == '#')                     return atoi (lpcs + 1);
+  else if (lpcs[0] == '#')                      return atoi (lpcs + 1);
   else
     return DEFAULT_CHARSET;
 }
@@ -4555,15 +5096,38 @@ w32_to_x_charset (fncharset)
 
   switch (fncharset)
     {
-    case ANSI_CHARSET:     return "ansi";
-    case OEM_CHARSET:      return "oem";
-    case SYMBOL_CHARSET:   return "symbol";
+      /* ansi is considered iso8859-1, as most modern ansi fonts are.  */
+    case ANSI_CHARSET:        return "iso8859-1";
+    case DEFAULT_CHARSET:     return "ascii-*";
+    case SYMBOL_CHARSET:      return "*-symbol";
+    case SHIFTJIS_CHARSET:    return "jisx0212-sjis";
+    case HANGEUL_CHARSET:     return "ksc5601-*";
+    case GB2312_CHARSET:      return "gb2312-*";
+    case CHINESEBIG5_CHARSET: return "big5-*";
+    case OEM_CHARSET:         return "*-oem";
+
+      /* More recent versions of Windows (95 and NT4.0) define more
+         character sets.  */
+#ifdef EASTEUROPE_CHARSET
+    case EASTEUROPE_CHARSET: return "iso8859-2";
+    case TURKISH_CHARSET:    return "iso8859-3";
+    case BALTIC_CHARSET:     return "iso8859-4";
+    case RUSSIAN_CHARSET:    return "iso8859-5";
+    case ARABIC_CHARSET:     return "iso8859-6";
+    case GREEK_CHARSET:      return "iso8859-7";
+    case HEBREW_CHARSET:     return "iso8859-8";
+    case VIETNAMESE_CHARSET: return "viscii1.1-*";
+    case THAI_CHARSET:       return "tis620-*";
+    case MAC_CHARSET:        return "*-mac";
+    case JOHAB_CHARSET:      break; /* What is this? Latin-9? */
+#endif
+
 #ifdef UNICODE_CHARSET
-    case UNICODE_CHARSET:  return "unicode";
+    case UNICODE_CHARSET:  return "iso10646-unicode";
 #endif
     }
   /* Encode numerical value of unknown charset.  */
-  sprintf (buf, "#%u", fncharset);
+  sprintf (buf, "*-#%u", fncharset);
   return buf;
 }
 
@@ -4573,15 +5137,26 @@ w32_to_x_font (lplogfont, lpxstr, len)
      char * lpxstr;
      int len;
 {
+  char fontname[50];
   char height_pixels[8];
   char height_dpi[8];
   char width_pixels[8];
+  char *fontname_dash;
 
   if (!lpxstr) abort ();
 
   if (!lplogfont)
     return FALSE;
 
+  strncpy (fontname, lplogfont->lfFaceName, 50);
+  fontname[49] = '\0'; /* Just in case */
+
+  /* Replace dashes with underscores so the dashes are not
+     misinterpreted */
+  fontname_dash = fontname;
+  while (fontname_dash = strchr (fontname_dash, '-'))
+      *fontname_dash = '_';
+
   if (lplogfont->lfHeight)
     {
       sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
@@ -4599,15 +5174,22 @@ w32_to_x_font (lplogfont, lpxstr, len)
     strcpy (width_pixels, "*");
 
   _snprintf (lpxstr, len - 1,
-            "-*-%s-%s-%c-*-*-%s-%s-*-*-%c-%s-*-%s-",
-            lplogfont->lfFaceName,
-            w32_to_x_weight (lplogfont->lfWeight),
-            lplogfont->lfItalic?'i':'r',
-            height_pixels,
-            height_dpi,
-            ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH) ? 'p' : 'c',
-            width_pixels,
-            w32_to_x_charset (lplogfont->lfCharSet)
+            "-*-%s-%s-%c-*-*-%s-%s-*-*-%c-%s-%s",
+                                                     /* foundry */
+            fontname,                               /* family */
+            w32_to_x_weight (lplogfont->lfWeight),  /* weight */
+            lplogfont->lfItalic?'i':'r',            /* slant */
+                                                     /* setwidth name */
+                                                     /* add style name */
+            height_pixels,                          /* pixel size */
+            height_dpi,                             /* point size */
+                                                     /* resx */
+                                                     /* resy */
+            ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
+             ? 'p' : 'c',                            /* spacing */
+            width_pixels,                           /* avg width */
+            w32_to_x_charset (lplogfont->lfCharSet) /* charset registry
+                                                        and encoding*/
             );
 
   lpxstr[len - 1] = 0;         /* just to be sure */
@@ -4623,6 +5205,7 @@ x_to_w32_font (lpxstr, lplogfont)
   
   memset (lplogfont, 0, sizeof (*lplogfont));
 
+  /* Set default value for each field.  */
 #if 1
   lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
   lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
@@ -4634,6 +5217,10 @@ x_to_w32_font (lpxstr, lplogfont)
   lplogfont->lfQuality = PROOF_QUALITY;
 #endif
 
+  lplogfont->lfCharSet = DEFAULT_CHARSET;
+  lplogfont->lfWeight = FW_DONTCARE;
+  lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
+
   if (!lpxstr)
     return FALSE;
 
@@ -4697,9 +5284,8 @@ x_to_w32_font (lpxstr, lplogfont)
 
       fields--;
 
-      /* Not all font specs include the registry field, so we allow for an
-        optional registry field before the encoding when parsing
-        remainder.  Also we strip the trailing '-' if present. */
+      /* Strip the trailing '-' if present. (it shouldn't be, as it
+         fails the test against xlfn-tight-regexp in fontset.el).  */
       {
        int len = strlen (remainder);
        if (len > 0 && remainder[len-1] == '-')
@@ -4807,22 +5393,34 @@ enum_font_cb2 (lplf, lptm, FontType, lpef)
   if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
     return (1);
   
+  /* Check that the character set matches if it was specified */
+  if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
+      lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
+    return (1);
+
+  /* We want all fonts cached, so don't compare sizes just yet */
   /*    if (!lpef->size_ref || lptm->tmMaxCharWidth == FONT_WIDTH (lpef->size_ref)) */
   {
     char buf[100];
+    Lisp_Object width = Qnil;
 
     if (!NILP (*(lpef->pattern)) && FontType != RASTER_FONTTYPE)
       {
+        /* Scalable fonts are as big as you want them to be.  */
        lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
        lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
       }
 
+    /* The MaxCharWidth is not valid at this stage for scalable fonts. */
+    if (FontType == RASTER_FONTTYPE)
+        width = make_number (lptm->tmMaxCharWidth);
+
     if (!w32_to_x_font (lplf, buf, 100)) return (0);
 
     if (NILP (*(lpef->pattern)) || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
       {
-       *lpef->tail = Fcons (build_string (buf), Qnil);
-       lpef->tail = &XCONS (*lpef->tail)->cdr;
+       *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
+       lpef->tail = &(XCONS (*lpef->tail)->cdr);
        lpef->numFonts++;
       }
   }
@@ -4844,7 +5442,250 @@ enum_font_cb1 (lplf, lptm, FontType, lpef)
 }
 
 
-DEFUN ("x-list-fonts", Fx_list_fonts, Sx_list_fonts, 1, 3, 0,
+/* Interface to fontset handler. (adapted from mw32font.c in Meadow
+   and xterm.c in Emacs 20.3) */
+
+/* Return a list of names of available fonts matching PATTERN on frame
+   F.  If SIZE is not 0, it is the size (maximum bound width) of fonts
+   to be listed.  Frame F NULL means we have not yet created any
+   frame, which means we can't get proper size info, as we don't have
+   a device context to use for GetTextMetrics.
+   MAXNAMES sets a limit on how many fonts to match.  */
+
+Lisp_Object
+w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
+{
+  Lisp_Object patterns, key, tem;
+  Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
+
+  /* If we don't have a frame, we can't use the Windows API to list
+     fonts, as it requires a device context for the Window.  This will
+     only happen during startup if the user specifies a font on the
+     command line.  Print a message on stderr and return nil.  */
+  if (!f)
+    {
+      char buffer[256];
+
+      sprintf (buffer, 
+              "Emacs cannot get a list of fonts before the initial frame "
+              "is created.\nThe font specified on the command line may not "
+              "be found.\n");
+      MessageBox (NULL, buffer, "Emacs Warning Dialog",
+                 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
+      return Qnil;
+    }
+
+
+  patterns = Fassoc (pattern, Valternate_fontname_alist);
+  if (NILP (patterns))
+    patterns = Fcons (pattern, Qnil);
+
+  for (; CONSP (patterns); patterns = XCONS (patterns)->cdr)
+    {
+      enumfont_t ef;
+
+      pattern = XCONS (patterns)->car;
+
+      /* See if we cached the result for this particular query.
+         The cache is an alist of the form:
+           ((PATTERN (FONTNAME . WIDTH) ...) ...)
+      */
+      if ( f &&
+           (tem = XCONS (FRAME_W32_DISPLAY_INFO (f)->name_list_element)->cdr,
+            !NILP (list = Fassoc (pattern, tem))))
+        {
+          list = Fcdr_safe (list);
+          /* We have a cached list. Don't have to get the list again.  */
+          goto label_cached;
+        }
+
+      BLOCK_INPUT;
+      /* At first, put PATTERN in the cache.  */
+      list = Qnil;
+      ef.pattern = &pattern;
+      ef.tail = ef.head = &list;
+      ef.numFonts = 0;
+      x_to_w32_font (STRINGP (pattern) ? XSTRING (pattern)->data :
+                     NULL, &ef.logfont);
+      {
+        ef.hdc = GetDC (FRAME_W32_WINDOW (f));
+
+        EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
+                          (LPARAM)&ef);
+
+        ReleaseDC (FRAME_W32_WINDOW (f), ef.hdc);
+      }
+
+      UNBLOCK_INPUT;
+
+      /* Make a list of the fonts we got back.
+         Store that in the font cache for the display. */
+      if (f != NULL)
+        XCONS (FRAME_W32_DISPLAY_INFO (f)->name_list_element)->cdr
+          = Fcons (Fcons (pattern, list),
+                   XCONS (FRAME_W32_DISPLAY_INFO (f)->name_list_element)->cdr);
+
+    label_cached:
+      if (NILP (list)) continue; /* Try the remaining alternatives.  */
+
+      newlist = second_best = Qnil;
+
+      /* Make a list of the fonts that have the right width.  */          
+      for (; CONSP (list); list = XCONS (list)->cdr)
+        {
+          int found_size;
+          tem = XCONS (list)->car;
+
+          if (!CONSP (tem))
+            continue;
+          if (NILP (XCONS (tem)->car))
+            continue;
+          if (!size)
+            {
+              newlist = Fcons (XCONS (tem)->car, newlist);
+              continue;
+            }
+          if (!INTEGERP (XCONS (tem)->cdr))
+            {
+              /* Since we don't yet know the size of the font, we must
+                 load it and try GetTextMetrics.  */
+              struct w32_display_info *dpyinfo
+                = FRAME_W32_DISPLAY_INFO (f);
+              W32FontStruct thisinfo;
+              LOGFONT lf;
+              HDC hdc;
+              HANDLE oldobj;
+
+              if (!x_to_w32_font (XSTRING (XCONS (tem)->car)->data, &lf))
+                continue;
+
+              BLOCK_INPUT;
+              thisinfo.hfont = CreateFontIndirect (&lf);
+              if (thisinfo.hfont == NULL)
+                continue;
+
+              hdc = GetDC (dpyinfo->root_window);
+              oldobj = SelectObject (hdc, thisinfo.hfont);
+              if (GetTextMetrics (hdc, &thisinfo.tm))
+                XCONS (tem)->cdr = make_number (FONT_WIDTH (&thisinfo));
+              else
+                XCONS (tem)->cdr = make_number (0);
+              SelectObject (hdc, oldobj);
+              ReleaseDC (dpyinfo->root_window, hdc);
+              DeleteObject(thisinfo.hfont);
+              UNBLOCK_INPUT;
+            }
+          found_size = XINT (XCONS (tem)->cdr);
+          if (found_size == size)
+            newlist = Fcons (XCONS (tem)->car, newlist);
+
+          /* keep track of the closest matching size in case
+             no exact match is found.  */
+          else if (found_size > 0)
+            {
+              if (NILP (second_best))
+                second_best = tem;
+              else if (found_size < size)
+                {
+                  if (XINT (XCONS (second_best)->cdr) > size
+                      || XINT (XCONS (second_best)->cdr) < found_size)
+                    second_best = tem;
+                }
+              else
+                {
+                  if (XINT (XCONS (second_best)->cdr) > size
+                      && XINT (XCONS (second_best)->cdr) >
+                      found_size)
+                    second_best = tem;
+                }
+            }
+        }
+
+      if (!NILP (newlist))
+        break;
+      else if (!NILP (second_best))
+        {
+          newlist = Fcons (XCONS (second_best)->car, Qnil);
+          break;
+        }
+    }
+
+  return newlist;
+}
+
+/* Return a pointer to struct font_info of font FONT_IDX of frame F.  */
+struct font_info *
+w32_get_font_info (f, font_idx)
+     FRAME_PTR f;
+     int font_idx;
+{
+  return (FRAME_W32_FONT_TABLE (f) + font_idx);
+}
+
+
+struct font_info*
+w32_query_font (struct frame *f, char *fontname)
+{
+  int i;
+  struct font_info *pfi;
+
+  pfi = FRAME_W32_FONT_TABLE (f);
+
+  for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
+    {
+      if (strcmp(pfi->name, fontname) == 0) return pfi;
+    }
+
+  return NULL;
+}
+
+/* Find a CCL program for a font specified by FONTP, and set the member
+ `encoder' of the structure.  */
+
+void
+w32_find_ccl_program (fontp)
+     struct font_info *fontp;
+{
+  extern Lisp_Object Vfont_ccl_encoder_alist, Vccl_program_table;
+  extern Lisp_Object Qccl_program_idx;
+  extern Lisp_Object resolve_symbol_ccl_program ();
+  Lisp_Object list, elt, ccl_prog, ccl_id;
+
+  for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCONS (list)->cdr)
+    {
+      elt = XCONS (list)->car;
+      if (CONSP (elt)
+         && STRINGP (XCONS (elt)->car)
+         && (fast_c_string_match_ignore_case (XCONS (elt)->car, fontp->name)
+             >= 0))
+       {
+         if (SYMBOLP (XCONS (elt)->cdr) &&
+             (!NILP (ccl_id = Fget (XCONS (elt)->cdr, Qccl_program_idx))))
+           {
+             ccl_prog = XVECTOR (Vccl_program_table)->contents[XUINT (ccl_id)];
+             if (!CONSP (ccl_prog)) continue;
+             ccl_prog = XCONS (ccl_prog)->cdr;
+           }
+         else
+           {
+             ccl_prog = XCONS (elt)->cdr;
+             if (!VECTORP (ccl_prog)) continue;
+           }
+           
+         fontp->font_encoder
+           = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
+         setup_ccl_program (fontp->font_encoder,
+                            resolve_symbol_ccl_program (ccl_prog));
+         break;
+       }
+    }
+}
+
+\f
+#if 1
+#include "x-list-font.c"
+#else
+DEFUN ("x-list-fonts", Fx_list_fonts, Sx_list_fonts, 1, 4, 0,
   "Return a list of the names of available fonts matching PATTERN.\n\
 If optional arguments FACE and FRAME are specified, return only fonts\n\
 the same size as FACE on FRAME.\n\
@@ -4859,9 +5700,12 @@ The return value is a list of strings, suitable as arguments to\n\
 set-face-font.\n\
 \n\
 Fonts Emacs can't use (i.e. proportional fonts) may or may not be excluded\n\
-even if they match PATTERN and FACE.")
-  (pattern, face, frame)
-    Lisp_Object pattern, face, frame;
+even if they match PATTERN and FACE.\n\
+\n\
+The optional fourth argument MAXIMUM sets a limit on how many\n\
+fonts to match.  The first MAXIMUM fonts are reported.")
+  (pattern, face, frame, maximum)
+    Lisp_Object pattern, face, frame, maximum;
 {
   int num_fonts;
   char **names;
@@ -4924,10 +5768,12 @@ even if they match PATTERN and FACE.")
       newlist = Qnil;
       for (tem = list; CONSP (tem); tem = XCONS (tem)->cdr)
        {
-         XFontStruct *thisinfo;
-
-          thisinfo = w32_load_font (FRAME_W32_DISPLAY_INFO (f), XSTRING (XCONS (tem)->car)->data);
+         struct font_info *fontinf;
+          XFontStruct *thisinfo = NULL;
 
+          fontinf = w32_load_font (f, XSTRING (XCONS (tem)->car)->data, 0);
+          if (fontinf)
+            thisinfo = (XFontStruct *)fontinf->font;
           if (thisinfo && same_size_fonts (thisinfo, size_ref))
            newlist = Fcons (XCONS (tem)->car, newlist);
 
@@ -4979,10 +5825,13 @@ even if they match PATTERN and FACE.")
            keeper = 1;
          else
            {
-             XFontStruct *thisinfo;
+             struct font_info *fontinf;
+              XFontStruct *thisinfo = NULL;
 
              BLOCK_INPUT;
-             thisinfo = w32_load_font (FRAME_W32_DISPLAY_INFO (f), XSTRING (Fcar (cur))->data);
+             fontinf = w32_load_font (f, XSTRING (Fcar (cur))->data, 0);
+              if (fontinf)
+                thisinfo = (XFontStruct *)fontinf->font;
 
              keeper = thisinfo && same_size_fonts (thisinfo, size_ref);
 
@@ -5000,6 +5849,7 @@ even if they match PATTERN and FACE.")
 
   return list;
 }
+#endif
 \f
 DEFUN ("x-color-defined-p", Fx_color_defined_p, Sx_color_defined_p, 1, 2, 0,
        "Return non-nil if color COLOR is supported on frame FRAME.\n\
@@ -5569,6 +6419,187 @@ If optional parameter FRAME is not specified, use selected frame.")
   return Qnil;
 }
 
+/* Lookup virtual keycode from string representing the name of a
+   non-ascii keystroke into the corresponding virtual key, using
+   lispy_function_keys.  */
+static int
+lookup_vk_code (char *key)
+{
+  int i;
+
+  for (i = 0; i < 256; i++)
+    if (lispy_function_keys[i] != 0
+       && strcmp (lispy_function_keys[i], key) == 0)
+      return i;
+
+  return -1;
+}
+
+/* Convert a one-element vector style key sequence to a hot key
+   definition.  */
+static int
+w32_parse_hot_key (key)
+     Lisp_Object key;
+{
+  /* Copied from Fdefine_key and store_in_keymap.  */
+  register Lisp_Object c;
+  int vk_code;
+  int lisp_modifiers;
+  int w32_modifiers;
+  struct gcpro gcpro1;
+
+  CHECK_VECTOR (key, 0);
+
+  if (XFASTINT (Flength (key)) != 1)
+    return Qnil;
+
+  GCPRO1 (key);
+
+  c = Faref (key, make_number (0));
+
+  if (CONSP (c) && lucid_event_type_list_p (c))
+    c = Fevent_convert_list (c);
+
+  UNGCPRO;
+
+  if (! INTEGERP (c) && ! SYMBOLP (c))
+    error ("Key definition is invalid");
+
+  /* Work out the base key and the modifiers.  */
+  if (SYMBOLP (c))
+    {
+      c = parse_modifiers (c);
+      lisp_modifiers = Fcar (Fcdr (c));
+      c = Fcar (c);
+      if (!SYMBOLP (c))
+       abort ();
+      vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
+    }
+  else if (INTEGERP (c))
+    {
+      lisp_modifiers = XINT (c) & ~CHARACTERBITS;
+      /* Many ascii characters are their own virtual key code.  */
+      vk_code = XINT (c) & CHARACTERBITS;
+    }
+
+  if (vk_code < 0 || vk_code > 255)
+    return Qnil;
+
+  if ((lisp_modifiers & meta_modifier) != 0
+      && !NILP (Vw32_alt_is_meta))
+    lisp_modifiers |= alt_modifier;
+
+  /* Convert lisp modifiers to Windows hot-key form.  */
+  w32_modifiers  = (lisp_modifiers & hyper_modifier)    ? MOD_WIN : 0;
+  w32_modifiers |= (lisp_modifiers & alt_modifier)      ? MOD_ALT : 0;
+  w32_modifiers |= (lisp_modifiers & ctrl_modifier)     ? MOD_CONTROL : 0;
+  w32_modifiers |= (lisp_modifiers & shift_modifier)    ? MOD_SHIFT : 0;
+
+  return HOTKEY (vk_code, w32_modifiers);
+}
+
+DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
+   "Register KEY as a hot-key combination.\n\
+Certain key combinations like Alt-Tab are reserved for system use on\n\
+Windows, and therefore are normally intercepted by the system.  However,\n\
+most of these key combinations can be received by registering them as\n\
+hot-keys, overriding their special meaning.\n\
+\n\
+KEY must be a one element key definition in vector form that would be\n\
+acceptable to `define-key' (e.g. [A-tab] for Alt-Tab).  The meta\n\
+modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
+is always interpreted as the Windows modifier keys.\n\
+\n\
+The return value is the hotkey-id if registered, otherwise nil.")
+  (key)
+     Lisp_Object key;
+{
+  key = w32_parse_hot_key (key);
+
+  if (NILP (Fmemq (key, w32_grabbed_keys)))
+    {
+      /* Reuse an empty slot if possible.  */
+      Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
+
+      /* Safe to add new key to list, even if we have focus.  */
+      if (NILP (item))
+       w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
+      else
+       XCAR (item) = key;
+
+      /* Notify input thread about new hot-key definition, so that it
+        takes effect without needing to switch focus.  */
+      PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
+                        (WPARAM) key, 0);
+    }
+
+  return key;
+}
+
+DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
+   "Unregister HOTKEY as a hot-key combination.")
+  (key)
+     Lisp_Object key;
+{
+  Lisp_Object item;
+
+  if (!INTEGERP (key))
+    key = w32_parse_hot_key (key);
+
+  item = Fmemq (key, w32_grabbed_keys);
+
+  if (!NILP (item))
+    {
+      /* Notify input thread about hot-key definition being removed, so
+        that it takes effect without needing focus switch.  */
+      if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
+                            (WPARAM) XINT (XCAR (item)), (LPARAM) item))
+       {
+         MSG msg;
+         GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
+       }
+      return Qt;
+    }
+  return Qnil;
+}
+
+DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
+   "Return list of registered hot-key IDs.")
+  ()
+{
+  return Fcopy_sequence (w32_grabbed_keys);
+}
+
+DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
+   "Convert hot-key ID to a lisp key combination.")
+  (hotkeyid)
+     Lisp_Object hotkeyid;
+{
+  int vk_code, w32_modifiers;
+  Lisp_Object key;
+
+  CHECK_NUMBER (hotkeyid, 0);
+
+  vk_code = HOTKEY_VK_CODE (hotkeyid);
+  w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
+
+  if (lispy_function_keys[vk_code])
+    key = intern (lispy_function_keys[vk_code]);
+  else
+    key = make_number (vk_code);
+
+  key = Fcons (key, Qnil);
+  if (w32_modifiers & MOD_SHIFT)
+    key = Fcons (intern ("shift"), key);
+  if (w32_modifiers & MOD_CONTROL)
+    key = Fcons (intern ("control"), key);
+  if (w32_modifiers & MOD_ALT)
+    key = Fcons (intern (NILP (Vw32_alt_is_meta) ? "alt" : "meta"), key);
+  if (w32_modifiers & MOD_WIN)
+    key = Fcons (intern ("hyper"), key);
+
+  return key;
+}
 \f
 syms_of_w32fns ()
 {
@@ -5646,13 +6677,19 @@ syms_of_w32fns ()
   staticpro (&Qdisplay);
   /* This is the end of symbol initialization.  */
 
+  Qface_set_after_frame_default = intern ("face-set-after-frame-default");
+  staticpro (&Qface_set_after_frame_default);
+
   Fput (Qundefined_color, Qerror_conditions,
        Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
   Fput (Qundefined_color, Qerror_message,
        build_string ("Undefined color"));
 
+  staticpro (&w32_grabbed_keys);
+  w32_grabbed_keys = Qnil;
+
   DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
-              "A array of color name mappings for windows.");
+              "An array of color name mappings for windows.");
   Vw32_color_map = Qnil;
 
   DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
@@ -5666,11 +6703,61 @@ open the System menu.  When nil, Emacs silently swallows alt key events.");
 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
   Vw32_alt_is_meta = Qt;
 
-  DEFVAR_LISP ("w32-pass-optional-keys-to-system", 
-              &Vw32_pass_optional_keys_to_system,
-              "Non-nil if the 'optional' keys (left window, right window,\n\
-and application keys) are passed on to Windows.");
-  Vw32_pass_optional_keys_to_system = Qnil;
+  DEFVAR_LISP ("w32-pass-lwindow-to-system", 
+              &Vw32_pass_lwindow_to_system,
+              "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
+When non-nil, the Start menu is opened by tapping the key.");
+  Vw32_pass_lwindow_to_system = Qt;
+
+  DEFVAR_LISP ("w32-pass-rwindow-to-system", 
+              &Vw32_pass_rwindow_to_system,
+              "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
+When non-nil, the Start menu is opened by tapping the key.");
+  Vw32_pass_rwindow_to_system = Qt;
+
+  DEFVAR_LISP ("w32-enable-num-lock", 
+              &Vw32_enable_num_lock,
+              "Non-nil if Num Lock should act normally.\n\
+Set to nil to see Num Lock as the key `kp-numlock'.");
+  Vw32_enable_num_lock = Qt;
+
+  DEFVAR_LISP ("w32-enable-caps-lock", 
+              &Vw32_enable_caps_lock,
+              "Non-nil if Caps Lock should act normally.\n\
+Set to nil to see Caps Lock as the key `capslock'.");
+  Vw32_enable_caps_lock = Qt;
+
+  DEFVAR_LISP ("w32-scroll-lock-modifier",
+              &Vw32_scroll_lock_modifier,
+              "Modifier to use for the Scroll Lock on state.\n\
+The value can be hyper, super, meta, alt, control or shift for the\n\
+respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
+Any other value will cause the key to be ignored.");
+  Vw32_scroll_lock_modifier = Qt;
+
+  DEFVAR_LISP ("w32-lwindow-modifier",
+              &Vw32_lwindow_modifier,
+              "Modifier to use for the left \"Windows\" key.\n\
+The value can be hyper, super, meta, alt, control or shift for the\n\
+respective modifier, or nil to appear as the key `lwindow'.\n\
+Any other value will cause the key to be ignored.");
+  Vw32_lwindow_modifier = Qnil;
+
+  DEFVAR_LISP ("w32-rwindow-modifier",
+              &Vw32_rwindow_modifier,
+              "Modifier to use for the right \"Windows\" key.\n\
+The value can be hyper, super, meta, alt, control or shift for the\n\
+respective modifier, or nil to appear as the key `rwindow'.\n\
+Any other value will cause the key to be ignored.");
+  Vw32_rwindow_modifier = Qnil;
+
+  DEFVAR_LISP ("w32-apps-modifier",
+              &Vw32_apps_modifier,
+              "Modifier to use for the \"Apps\" key.\n\
+The value can be hyper, super, meta, alt, control or shift for the\n\
+respective modifier, or nil to appear as the key `apps'.\n\
+Any other value will cause the key to be ignored.");
+  Vw32_apps_modifier = Qnil;
 
   DEFVAR_LISP ("w32-enable-italics", &Vw32_enable_italics,
               "Non-nil enables selection of artificially italicized fonts.");
@@ -5741,6 +6828,25 @@ unless you set it to something else.");
      and maybe the user would like to set it to t.  */
   Vx_no_window_manager = Qnil;
 
+  DEFVAR_LISP ("x-pixel-size-width-font-regexp",
+              &Vx_pixel_size_width_font_regexp,
+     "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
+\n\
+Since Emacs gets width of a font matching with this regexp from\n\
+PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
+such a font.  This is especially effective for such large fonts as\n\
+Chinese, Japanese, and Korean.");
+  Vx_pixel_size_width_font_regexp = Qnil;
+
+  DEFVAR_BOOL ("unibyte-display-via-language-environment",
+              &unibyte_display_via_language_environment,
+   "*Non-nil means display unibyte text according to language environment.\n\
+Specifically this means that unibyte non-ASCII characters\n\
+are displayed by converting them to the equivalent multibyte characters\n\
+according to the current language environment.  As a result, they are\n\
+displayed according to the current fontset.");
+  unibyte_display_via_language_environment = 0;
+
   defsubr (&Sx_get_resource);
   defsubr (&Sx_list_fonts);
   defsubr (&Sx_display_color_p);
@@ -5775,11 +6881,30 @@ unless you set it to something else.");
   defsubr (&Sw32_default_color_map);
   defsubr (&Sw32_load_color_file);
   defsubr (&Sw32_send_sys_command);
+  defsubr (&Sw32_register_hot_key);
+  defsubr (&Sw32_unregister_hot_key);
+  defsubr (&Sw32_registered_hot_keys);
+  defsubr (&Sw32_reconstruct_hot_key);
+
+  /* Setting callback functions for fontset handler.  */
+  get_font_info_func = w32_get_font_info;
+  list_fonts_func = w32_list_fonts;
+  load_font_func = w32_load_font;
+  find_ccl_program_func = w32_find_ccl_program;
+  query_font_func = w32_query_font;
+  set_frame_fontset_func = x_set_font;
+  check_window_system_func = check_w32;
 }
 
 #undef abort
 
 void 
+/* For convenience when debugging.  */
+int
+w32_last_error()
+{
+  return GetLastError ();
+}
 w32_abort()
 {
   int button;