ns-win.el 63.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
;;; ns-win.el --- lisp side of interface with NeXT/Open/GNUstep/MacOS X window system

;; Copyright (C) 1993, 1994, 2005, 2006, 2008 Free Software Foundation, Inc.

;; Author: Carl Edman, Christian Limpach, Scott Bender, Christophe de Dinechin, Adrian Robert
;; Keywords: terminals

;; This file is part of GNU Emacs.

;; GNU Emacs 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 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs 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 GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

;;; Commentary:

;; ns-win.el:  this file is loaded from ../lisp/startup.el when it recognizes
;; that NS windows are to be used.  Command line switches are parsed and those
;; pertaining to NS are processed and removed from the command line.  The
;; NS display is opened and hooks are set for popping up the initial window.

;; startup.el will then examine startup files, and eventually call the hooks
;; which create the first window (s).

;; A number of other NS convenience functions are defined in this file,
;; which works in close coordination with src/nsfns.m.

;;; Code:


(if (not (featurep 'ns-windowing))
    (error "%s: Loading ns-win.el but not compiled for *Step/OS X"
	   (invocation-name)))

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

45 46 47 48 49 50 51 52
;; Documentation-purposes only: actually loaded in loadup.el
(require 'frame)
(require 'mouse)
(require 'faces)
(require 'easymenu)
(require 'menu-bar)
(require 'fontset)

53 54
;; Not needed?
;;(require 'ispell)
55

56 57 58 59 60 61 62 63 64
;; nsterm.m
(defvar ns-version-string)
(defvar ns-expand-space)
(defvar ns-cursor-blink-rate)
(defvar ns-alternate-modifier)

(declare-function ns-server-vendor "nsfns.m" (&optional display))
(declare-function ns-server-version "nsfns.m" (&optional display))

65
(defun ns-submit-bug-report ()
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  "Submit via mail a bug report on Emacs 23.0.0 for GNUstep / OS X."
  (interactive)
  (let ((frame-parameters (frame-parameters))
        (server-vendor (ns-server-vendor))
        (server-version (ns-server-version)))
    (reporter-submit-bug-report
     "Adrian Robert <Adrian.B.Robert@gmail.com>"
     ;;"Christophe de Dinechin <descubes@earthlink.net>"
     ;;"Scott Bender <emacs@harmony-ds.com>"
     ;;"Christian Limpach <chris@nice.ch>"
     ;;"Carl Edman <cedman@princeton.edu>"
     (concat "Emacs for GNUstep / OS X " ns-version-string)
     '(ns-expand-space ns-cursor-blink-rate ns-alternate-modifier
       data-directory frame-parameters window-system window-system-version
       server-vendor server-version system-configuration-options))))
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


;;;; Command line argument handling.

(defvar ns-invocation-args nil)
(defvar ns-command-line-resources nil)

;; Handler for switches of the form "-switch value" or "-switch".
(defun ns-handle-switch (switch)
  (let ((aelt (assoc switch command-line-ns-option-alist)))
    (if aelt
	(let ((param (nth 3 aelt))
	      (value (nth 4 aelt)))
	  (if value
	      (setq default-frame-alist
		    (cons (cons param value)
			  default-frame-alist))
	    (setq default-frame-alist
		  (cons (cons param
			      (car ns-invocation-args))
			default-frame-alist)
		  ns-invocation-args (cdr ns-invocation-args)))))))

;; Handler for switches of the form "-switch n"
(defun ns-handle-numeric-switch (switch)
  (let ((aelt (assoc switch command-line-ns-option-alist)))
    (if aelt
	(let ((param (nth 3 aelt)))
	  (setq default-frame-alist
		(cons (cons param
			    (string-to-number (car ns-invocation-args)))
		      default-frame-alist)
		ns-invocation-args
		(cdr ns-invocation-args))))))

;; Make -iconic apply only to the initial frame!
(defun ns-handle-iconic (switch)
  (setq initial-frame-alist
        (cons '(visibility . icon) initial-frame-alist)))

;; Handle the -name option, set the name of
;; the initial frame.
(defun ns-handle-name-switch (switch)
  (or (consp ns-invocation-args)
      (error "%s: missing argument to `%s' option" (invocation-name) switch))
  (setq initial-frame-alist (cons (cons 'name (car ns-invocation-args))
                                  initial-frame-alist)
        ns-invocation-args (cdr ns-invocation-args)))

130 131 132
;; nsterm.m.
(defvar ns-input-file)

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
(defun ns-handle-nxopen (switch)
  (setq unread-command-events (append unread-command-events '(ns-open-file))
        ns-input-file (append ns-input-file (list (car ns-invocation-args)))
        ns-invocation-args (cdr ns-invocation-args)))

(defun ns-handle-nxopentemp (switch)
  (setq unread-command-events (append unread-command-events '(ns-open-temp-file))
        ns-input-file (append ns-input-file (list (car ns-invocation-args)))
        ns-invocation-args (cdr ns-invocation-args)))

(defun ns-ignore-0-arg (switch)
  )
(defun ns-ignore-1-arg (switch)
  (setq ns-invocation-args (cdr ns-invocation-args)))
(defun ns-ignore-2-arg (switch)
  (setq ns-invocation-args (cddr ns-invocation-args)))

(defun ns-handle-args (args)
  "Here the NS-related command line options in ARGS are processed,
before the user's startup file is loaded.  They are copied to
`ns-invocation-args', from which the NS related things are extracted, first
the switch (e.g., \"-fg\") in the following code, and possible values
\(e.g., \"black\") in the option handler code (e.g., ns-handle-switch).
This function returns ARGS minus the arguments that have been processed."
  ;; We use ARGS to accumulate the args that we don't handle here, to return.
  (setq ns-invocation-args args
        args nil)
  (while ns-invocation-args
    (let* ((this-switch (car ns-invocation-args))
	   (orig-this-switch this-switch)
	   completion argval aelt handler)
      (setq ns-invocation-args (cdr ns-invocation-args))
      ;; Check for long options with attached arguments
      ;; and separate out the attached option argument into argval.
      (if (string-match "^--[^=]*=" this-switch)
	  (setq argval (substring this-switch (match-end 0))
		this-switch (substring this-switch 0 (1- (match-end 0)))))
      ;; Complete names of long options.
      (if (string-match "^--" this-switch)
	  (progn
	    (setq completion (try-completion this-switch
                                             command-line-ns-option-alist))
	    (if (eq completion t)
		;; Exact match for long option.
		nil
	      (if (stringp completion)
		  (let ((elt (assoc completion command-line-ns-option-alist)))
		    ;; Check for abbreviated long option.
		    (or elt
			(error "Option `%s' is ambiguous" this-switch))
		    (setq this-switch completion))))))
      (setq aelt (assoc this-switch command-line-ns-option-alist))
      (if aelt (setq handler (nth 2 aelt)))
      (if handler
	  (if argval
	      (let ((ns-invocation-args
		     (cons argval ns-invocation-args)))
		(funcall handler this-switch))
	    (funcall handler this-switch))
	(setq args (cons orig-this-switch args)))))
  (nreverse args))

(defun x-parse-geometry (geom)
  "Parse an NS-style geometry string STRING.
Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
The properties returned may include `top', `left', `height', and `width'."
  (if (string-match "\\([0-9]+\\)\\( \\([0-9]+\\)\\( \\([0-9]+\\)\\( \\([0-9]+\\) ?\\)?\\)?\\)?"
                    geom)
      (apply 'append
202 203 204 205 206 207 208 209
             (list
              (list (cons 'top (string-to-number (match-string 1 geom))))
              (if (match-string 3 geom)
                  (list (cons 'left (string-to-number (match-string 3 geom)))))
              (if (match-string 5 geom)
                  (list (cons 'height (string-to-number (match-string 5 geom)))))
              (if (match-string 7 geom)
                  (list (cons 'width (string-to-number (match-string 7 geom)))))))
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
    '()))



;;;; Keyboard mapping.

;; These tell read-char how to convert
;; these special chars to ASCII.
(put 'backspace 'ascii-character 127)
(put 'delete 'ascii-character 127)
(put 'tab 'ascii-character ?\t)
(put 'S-tab 'ascii-character (logior 16 ?\t))
(put 'linefeed 'ascii-character ?\n)
(put 'clear 'ascii-character 12)
(put 'return 'ascii-character 13)
(put 'escape 'ascii-character ?\e)

;; Map certain keypad keys into ASCII characters
;; that people usually expect.
(define-key function-key-map [backspace] [127])
(define-key function-key-map [delete] [127])
(define-key function-key-map [tab] [?\t])
(define-key function-key-map [S-tab] [25])
(define-key function-key-map [linefeed] [?\n])
(define-key function-key-map [clear] [11])
(define-key function-key-map [return] [13])
(define-key function-key-map [escape] [?\e])
(define-key function-key-map [M-backspace] [?\M-\d])
(define-key function-key-map [M-delete] [?\M-\d])
(define-key function-key-map [M-tab] [?\M-\t])
(define-key function-key-map [M-linefeed] [?\M-\n])
(define-key function-key-map [M-clear] [?\M-\013])
(define-key function-key-map [M-return] [?\M-\015])
(define-key function-key-map [M-escape] [?\M-\e])


;; Here are some NeXTSTEP like bindings for command key sequences.
(define-key global-map [?\s-,] 'ns-popup-prefs-panel)
(define-key global-map [?\s-'] 'next-multiframe-window)
(define-key global-map [?\s-`] 'other-frame)
(define-key global-map [?\s--] 'center-line)
(define-key global-map [?\s-:] 'ispell)
(define-key global-map [?\s-\;] 'ispell-next)
(define-key global-map [?\s-?] 'info)
(define-key global-map [?\s-^] 'kill-some-buffers)
(define-key global-map [?\s-&] 'kill-this-buffer)
(define-key global-map [?\s-C] 'ns-popup-color-panel)
(define-key global-map [?\s-D] 'dired)
(define-key global-map [?\s-E] 'edit-abbrevs)
(define-key global-map [?\s-L] 'shell-command)
(define-key global-map [?\s-M] 'manual-entry)
(define-key global-map [?\s-S] 'ns-write-file-using-panel)
(define-key global-map [?\s-a] 'mark-whole-buffer)
(define-key global-map [?\s-c] 'ns-copy-including-secondary)
(define-key global-map [?\s-d] 'isearch-repeat-backward)
(define-key global-map [?\s-e] 'isearch-yank-kill)
(define-key global-map [?\s-f] 'isearch-forward)
(define-key global-map [?\s-g] 'isearch-repeat-forward)
(define-key global-map [?\s-h] 'ns-do-hide-emacs)
(define-key global-map [?\s-H] 'ns-do-hide-others)
(define-key global-map [?\s-j] 'exchange-point-and-mark)
(define-key global-map [?\s-k] 'kill-this-buffer)
(define-key global-map [?\s-l] 'goto-line)
(define-key global-map [?\s-m] 'iconify-frame)
(define-key global-map [?\s-n] 'make-frame)
(define-key global-map [?\s-o] 'ns-open-file-using-panel)
(define-key global-map [?\s-p] 'ns-print-buffer)
(define-key global-map [?\s-q] 'save-buffers-kill-emacs)
(define-key global-map [?\s-s] 'save-buffer)
(define-key global-map [?\s-t] 'ns-popup-font-panel)
(define-key global-map [?\s-u] 'revert-buffer)
(define-key global-map [?\s-v] 'yank)
(define-key global-map [?\s-w] 'delete-frame)
(define-key global-map [?\s-x] 'kill-region)
(define-key global-map [?\s-y] 'ns-paste-secondary)
(define-key global-map [?\s-z] 'undo)
(define-key global-map [?\s-|] 'shell-command-on-region)
(define-key global-map [s-kp-bar] 'shell-command-on-region)
288
;; (as in Terminal.app)
289 290 291 292 293 294 295 296 297 298 299 300 301 302
(define-key global-map [s-right] 'ns-next-frame)
(define-key global-map [s-left] 'ns-prev-frame)

(define-key global-map [home] 'beginning-of-buffer)
(define-key global-map [end] 'end-of-buffer)
(define-key global-map [kp-home] 'beginning-of-buffer)
(define-key global-map [kp-end] 'end-of-buffer)
(define-key global-map [kp-prior] 'scroll-down)
(define-key global-map [kp-next] 'scroll-up)


;; Special NeXTSTEP generated events are converted to function keys.  Here
;; are the bindings for them.
(define-key global-map [ns-power-off]
303
  (lambda () (interactive) (save-buffers-kill-emacs t)))
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
(define-key global-map [ns-open-file] 'ns-find-file)
(define-key global-map [ns-open-temp-file] [ns-open-file])
(define-key global-map [ns-drag-file] 'ns-insert-file)
(define-key global-map [ns-drag-color] 'ns-set-foreground-at-mouse)
(define-key global-map [S-ns-drag-color] 'ns-set-background-at-mouse)
(define-key global-map [ns-drag-text] 'ns-insert-text)
(define-key global-map [ns-change-font] 'ns-respond-to-change-font)
(define-key global-map [ns-open-file-line] 'ns-open-file-select-line)
(define-key global-map [ns-insert-working-text] 'ns-insert-working-text)
(define-key global-map [ns-delete-working-text] 'ns-delete-working-text)
(define-key global-map [ns-spi-service-call] 'ns-spi-service-call)



;;;; Lisp niceties, most used only under ns-extended-platform-support-mode,
;;;; defined below

(autoload 'ns-grabenv "ns-grabenv" "Get environment from your shell." t nil)
(load "ns-carbon-compat")

;; alt-up/down scrolling a la Stuart.app
;; only activated if ns-extended-platform-support is on
(defun up-one () (interactive) (scroll-up 1))
(defun down-one () (interactive) (scroll-down 1))
(defun left-one () (interactive) (scroll-left 1))
(defun right-one () (interactive) (scroll-right 1))

331 332
(defvar menu-bar-ns-file-menu)		; below

333 334 335 336 337
;; Toggle some additional NS-like features that may interfere with users'
;; expectations coming from emacs on other platforms.
(define-minor-mode ns-extended-platform-support-mode
  "Toggle NS extended platform support features.
   When this mode is active (no modeline indicator):
338
   - File menu is altered slightly in keeping with conventions.
339
   - Meta-up, meta-down are bound to scroll window up and down one line.
340 341
   - Screen position is preserved in scrolling.
   - Transient mark mode is activated"
342 343 344 345 346
  :init-value nil
  :global t
  :group 'ns
  (if ns-extended-platform-support-mode
      (progn
347 348 349 350 351 352 353 354 355 356 357 358 359
        (global-set-key [M-up] 'down-one)
        (global-set-key [M-down] 'up-one)
        ;; These conflict w/word-left, word-right.
        ;;(global-set-key [M-left] 'left-one)
        ;;(global-set-key [M-right] 'right-one)

        (setq scroll-preserve-screen-position t)
        (transient-mark-mode 1)

        ;; Change file menu to simplify and add a couple of NS-specific items
        (easy-menu-remove-item global-map '("menu-bar") 'file)
        (easy-menu-add-item global-map '(menu-bar)
                            (cons "File" menu-bar-ns-file-menu) 'edit))
360
    (progn
361 362 363 364 365 366 367 368
      ;; Undo everything above.
      (global-unset-key [M-up])
      (global-unset-key [M-down])
      (setq scroll-preserve-screen-position nil)
      (transient-mark-mode 0)
      (easy-menu-remove-item global-map '("menu-bar") 'file)
      (easy-menu-add-item global-map '(menu-bar)
                          (cons "File" menu-bar-file-menu) 'edit))))
369 370 371 372 373 374 375 376


(defun x-setup-function-keys (frame)
  "Set up function Keys for NS for given FRAME."
  (unless (terminal-parameter frame 'x-setup-function-keys)
    (with-selected-frame frame
      (setq interprogram-cut-function 'ns-select-text
	    interprogram-paste-function 'ns-pasteboard-value)
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
      ;; (let ((map (copy-keymap x-alternatives-map)))
      ;;   (set-keymap-parent map (keymap-parent local-function-key-map))
      ;;   (set-keymap-parent local-function-key-map map))
      (setq system-key-alist
            (list
             (cons (logior (lsh 0 16)   1) 'ns-power-off)
             (cons (logior (lsh 0 16)   2) 'ns-open-file)
             (cons (logior (lsh 0 16)   3) 'ns-open-temp-file)
             (cons (logior (lsh 0 16)   4) 'ns-drag-file)
             (cons (logior (lsh 0 16)   5) 'ns-drag-color)
             (cons (logior (lsh 0 16)   6) 'ns-drag-text)
             (cons (logior (lsh 0 16)   7) 'ns-change-font)
             (cons (logior (lsh 0 16)   8) 'ns-open-file-line)
             (cons (logior (lsh 0 16)   9) 'ns-insert-working-text)
             (cons (logior (lsh 0 16)  10) 'ns-delete-working-text)
             (cons (logior (lsh 0 16)  11) 'ns-spi-service-call)
             (cons (logior (lsh 1 16)  32) 'f1)
             (cons (logior (lsh 1 16)  33) 'f2)
             (cons (logior (lsh 1 16)  34) 'f3)
             (cons (logior (lsh 1 16)  35) 'f4)
             (cons (logior (lsh 1 16)  36) 'f5)
             (cons (logior (lsh 1 16)  37) 'f6)
             (cons (logior (lsh 1 16)  38) 'f7)
             (cons (logior (lsh 1 16)  39) 'f8)
             (cons (logior (lsh 1 16)  40) 'f9)
             (cons (logior (lsh 1 16)  41) 'f10)
             (cons (logior (lsh 1 16)  42) 'f11)
             (cons (logior (lsh 1 16)  43) 'f12)
             (cons (logior (lsh 1 16)  44) 'kp-insert)
             (cons (logior (lsh 1 16)  45) 'kp-delete)
             (cons (logior (lsh 1 16)  46) 'kp-home)
             (cons (logior (lsh 1 16)  47) 'kp-end)
             (cons (logior (lsh 1 16)  48) 'kp-prior)
             (cons (logior (lsh 1 16)  49) 'kp-next)
             (cons (logior (lsh 1 16)  50) 'print-screen)
             (cons (logior (lsh 1 16)  51) 'scroll-lock)
             (cons (logior (lsh 1 16)  52) 'pause)
             (cons (logior (lsh 1 16)  53) 'system)
             (cons (logior (lsh 1 16)  54) 'break)
             (cons (logior (lsh 1 16)  56) 'please-tell-carl-what-this-key-is-called-56)
             (cons (logior (lsh 1 16)  61) 'please-tell-carl-what-this-key-is-called-61)
             (cons (logior (lsh 1 16)  62) 'please-tell-carl-what-this-key-is-called-62)
             (cons (logior (lsh 1 16)  63) 'please-tell-carl-what-this-key-is-called-63)
             (cons (logior (lsh 1 16)  64) 'please-tell-carl-what-this-key-is-called-64)
             (cons (logior (lsh 1 16)  69) 'please-tell-carl-what-this-key-is-called-69)
             (cons (logior (lsh 1 16)  70) 'please-tell-carl-what-this-key-is-called-70)
             (cons (logior (lsh 1 16)  71) 'please-tell-carl-what-this-key-is-called-71)
             (cons (logior (lsh 1 16)  72) 'please-tell-carl-what-this-key-is-called-72)
             (cons (logior (lsh 1 16)  73) 'please-tell-carl-what-this-key-is-called-73)
             (cons (logior (lsh 2 16)   3) 'kp-enter)
             (cons (logior (lsh 2 16)   9) 'kp-tab)
             (cons (logior (lsh 2 16)  28) 'kp-quit)
             (cons (logior (lsh 2 16)  35) 'kp-hash)
             (cons (logior (lsh 2 16)  42) 'kp-multiply)
             (cons (logior (lsh 2 16)  43) 'kp-add)
             (cons (logior (lsh 2 16)  44) 'kp-separator)
             (cons (logior (lsh 2 16)  45) 'kp-subtract)
             (cons (logior (lsh 2 16)  46) 'kp-decimal)
             (cons (logior (lsh 2 16)  47) 'kp-divide)
             (cons (logior (lsh 2 16)  48) 'kp-0)
             (cons (logior (lsh 2 16)  49) 'kp-1)
             (cons (logior (lsh 2 16)  50) 'kp-2)
             (cons (logior (lsh 2 16)  51) 'kp-3)
             (cons (logior (lsh 2 16)  52) 'kp-4)
             (cons (logior (lsh 2 16)  53) 'kp-5)
             (cons (logior (lsh 2 16)  54) 'kp-6)
             (cons (logior (lsh 2 16)  55) 'kp-7)
             (cons (logior (lsh 2 16)  56) 'kp-8)
             (cons (logior (lsh 2 16)  57) 'kp-9)
             (cons (logior (lsh 2 16)  60) 'kp-less)
             (cons (logior (lsh 2 16)  61) 'kp-equal)
             (cons (logior (lsh 2 16)  62) 'kp-more)
             (cons (logior (lsh 2 16)  64) 'kp-at)
             (cons (logior (lsh 2 16)  92) 'kp-backslash)
             (cons (logior (lsh 2 16)  96) 'kp-backtick)
             (cons (logior (lsh 2 16) 124) 'kp-bar)
             (cons (logior (lsh 2 16) 126) 'kp-tilde)
             (cons (logior (lsh 2 16) 157) 'kp-mu)
             (cons (logior (lsh 2 16) 165) 'kp-yen)
             (cons (logior (lsh 2 16) 167) 'kp-paragraph)
             (cons (logior (lsh 2 16) 172) 'left)
             (cons (logior (lsh 2 16) 173) 'up)
             (cons (logior (lsh 2 16) 174) 'right)
             (cons (logior (lsh 2 16) 175) 'down)
             (cons (logior (lsh 2 16) 176) 'kp-ring)
             (cons (logior (lsh 2 16) 201) 'kp-square)
             (cons (logior (lsh 2 16) 204) 'kp-cube)
             (cons (logior (lsh 3 16)   8) 'backspace)
             (cons (logior (lsh 3 16)   9) 'tab)
             (cons (logior (lsh 3 16)  10) 'linefeed)
             (cons (logior (lsh 3 16)  11) 'clear)
             (cons (logior (lsh 3 16)  13) 'return)
             (cons (logior (lsh 3 16)  18) 'pause)
             (cons (logior (lsh 3 16)  25) 'S-tab)
             (cons (logior (lsh 3 16)  27) 'escape)
             (cons (logior (lsh 3 16) 127) 'delete)
             ))
      (set-terminal-parameter frame 'x-setup-function-keys t))))
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



;;;; Miscellaneous mouse bindings.

;;; Allow shift-clicks to work just like under NS
(defun mouse-extend-region (event)
  "Move point or mark so as to extend region.
This should be bound to a mouse click event type."
  (interactive "e")
  (mouse-minibuffer-check event)
  (let ((posn (event-end event)))
    (if (not (windowp (posn-window posn)))
        (error "Cursor not in text area of window"))
    (select-window (posn-window posn))
    (cond
     ((not (numberp (posn-point posn))))
     ((or (not mark-active) (> (abs (- (posn-point posn) (point)))
                               (abs (- (posn-point posn) (mark)))))
      (let ((point-save (point)))
        (unwind-protect
            (progn
              (goto-char (posn-point posn))
              (push-mark nil t t)
              (or transient-mark-mode
                  (sit-for 1)))
          (goto-char point-save))))
     (t
      (goto-char (posn-point posn))))))

(define-key global-map [S-mouse-1] 'mouse-extend-region)
(global-unset-key [S-down-mouse-1])



510
;; Must come after keybindings.
511 512 513 514 515 516 517 518 519 520

(fmakunbound 'clipboard-yank)
(fmakunbound 'clipboard-kill-ring-save)
(fmakunbound 'clipboard-kill-region)
(fmakunbound 'menu-bar-enable-clipboard)

;; Add a couple of menus and rearrange some others; easiest just to redo toplvl
;; Note keymap defns must be given last-to-first
(define-key global-map [menu-bar] (make-sparse-keymap "menu-bar"))

521 522 523 524 525 526
(setq menu-bar-final-items
      (cond ((eq system-type 'darwin)
             '(buffer windows services help-menu))
            ;; Otherwise, GNUstep.
            (t
             '(buffer windows services hide-app quit))))
527

528 529 530 531
;; Add standard top-level items to GNUstep menu.
(unless (eq system-type 'darwin)
  (define-key global-map [menu-bar quit] '("Quit" . save-buffers-kill-emacs))
  (define-key global-map [menu-bar hide-app] '("Hide" . ns-do-hide-emacs)))
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

(define-key global-map [menu-bar services]
  (cons "Services" (make-sparse-keymap "Services")))
(define-key global-map [menu-bar windows] (make-sparse-keymap "Windows"))
(define-key global-map [menu-bar buffer]
  (cons "Buffers" global-buffers-menu-map))
;;  (cons "Buffers" (make-sparse-keymap "Buffers")))
(define-key global-map [menu-bar tools] (cons "Tools" menu-bar-tools-menu))
(define-key global-map [menu-bar options] (cons "Options" menu-bar-options-menu))
(define-key global-map [menu-bar edit] (cons "Edit" menu-bar-edit-menu))
(define-key global-map [menu-bar file] (cons "File" menu-bar-file-menu))

;; If running under GNUstep, rename "Help" to "Info"
(cond ((eq system-type 'darwin)
       (define-key global-map [menu-bar help-menu]
	 (cons "Help" menu-bar-help-menu)))
      (t
       (let ((contents (reverse (cdr menu-bar-help-menu))))
	 (setq menu-bar-help-menu
	       (append (list 'keymap) (cdr contents) (list "Info"))))
       (define-key global-map [menu-bar help-menu]
	 (cons "Info" menu-bar-help-menu))))


;;;; Add to help / info menu
(defun info-ns-emacs ()
  "Jump to ns-emacs info item."
  (interactive)
  (info "ns-emacs"))

(define-key menu-bar-help-menu [ns-bug-report]
  '("Report Emacs.app bug..." . ns-submit-bug-report))
(define-key menu-bar-help-menu [info-ns]
  '("Emacs.app Manual" . info-ns-emacs))
(if (not (eq system-type 'darwin))
    ;; in OS X it's in the app menu already
    (define-key menu-bar-help-menu [info-panel]
      '("About Emacs..." . ns-do-emacs-info-panel)))


;;;; File menu, replaces standard under ns-extended-platform-support
(defvar menu-bar-ns-file-menu (make-sparse-keymap "File"))
(define-key menu-bar-ns-file-menu [one-window]
  '("Remove Splits" . delete-other-windows))
(define-key menu-bar-ns-file-menu [split-window]
  '("Split Window" . split-window-vertically))

(define-key menu-bar-ns-file-menu [separator-print] '("--"))

(defvar ns-ps-print-menu-map (make-sparse-keymap "Postscript Print"))
(define-key ns-ps-print-menu-map [ps-print-region]
  '("Region (B+W)" . ps-print-region))
(define-key ns-ps-print-menu-map [ps-print-buffer]
  '("Buffer (B+W)" . ps-print-buffer))
(define-key ns-ps-print-menu-map [ps-print-region-faces]
  '("Region" . ps-print-region-with-faces))
(define-key ns-ps-print-menu-map [ps-print-buffer-faces]
  '("Buffer" . ns-ps-print-buffer-with-faces))
(define-key menu-bar-ns-file-menu [postscript-print]
  (cons "Postscript Print" ns-ps-print-menu-map))

(define-key menu-bar-ns-file-menu [print-region]
  '("Print Region" . print-region))
(define-key menu-bar-ns-file-menu [print-buffer]
  '("Print Buffer" . ns-print-buffer))

(define-key menu-bar-ns-file-menu [separator-save] '("--"))

(define-key menu-bar-ns-file-menu [recover-session]
  '("Recover Crashed Session" . recover-session))
(define-key menu-bar-ns-file-menu [revert-buffer]
  '("Revert Buffer" . revert-buffer))
(define-key menu-bar-ns-file-menu [write-file]
  '("Save Buffer As..." . ns-write-file-using-panel))
(define-key menu-bar-ns-file-menu [save-buffer] '("Save Buffer" . save-buffer))

(define-key menu-bar-ns-file-menu [kill-buffer]
  '("Kill Current Buffer" . kill-this-buffer))
(define-key menu-bar-ns-file-menu [delete-this-frame]
  '("Close Frame" . delete-frame))

(define-key menu-bar-ns-file-menu [separator-open] '("--"))

(define-key menu-bar-ns-file-menu [insert-file]
  '("Insert File..." . insert-file))
(define-key menu-bar-ns-file-menu [dired]
  '("Open Directory..." . ns-open-file-using-panel))
(define-key menu-bar-ns-file-menu [open-file]
  '("Open File..." . ns-open-file-using-panel))
(define-key menu-bar-ns-file-menu [make-frame]
  '("New Frame" . make-frame))


;;;; Edit menu: Modify slightly

627
;; Substitute a Copy function that works better under X (for GNUstep).
628 629 630
(easy-menu-remove-item global-map '("menu-bar" "edit") 'copy)
(define-key-after menu-bar-edit-menu [copy]
  '(menu-item "Copy" ns-copy-including-secondary
631 632
    :enable mark-active
    :help "Copy text in region between mark and current position")
633 634
  'cut)

635 636
;; Change to same precondition as select-and-paste, as we don't have
;; `x-selection-exists-p'.
637 638 639
(easy-menu-remove-item global-map '("menu-bar" "edit") 'paste)
(define-key-after menu-bar-edit-menu [paste]
  '(menu-item "Paste" yank
640 641
    :enable (and (cdr yank-menu) (not buffer-read-only))
    :help "Paste (yank) text most recently cut/copied")
642 643
  'copy)

644
;; Change text to be more consistent with surrounding menu items `paste', etc.
645 646 647
(easy-menu-remove-item global-map '("menu-bar" "edit") 'paste-from-menu)
(define-key-after menu-bar-edit-menu [select-paste]
  '(menu-item "Select and Paste" yank-menu
648 649
    :enable (and (cdr yank-menu) (not buffer-read-only))
    :help "Choose a string from the kill ring and paste it")
650 651
  'paste)

652
;; Separate undo from cut/paste section, add spell for platform consistency.
653 654 655 656 657 658 659 660 661 662 663 664 665
(define-key-after menu-bar-edit-menu [separator-undo] '("--") 'undo)
(define-key-after menu-bar-edit-menu [spell] '("Spell" . ispell-menu-map) 'fill)


;;;; Windows menu
(defun menu-bar-select-frame ()
  (interactive)
  (make-frame-visible last-command-event)
  (raise-frame last-command-event)
  (select-frame last-command-event))

(defun menu-bar-update-frames ()
  ;; If user discards the Windows item, play along.
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
  (when (lookup-key (current-global-map) [menu-bar windows])
    (let ((frames (frame-list))
          (frames-menu (make-sparse-keymap "Select Frame")))
      (setcdr frames-menu
              (nconc
               (mapcar (lambda (frame)
                         (list* frame
                                (cdr (assq 'name (frame-parameters frame)))
                                'menu-bar-select-frame))
                       frames)
               (cdr frames-menu)))
      (define-key frames-menu [separator-frames] '("--"))
      (define-key frames-menu [popup-color-panel]
        '("Colors..." . ns-popup-color-panel))
      (define-key frames-menu [popup-font-panel]
        '("Font Panel..." . ns-popup-font-panel))
      (define-key frames-menu [separator-arrange] '("--"))
      (define-key frames-menu [arrange-all-frames]
        '("Arrange All Frames" . ns-arrange-all-frames))
      (define-key frames-menu [arrange-visible-frames]
        '("Arrange Visible Frames" . ns-arrange-visible-frames))
      ;; Don't use delete-frame as event name
      ;; because that is a special event.
      (define-key (current-global-map) [menu-bar windows]
        (cons "Windows" frames-menu)))))
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

(defun force-menu-bar-update-buffers ()
  ;; This is a hack to get around fact that we already checked
  ;; frame-or-buffer-changed-p and reset it, so menu-bar-update-buffers
  ;; does not pick up any change.
  (menu-bar-update-buffers t))

(add-hook 'menu-bar-update-fab-hook 'menu-bar-update-frames)
(add-hook 'menu-bar-update-fab-hook 'force-menu-bar-update-buffers)

(defun menu-bar-update-frames-and-buffers ()
  (if (frame-or-buffer-changed-p)
      (run-hooks 'menu-bar-update-fab-hook)))

(setq menu-bar-update-hook
      (delq 'menu-bar-update-buffers menu-bar-update-hook))
(add-hook 'menu-bar-update-hook 'menu-bar-update-frames-and-buffers)

(menu-bar-update-frames-and-buffers)


;; ns-arrange functions contributed
;; by Eberhard Mandler <mandler@dbag.ulm.DaimlerBenz.COM>
(defun ns-arrange-all-frames ()
  "Arranges all frames according to topline"
  (interactive)
  (ns-arrange-frames t))

(defun ns-arrange-visible-frames ()
  "Arranges all visible frames according to topline"
  (interactive)
  (ns-arrange-frames nil))

(defun ns-arrange-frames ( vis)
  (let ((frame (next-frame))
	(end-frame (selected-frame))
	(inc-x 20)                      ;relative position of frames
	(inc-y 22)
	(x-pos 100)                     ;start position
	(y-pos 40)
	(done nil))
    (while (not done)                   ;cycle through all frames
      (if (not (or vis (eq (frame-visible-p frame) t)))
734
          (setq x-pos x-pos); do nothing; true case
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
	(set-frame-position frame x-pos y-pos)
	(setq x-pos (+ x-pos inc-x))
	(setq y-pos (+ y-pos inc-y))
	(raise-frame frame))
      (select-frame frame)
      (setq frame (next-frame))
      (setq done (equal frame end-frame)))
    (set-frame-position end-frame x-pos y-pos)
    (raise-frame frame)
    (select-frame frame)))


;;;; Services
(defun ns-define-service (path)
  (let ((mapping [menu-bar services])
	(service (mapconcat 'identity path "/"))
	(name (intern
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
               (subst-char-in-string
                ?\s ?-
                (mapconcat 'identity (cons "ns-service" path) "-")))))
    ;; This defines the function.
    (defalias name
      (lexical-let ((service service))
        (lambda (arg)
          (interactive "p")
          (let* ((in-string
                  (cond ((stringp arg) arg)
                        (mark-active
                         (buffer-substring (region-beginning) (region-end)))))
                 (out-string (ns-perform-service service in-string)))
            (cond
             ((stringp arg) out-string)
             ((and out-string (or (not in-string)
                                  (not (string= in-string out-string))))
              (if mark-active (delete-region (region-beginning) (region-end)))
              (insert out-string)
              (setq deactivate-mark nil)))))))
772 773 774 775 776 777 778 779 780 781 782 783 784 785
    (cond
     ((lookup-key global-map mapping)
      (while (cdr path)
	(setq mapping (vconcat mapping (list (intern (car path)))))
	(if (not (keymapp (lookup-key global-map mapping)))
	    (define-key global-map mapping
	      (cons (car path) (make-sparse-keymap (car path)))))
	(setq path (cdr path)))
      (setq mapping (vconcat mapping (list (intern (car path)))))
      (define-key global-map mapping (cons (car path) name))))
    name))

(precompute-menubar-bindings)

786 787 788 789
;; nsterm.m
(defvar ns-input-spi-name)
(defvar ns-input-spi-arg)

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
(defun ns-spi-service-call ()
  "Respond to a service request to Emacs.app."
  (interactive)
  (cond ((string-equal ns-input-spi-name "open-selection")
	 (switch-to-buffer (generate-new-buffer "*untitled*"))
	 (insert ns-input-spi-arg))
	((string-equal ns-input-spi-name "open-file")
	 (dnd-open-file ns-input-spi-arg nil))
	((string-equal ns-input-spi-name "mail-selection")
	 (compose-mail)
	 (rfc822-goto-eoh)
	 (forward-line 1)
	 (insert ns-input-spi-arg))
	((string-equal ns-input-spi-name "mail-to")
	 (compose-mail ns-input-spi-arg))
	(t (error (concat "Service " ns-input-spi-name " not recognized")))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;



;;;; Composed key sequence handling for NS system input methods.
;;;; (On NS systems, input methods are provided for CJK characters,
;;;;  etc. which require multiple keystrokes, and during entry a
;;;;  partial ("working") result is typically shown in the editing window.)

(defface ns-working-text-face
  '((t :underline t))
  "Face used to highlight working text during compose sequence insert."
  :group 'ns)

(defvar ns-working-overlay nil
  "Overlay used to highlight working text during compose sequence insert.")
(make-variable-buffer-local 'ns-working-overlay)
(defvar ns-working-overlay-len 0
  "Length of working text during compose sequence insert.")
(make-variable-buffer-local 'ns-working-overlay-len)

829 830
;; Based on mac-win.el 2007/08/26 unicode-2.  This will fail if called
;; from an "interactive" function.
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
(defun ns-in-echo-area ()
  "Whether, for purposes of inserting working composition text, the minibuffer
is currently being used."
  (or isearch-mode
      (and cursor-in-echo-area (current-message))
      ;; Overlay strings are not shown in some cases.
      (get-char-property (point) 'invisible)
      (and (not (bobp))
	   (or (and (get-char-property (point) 'display)
		    (eq (get-char-property (1- (point)) 'display)
			(get-char-property (point) 'display)))
	       (and (get-char-property (point) 'composition)
		    (eq (get-char-property (1- (point)) 'composition)
			(get-char-property (point) 'composition)))))))

846 847
;; Currently not used, doesn't work because the 'interactive' here stays
;; for subinvocations.
848 849 850 851
(defun ns-insert-working-text ()
  (interactive)
  (if (ns-in-echo-area) (ns-echo-working-text) (ns-put-working-text)))

852 853
(defvar ns-working-text)		; nsterm.m

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
(defun ns-put-working-text ()
  "Insert contents of ns-working-text as UTF8 string and mark with
ns-working-overlay.  Any previously existing working text is cleared first.
The overlay is assigned the face ns-working-text-face."
  (interactive)
  (if ns-working-overlay (ns-delete-working-text))
  (let ((start (point)))
    (insert ns-working-text)
    (overlay-put (setq ns-working-overlay (make-overlay start (point)
							(current-buffer) nil t))
		 'face 'ns-working-text-face)
    (setq ns-working-overlay-len (+ ns-working-overlay-len (- (point) start)))))

(defun ns-echo-working-text ()
  "Echo contents of ns-working-text in message display area.
See ns-insert-working-text."
  (if ns-working-overlay (ns-unecho-working-text))
  (let* ((msg (current-message))
	 (msglen (length msg))
	 message-log-max)
    (setq ns-working-overlay-len (length ns-working-text))
    (setq msg (concat msg ns-working-text))
    (put-text-property msglen (+ msglen ns-working-overlay-len) 'face 'ns-working-text-face msg)
    (message "%s" msg)
    (setq ns-working-overlay t)))

(defun ns-delete-working-text()
  "Delete working text and clear ns-working-overlay."
  (interactive)
  (delete-backward-char ns-working-overlay-len)
  (setq ns-working-overlay-len 0)
  (delete-overlay ns-working-overlay))

(defun ns-unecho-working-text()
  "Delete working text from echo area and clear ns-working-overlay."
  (let ((msg (current-message))
	message-log-max)
    (setq msg (substring msg 0 (- (length msg) ns-working-overlay-len)))
    (setq ns-working-overlay-len 0)
    (setq ns-working-overlay nil)))


896 897
(declare-function ns-convert-utf8-nfd-to-nfc "nsfns.m" (str))

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
;;;; OS X file system Unicode UTF-8 NFD (decomposed form) support
;; Lisp code based on utf-8m.el, by Seiji Zenitani, Eiji Honjoh, and
;; Carsten Bormann.
(if (eq system-type 'darwin)
    (progn

      (defun ns-utf8-nfd-post-read-conversion (length)
	"Calls ns-convert-utf8-nfd-to-nfc to compose char sequences."
	(save-excursion
	  (save-restriction
	    (narrow-to-region (point) (+ (point) length))
	    (let ((str (buffer-string)))
	      (delete-region (point-min) (point-max))
	      (insert (ns-convert-utf8-nfd-to-nfc str))
	      (- (point-max) (point-min))
	      ))))

      (define-coding-system 'utf-8-nfd
	"UTF-8 NFD (decomposed) encoding."
	:coding-type 'utf-8
	:mnemonic ?U
	:charset-list '(unicode)
	:post-read-conversion 'ns-utf8-nfd-post-read-conversion)
      (set-file-name-coding-system 'utf-8-nfd)))

;; PENDING: disable composition-based display for Indic scripts as it
;;          is not working well under NS for some reason
(set-char-table-range composition-function-table
926
                      '(#x0900 . #x0DFF) nil)
927 928 929 930


;;;; Inter-app communications support.

931 932
(defvar ns-input-text)			; nsterm.m

933 934 935 936 937
(defun ns-insert-text ()
  "Insert contents of ns-input-text at point."
  (interactive)
  (insert ns-input-text)
  (setq ns-input-text nil))
938

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
(defun ns-insert-file ()
  "Insert contents of file ns-input-file like insert-file but with less
prompting.  If file is a directory perform a find-file on it."
  (interactive)
  (let ((f))
    (setq f (car ns-input-file))
    (setq ns-input-file (cdr ns-input-file))
    (if (file-directory-p f)
        (find-file f)
      (push-mark (+ (point) (car (cdr (insert-file-contents f))))))))

(defvar ns-select-overlay nil
  "Overlay used to highlight areas in files requested by NS apps.")
(make-variable-buffer-local 'ns-select-overlay)

954 955
(defvar ns-input-line) 			; nsterm.m

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
(defun ns-open-file-select-line ()
  "Brings up a buffer containing file ns-input-file,\n\
and highlights lines indicated by ns-input-line."
  (interactive)
  (ns-find-file)
  (cond
   ((and ns-input-line (buffer-modified-p))
    (if ns-select-overlay
        (setq ns-select-overlay (delete-overlay ns-select-overlay)))
    (deactivate-mark)
    (goto-line (if (consp ns-input-line)
                   (min (car ns-input-line) (cdr ns-input-line))
                 ns-input-line)))
   (ns-input-line
    (if (not ns-select-overlay)
        (overlay-put (setq ns-select-overlay (make-overlay (point-min) (point-min)))
                     'face 'highlight))
    (let ((beg (save-excursion
                 (goto-line (if (consp ns-input-line)
                                (min (car ns-input-line) (cdr ns-input-line))
                              ns-input-line))
                 (point)))
          (end (save-excursion
                 (goto-line (+ 1 (if (consp ns-input-line)
                                     (max (car ns-input-line) (cdr ns-input-line))
                                   ns-input-line)))
                 (point))))
      (move-overlay ns-select-overlay beg end)
      (deactivate-mark)
      (goto-char beg)))
   (t
    (if ns-select-overlay
        (setq ns-select-overlay (delete-overlay ns-select-overlay))))))

(defun ns-unselect-line ()
  "Removes any NS highlight a buffer may contain."
  (if ns-select-overlay
      (setq ns-select-overlay (delete-overlay ns-select-overlay))))

(add-hook 'first-change-hook 'ns-unselect-line)



;;;; Preferences handling.
1000
(declare-function ns-get-resource "nsfns.m" (owner name))
1001 1002 1003 1004 1005 1006 1007 1008 1009

(defun get-lisp-resource (arg1 arg2)
  (let ((res (ns-get-resource arg1 arg2)))
    (cond
     ((not res) 'unbound)
     ((string-equal (upcase res) "YES") t)
     ((string-equal (upcase res) "NO")  nil)
     (t (read res)))))

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
;; nsterm.m
(defvar ns-command-modifier)
(defvar ns-control-modifier)
(defvar ns-function-modifier)
(defvar ns-antialias-text)
(defvar ns-use-qd-smoothing)
(defvar ns-use-system-highlight-color)

(declare-function ns-set-resource "nsfns.m" (owner name value))
(declare-function ns-font-name "nsfns.m" (name))
(declare-function ns-read-file-name "nsfns.m"
		  (prompt &optional dir isLoad init))

1023 1024 1025 1026 1027 1028 1029 1030 1031
(defun ns-save-preferences ()
  "Set all the defaults."
  (interactive)
  ;; Global preferences
  (ns-set-resource nil "AlternateModifier" (symbol-name ns-alternate-modifier))
  (ns-set-resource nil "CommandModifier" (symbol-name ns-command-modifier))
  (ns-set-resource nil "ControlModifier" (symbol-name ns-control-modifier))
  (ns-set-resource nil "FunctionModifier" (symbol-name ns-function-modifier))
  (ns-set-resource nil "CursorBlinkRate"
1032 1033 1034
                   (if ns-cursor-blink-rate
                       (number-to-string ns-cursor-blink-rate)
                     "NO"))
1035
  (ns-set-resource nil "ExpandSpace"
1036 1037 1038
                   (if ns-expand-space
                       (number-to-string ns-expand-space)
                     "NO"))
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
  (ns-set-resource nil "GSFontAntiAlias" (if ns-antialias-text "YES" "NO"))
  (ns-set-resource nil "UseQuickdrawSmoothing"
		   (if ns-use-qd-smoothing "YES" "NO"))
  (ns-set-resource nil "UseSystemHighlightColor"
		   (if ns-use-system-highlight-color "YES" "NO"))
  ;; Default frame parameters
  (let ((p (frame-parameters)))
    (let ((f (assq 'font p)))
      (if f (ns-set-resource nil "Font" (ns-font-name (cdr f)))))
    (let ((fs (assq 'fontsize p)))
      (if fs (ns-set-resource nil "FontSize" (number-to-string (cdr fs)))))
    (let ((fgc (assq 'foreground-color p)))
      (if fgc (ns-set-resource nil "Foreground" (cdr fgc))))
    (let ((bgc (assq 'background-color p)))
      (if bgc (ns-set-resource nil "Background" (cdr bgc))))
    (let ((cc (assq 'cursor-color p)))
      (if cc (ns-set-resource nil "CursorColor" (cdr cc))))
    (let ((ct (assq 'cursor-type p)))
      (if ct (ns-set-resource nil "CursorType"
1058 1059
                              (if (symbolp (cdr ct))
                                  (symbol-name (cdr ct)) (cdr ct)))))
1060 1061 1062 1063 1064 1065 1066
    (let ((under (assq 'underline p)))
      (if under (ns-set-resource nil "Underline"
				 (cond ((eq (cdr under) t) "YES")
				       ((eq (cdr under) nil) "NO")
				       (t (cdr under))))))
    (let ((ibw (assq 'internal-border-width p)))
      (if ibw (ns-set-resource nil "InternalBorderWidth"
1067 1068 1069 1070 1071 1072 1073 1074 1075
                               (number-to-string (cdr ibw)))))
    (let ((vsb (assq 'vertical-scroll-bars p)))
      (if vsb (ns-set-resource nil "VerticalScrollBars"
                               (case (cdr vsb)
                                ((t) "YES")
                                ((nil) "NO")
                                ((left) "left")
                                ((right) "right")
                                (t nil)))))
1076 1077
    (let ((height (assq 'height p)))
      (if height (ns-set-resource nil "Height"
1078
                                  (number-to-string (cdr height)))))
1079 1080
    (let ((width (assq 'width p)))
      (if width (ns-set-resource nil "Width"
1081
                                 (number-to-string (cdr width)))))
1082 1083
    (let ((top (assq 'top p)))
      (if top (ns-set-resource nil "Top"
1084
                               (number-to-string (cdr top)))))
1085 1086
    (let ((left (assq 'left p)))
      (if left (ns-set-resource nil "Left"
1087
                                (number-to-string (cdr left)))))
1088 1089 1090
    ;; These not fully supported
    (let ((ar (assq 'auto-raise p)))
      (if ar (ns-set-resource nil "AutoRaise"
1091
                              (if (cdr ar) "YES" "NO"))))
1092 1093
    (let ((al (assq 'auto-lower p)))
      (if al (ns-set-resource nil "AutoLower"
1094
                              (if (cdr al) "YES" "NO"))))
1095 1096
    (let ((mbl (assq 'menu-bar-lines p)))
      (if mbl (ns-set-resource nil "Menus"
1097
                               (if (cdr mbl) "YES" "NO"))))
1098 1099 1100 1101 1102 1103 1104 1105 1106
    )
  (let ((fl (face-list)))
    (while (consp fl)
      (or (eq 'default (car fl))
          ;; dont save Default* since it causes all created faces to
          ;; inherit its values.  The properties of the default face
          ;; have already been saved from the frame-parameters anyway.
          (let* ((name (symbol-name (car fl)))
                 (font (face-font (car fl)))
1107
                 ;; (fontsize (face-fontsize (car fl)))
1108 1109 1110 1111 1112 1113
                 (foreground (face-foreground (car fl)))
                 (background (face-background (car fl)))
                 (underline (face-underline-p (car fl)))
                 (italic (face-italic-p (car fl)))
                 (bold (face-bold-p (car fl)))
                 (stipple (face-stipple (car fl))))
1114 1115 1116 1117
            ;; (ns-set-resource nil (concat name ".attributeFont")
            ;;                  (if font font nil))
            ;; (ns-set-resource nil (concat name ".attributeFontSize")
            ;;                  (if fontsize (number-to-string fontsize) nil))
1118
            (ns-set-resource nil (concat name ".attributeForeground")
1119
                             (if foreground foreground nil))
1120
            (ns-set-resource nil (concat name ".attributeBackground")
1121
                             (if background background nil))
1122
            (ns-set-resource nil (concat name ".attributeUnderline")
1123
                             (if underline "YES" nil))
1124
            (ns-set-resource nil (concat name ".attributeItalic")
1125
                             (if italic "YES" nil))
1126
            (ns-set-resource nil (concat name ".attributeBold")
1127
                             (if bold "YES" nil))
1128 1129 1130 1131
            (and stipple
                 (or (stringp stipple)
                     (setq stipple (prin1-to-string stipple))))
            (ns-set-resource nil (concat name ".attributeStipple")
1132
                             (if stipple stipple nil))))
1133 1134
      (setq fl (cdr fl)))))

1135 1136
(declare-function menu-bar-options-save-orig "ns-win" () t)

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
;; call ns-save-preferences when menu-bar-options-save is called
(fset 'menu-bar-options-save-orig (symbol-function 'menu-bar-options-save))
(defun ns-save-options ()
  (interactive)
  (menu-bar-options-save-orig)
  (ns-save-preferences))
(fset 'menu-bar-options-save (symbol-function 'ns-save-options))


;;;; File handling.

(defun ns-open-file-using-panel ()
  "Pop up open-file panel, and load the result in a buffer."
  (interactive)
1151
  ;; Prompt dir defaultName isLoad initial.
1152 1153 1154 1155 1156 1157 1158 1159
  (setq ns-input-file (ns-read-file-name "Select File to Load" nil t nil))
  (if ns-input-file
      (and (setq ns-input-file (list ns-input-file)) (ns-find-file))))

(defun ns-write-file-using-panel ()
  "Pop up save-file panel, and save buffer in resulting name."
  (interactive)
  (let (ns-output-file)
1160
    ;; Prompt dir defaultName isLoad initial.
1161 1162 1163 1164
    (setq ns-output-file (ns-read-file-name "Save As" nil nil nil))
    (message ns-output-file)
    (if ns-output-file (write-file ns-output-file))))

1165 1166 1167 1168 1169 1170 1171
(defvar ns-pop-up-frames 'fresh
  "*Non-nil means open files upon request from the Workspace in a new frame.
If t, always do so.  Any other non-nil value means open a new frame
unless the current buffer is a scratch buffer.")

(declare-function ns-hide-emacs "nsfns.m" (on))

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
(defun ns-find-file ()
  "Do a find-file with the ns-input-file as argument."
  (interactive)
  (let ((f) (file) (bufwin1) (bufwin2))
    (setq f (file-truename (car ns-input-file)))
    (setq ns-input-file (cdr ns-input-file))
    (setq file (find-file-noselect f))
    (setq bufwin1 (get-buffer-window file 'visible))
    (setq bufwin2 (get-buffer-window "*scratch*" 'visibile))
    (cond
     (bufwin1
      (select-frame (window-frame bufwin1))
      (raise-frame (window-frame bufwin1))
      (select-window bufwin1))
     ((and (eq ns-pop-up-frames 'fresh) bufwin2)
      (ns-hide-emacs 'activate)
      (select-frame (window-frame bufwin2))
      (raise-frame (window-frame bufwin2))
      (select-window bufwin2)
      (find-file f))
     (ns-pop-up-frames
      (ns-hide-emacs 'activate)
      (let ((pop-up-frames t)) (pop-to-buffer file nil)))
     (t
      (ns-hide-emacs 'activate)
      (find-file f)))))



;;;; Frame-related functions.

;; Don't show the frame name; that's redundant with NS.
(setq-default mode-line-frame-identification '("  "))

;; You say tomAYto, I say tomAHto..
(defvaralias 'ns-option-modifier 'ns-alternate-modifier)

(defun ns-do-hide-emacs ()
  (interactive)
  (ns-hide-emacs t))

1213 1214
(declare-function ns-hide-others "nsfns.m" ())

1215 1216 1217 1218
(defun ns-do-hide-others ()
  (interactive)
  (ns-hide-others))

1219 1220
(declare-function ns-emacs-info-panel "nsfns.m" ())

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
(defun ns-do-emacs-info-panel ()
  (interactive)
  (ns-emacs-info-panel))

(defun ns-next-frame ()
  "Switch to next visible frame."
  (interactive)
  (other-frame 1))
(defun ns-prev-frame ()
  "Switch to previous visible frame."
  (interactive)
  (other-frame -1))

1234
;; If no position specified, make new frame offset by 25 from current.
1235
(add-hook 'before-make-frame-hook
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
          (lambda ()
            (let ((left (cdr (assq 'left (frame-parameters))))
                  (top (cdr (assq 'top (frame-parameters)))))
              (if (consp left) (setq left (cadr left)))
              (if (consp top) (setq top (cadr top)))
              (cond
               ((or (assq 'top parameters) (assq 'left parameters)))
               ((or (not left) (not top)))
               (t
                (setq parameters (cons (cons 'left (+ left 25))
                                       (cons (cons 'top (+ top 25))
                                             parameters))))))))

;; frame will be focused anyway, so select it
1250 1251
(add-hook 'after-make-frame-functions 'select-frame)

1252 1253 1254 1255 1256
;; (defun ns-win-suspend-error ()
;;   (error "Suspending an emacs running under *Step/OS X makes no sense"))
;; (add-hook 'suspend-hook 'ns-win-suspend-error)
;; (substitute-key-definition 'suspend-emacs 'iconify-or-deiconify-frame
;; 			   global-map)
1257 1258 1259 1260 1261 1262 1263

;; Based on a function by David Reitter <dreitter@inf.ed.ac.uk> ;
;; see http://lists.gnu.org/archive/html/emacs-devel/2005-09/msg00681.html .
(defun ns-toggle-toolbar (&optional frame)
  "Switches the tool bar on and off in frame FRAME.
 If FRAME is nil, the change applies to the selected frame."
  (interactive)
1264 1265
  (modify-frame-parameters
   frame (list (cons 'tool-bar-lines
1266 1267 1268 1269
		       (if (> (or (frame-parameter frame 'tool-bar-lines) 0) 0)
				   0 1)) ))
  (if (not tool-bar-mode) (tool-bar-mode t)))

1270 1271
(defvar ns-cursor-blink-mode) 		; nsterm.m

1272
;; Redefine from frame.el.
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
(define-minor-mode blink-cursor-mode
  "Toggle blinking cursor mode.
With a numeric argument, turn blinking cursor mode on if ARG is positive,
otherwise turn it off.  When blinking cursor mode is enabled, the
cursor of the selected window blinks.

Note that this command is effective only when Emacs
displays through a window system, because then Emacs does its own
cursor display.  On a text-only terminal, this is not implemented."
  :init-value (not (or noninteractive
		       no-blinking-cursor
		       (eq ns-cursor-blink-rate nil)))
  :initialize 'custom-initialize-safe-default
  :group 'cursor
  :global t
  (if blink-cursor-mode
      (setq ns-cursor-blink-mode t)
      (setq ns-cursor-blink-mode nil)))



;;;; Dialog-related functions.

;; Ask user for confirm before printing.  Due to Kevin Rodgers.
(defun ns-print-buffer ()
  "Interactive front-end to `print-buffer': asks for user confirmation first."
  (interactive)
  (if (and (interactive-p)
1301 1302 1303 1304 1305 1306 1307 1308 1309
           (or (listp last-nonmenu-event)
               (and (char-or-string-p (event-basic-type last-command-event))
                    (memq 'super (event-modifiers last-command-event)))))
      (let ((last-nonmenu-event (if (listp last-nonmenu-event)
                                    last-nonmenu-event
                                  ;; Fake it:
                                  `(mouse-1 POSITION 1))))
        (if (y-or-n-p (format "Print buffer %s? " (buffer-name)))
            (print-buffer)
1310 1311 1312 1313 1314 1315
	  (error "Cancelled")))
    (print-buffer)))

(defun ns-yes-or-no-p (prompt)
  "As yes-or-no-p except that NS panel always used for querying."
  (interactive)
1316 1317
  (setq last-nonmenu-event nil)
  (yes-or-no-p prompt))
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329


;;;; Font support.

(defalias 'x-list-fonts 'ns-list-fonts)
;; Needed for font listing functions under both backend and normal
(setq scalable-fonts-allowed t)

;; Set to use font panel instead
(defalias 'generate-fontset-menu 'ns-popup-font-panel)
(defalias 'mouse-set-font 'ns-popup-font-panel)

1330 1331 1332 1333
;; nsterm.m
(defvar ns-input-font)
(defvar ns-input-fontsize)

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
(defun ns-respond-to-change-font ()
  "Respond to changeFont: event, expecting ns-input-font and\n\
ns-input-fontsize of new font."
  (interactive)
  (modify-frame-parameters (selected-frame)
                           (list (cons 'font ns-input-font)
                                 (cons 'fontsize ns-input-fontsize)))
  (set-frame-font ns-input-font))


;; Default fontset for Mac OS X.  This is mainly here to show how a fontset
;; can be set up manually.  Ordinarily, fontsets are auto-created whenever
;; a font is chosen by 
(defvar ns-standard-fontset-spec
1348 1349 1350 1351 1352 1353 1354 1355 1356
  ;; Only some code supports this so far, so use uglier XLFD version
  ;; "-ns-*-*-*-*-*-10-*-*-*-*-*-fontset-standard,latin:Courier,han:Kai"
  (mapconcat 'identity
             '("-ns-*-*-*-*-*-10-*-*-*-*-*-fontset-standard"
               "latin:-*-Courier-*-*-*-*-10-*-*-*-*-*-iso10646-1"
               "han:-*-Kai-*-*-*-*-10-*-*-*-*-*-iso10646-1"
               "cyrillic:-*-Trebuchet$MS-*-*-*-*-10-*-*-*-*-*-iso10646-1")
             ",")
  "String of fontset spec of the standard fontset.
1357 1358 1359 1360
This defines a fontset consisting of the Courier and other fonts that
come with OS X\".
See the documentation of `create-fontset-from-fontset-spec for the format.")

1361
;; Conditional on new-fontset so bootstrapping works on non-GUI compiles.
1362 1363 1364 1365 1366
(if (fboundp 'new-fontset)
    (progn
      ;; Setup the default fontset.
      (setup-default-fontset)
      ;; Create the standard fontset.
1367
      (create-fontset-from-fontset-spec ns-standard-fontset-spec t)))
1368

1369 1370
;;(push (cons 'font "-ns-*-*-*-*-*-10-*-*-*-*-*-fontset-standard")
;;      default-frame-alist)
1371

1372
;; Add some additional scripts to var we use for fontset generation.
1373 1374 1375
(setq script-representative-chars
      (cons '(kana #xff8a)
	    (cons '(symbol #x2295 #x2287 #x25a1)
1376
                  script-representative-chars)))
1377 1378 1379 1380


;;;; Pasteboard support.

1381 1382
(declare-function ns-get-cut-buffer-internal "nsselect.m" (buffer))

1383 1384 1385 1386
(defun ns-get-pasteboard ()
  "Returns the value of the pasteboard."
  (ns-get-cut-buffer-internal 'PRIMARY))

1387 1388
(declare-function ns-store-cut-buffer-internal "nsselect.m" (buffer string))

1389 1390 1391 1392 1393 1394
(defun ns-set-pasteboard (string)
  "Store STRING into the NS server's pasteboard."
  ;; Check the data type of STRING.
  (if (not (stringp string)) (error "Nonstring given to pasteboard"))
  (ns-store-cut-buffer-internal 'PRIMARY string))

1395 1396 1397
;; We keep track of the last text selected here, so we can check the
;; current selection against it, and avoid passing back our own text
;; from ns-pasteboard-value.
1398 1399 1400
(defvar ns-last-selected-text nil)

(defun ns-select-text (text &optional push)
1401
  "Put TEXT, a string, on the pasteboard."
1402 1403 1404 1405 1406
  ;; Don't send the pasteboard too much text.
  ;; It becomes slow, and if really big it causes errors.
  (ns-set-pasteboard text)
  (setq ns-last-selected-text text))

1407 1408 1409
;; Return the value of the current NS selection.  For compatibility
;; with older NS applications, this checks cut buffer 0 before
;; retrieving the value of the primary selection.
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
(defun ns-pasteboard-value ()
  (let (text)
    
    ;; Consult the selection, then the cut buffer.  Treat empty strings
    ;; as if they were unset.
    (or text (setq text (ns-get-pasteboard)))
    (if (string= text "") (setq text nil))
    
    (cond
     ((not text) nil)
     ((eq text ns-last-selected-text) nil)
     ((string= text ns-last-selected-text)
      ;; Record the newer string, so subsequent calls can use the `eq' test.
      (setq ns-last-selected-text text)
      nil)
     (t
      (setq ns-last-selected-text text)))))

(defun ns-copy-including-secondary ()
  (interactive)
  (call-interactively 'kill-ring-save)
  (ns-store-cut-buffer-internal 'SECONDARY
				(buffer-substring (point) (mark t))))
(defun ns-paste-secondary ()
  (interactive)
  (insert (ns-get-cut-buffer-internal 'SECONDARY)))

;; PENDING: not sure what to do here.. for now interprog- are set in
1438
;; init-fn-keys, and unsure whether these x- settings have an effect.
1439 1440
;;(setq interprogram-cut-function 'ns-select-text
;;      interprogram-paste-function 'ns-pasteboard-value)
1441
;; These only needed if above not working.
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
(defalias 'x-select-text 'ns-select-text)
(defalias 'x-cut-buffer-or-selection-value 'ns-pasteboard-value)
(defalias 'x-disown-selection-internal 'ns-disown-selection-internal)
(defalias 'x-get-selection-internal 'ns-get-selection-internal)
(defalias 'x-own-selection-internal 'ns-own-selection-internal)

(set-face-background 'region "ns_selection_color")



;;;; Scrollbar handling.

(global-set-key [vertical-scroll-bar down-mouse-1] 'ns-handle-scroll-bar-event)
(global-unset-key [vertical-scroll-bar mouse-1])
(global-unset-key [vertical-scroll-bar drag-mouse-1])

(defun ns-scroll-bar-move (event)
  "Scroll the frame according to an NS scroller event."
  (interactive "e")
  (let* ((pos (event-end event))
         (window (nth 0 pos))
         (scale (nth 2 pos)))
    (save-excursion
      (set-buffer (window-buffer window))
      (cond
       ((eq (car scale) (cdr scale))
	(goto-char (point-max)))
       ((= (car scale) 0)
	(goto-char (point-min)))
       (t
	(goto-char (+ (point-min) 1
		      (scroll-bar-scale scale (- (point-max) (point-min)))))))
      (beginning-of-line)
      (set-window-start window (point))
      (vertical-motion (/ (window-height window) 2) window))))

(defun ns-handle-scroll-bar-event (event)
  "Handle scroll bar EVENT to emulate Mac Toolbox style scrolling."
  (interactive "e")
  (let* ((position (event-start event))
	 (bar-part (nth 4 position))
	 (window (nth 0 position))
	 (old-window (selected-window)))
    (cond
     ((eq bar-part 'ratio)
      (ns-scroll-bar-move event))
     ((eq bar-part 'handle)
      (if (eq window (selected-window))
	  (track-mouse (ns-scroll-bar-move event))
1491
        ;; track-mouse faster for selected window, slower for unselected.
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
	(ns-scroll-bar-move event)))
     (t
      (select-window window)
      (cond
       ((eq bar-part 'up)
	(goto-char (window-start window))
	(scroll-down 1))
       ((eq bar-part 'above-handle)
	(scroll-down))
       ((eq bar-part 'below-handle)
	(scroll-up))
       ((eq bar-part 'down)
	(goto-char (window-start window))
	(scroll-up 1)))
      (select-window old-window)))))


;;;; Color support.

1511 1512
(declare-function ns-list-colors "nsfns.m" (&optional frame))

1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
(defvar x-colors (ns-list-colors)
  "The list of colors defined in non-PANTONE color files.")
(defvar colors x-colors
  "The list of colors defined in non-PANTONE color files.")

(defun ns-defined-colors (&optional frame)
  "Return a list of colors supported for a particular frame.
The argument FRAME specifies which frame to try.
The value may be different for frames on different NS displays."
  (or frame (setq frame (selected-frame)))
  (let ((all-colors x-colors)
	(this-color nil)
	(defined-colors nil))
    (while all-colors
      (setq this-color (car all-colors)
	    all-colors (cdr all-colors))
1529 1530
      ;; (and (face-color-supported-p frame this-color t)
      (setq defined-colors (cons this-color defined-colors))) ;;)
1531 1532 1533 1534
    defined-colors))
(defalias 'x-defined-colors 'ns-defined-colors)
(defalias 'xw-defined-colors 'ns-defined-colors)

1535 1536
(declare-function ns-set-alpha "nsfns.m" (color alpha))

Adrian Robert's avatar