ns-win.el 46.7 KB
Newer Older
1 2
;;; ns-win.el --- lisp side of interface with NeXT/Open/GNUstep/MacOS X window system

Glenn Morris's avatar
Glenn Morris committed
3
;; Copyright (C) 1993, 1994, 2005, 2006, 2007, 2008, 2009
4
;;   Free Software Foundation, Inc.
5

6 7 8 9 10
;; Authors: Carl Edman
;;	Christian Limpach
;;	Scott Bender
;;	Christophe de Dinechin
;;	Adrian Robert
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
;; 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/>.
27 28 29

;;; Commentary:

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

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

39 40
;; A number of other Nextstep convenience functions are defined in
;; this file, which works in close coordination with src/nsfns.m.
41 42 43 44

;;; Code:


Dan Nicolaescu's avatar
Dan Nicolaescu committed
45
(if (not (featurep 'ns))
Glenn Morris's avatar
Glenn Morris committed
46
    (error "%s: Loading ns-win.el but not compiled for GNUstep/MacOS"
47 48
	   (invocation-name)))

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

51 52 53 54 55 56 57 58
;; Documentation-purposes only: actually loaded in loadup.el
(require 'frame)
(require 'mouse)
(require 'faces)
(require 'easymenu)
(require 'menu-bar)
(require 'fontset)

59 60
;; Not needed?
;;(require 'ispell)
61

Glenn Morris's avatar
Glenn Morris committed
62 63 64 65
(defgroup ns nil
  "GNUstep/Mac OS X specific features."
  :group 'environment)

66 67 68 69
;; nsterm.m
(defvar ns-version-string)
(defvar ns-alternate-modifier)

70 71 72 73 74 75
;;;; 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".
76
(defun ns-handle-switch (switch &optional numeric)
77 78
  (let ((aelt (assoc switch command-line-ns-option-alist)))
    (if aelt
79 80 81 82 83 84
	(setq default-frame-alist
	      (cons (cons (nth 3 aelt)
			  (if numeric
			      (string-to-number (pop ns-invocation-args))
			    (or (nth 4 aelt) (pop ns-invocation-args))))
		    default-frame-alist)))))
85 86 87

;; Handler for switches of the form "-switch n"
(defun ns-handle-numeric-switch (switch)
88
  (ns-handle-switch switch t))
89 90 91 92 93 94

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

95
;; Handle the -name option, set the name of the initial frame.
96 97 98
(defun ns-handle-name-switch (switch)
  (or (consp ns-invocation-args)
      (error "%s: missing argument to `%s' option" (invocation-name) switch))
99 100 101 102
  (setq initial-frame-alist (cons (cons 'name (pop ns-invocation-args))
                                  initial-frame-alist)))

;; Set (but not used?) in frame.el.
103
(defvar x-display-name nil
104 105 106
  "The name of the window display on which Emacs was started.
On X, the display name of individual X frames is recorded in the
`display' frame parameter.")
107

108 109 110
;; nsterm.m.
(defvar ns-input-file)

111 112
(defun ns-handle-nxopen (switch)
  (setq unread-command-events (append unread-command-events '(ns-open-file))
113
        ns-input-file (append ns-input-file (list (pop ns-invocation-args)))))
114 115

(defun ns-handle-nxopentemp (switch)
116 117 118
  (setq unread-command-events (append unread-command-events
				      '(ns-open-temp-file))
        ns-input-file (append ns-input-file (list (pop ns-invocation-args)))))
119 120 121 122 123 124 125

(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)
126
  "Process Nextstep-related command line options.
127
This is run before the user's startup file is loaded.
128 129
The options in ARGS are copied to `ns-invocation-args'.
The Nextstep-related settings are then applied using the handlers
130
defined in `command-line-ns-option-alist'.
131
The return value is ARGS minus the number of arguments processed."
132 133 134 135
  ;; 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
136
    (let* ((this-switch (pop ns-invocation-args))
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
	   (orig-this-switch this-switch)
	   completion argval aelt handler)
      ;; 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))

169
(defun ns-parse-geometry (geom)
Glenn Morris's avatar
Glenn Morris committed
170
  "Parse a Nextstep-style geometry string GEOM.
171 172
Returns an alist of the form ((top . TOP), (left . LEFT) ... ).
The properties returned may include `top', `left', `height', and `width'."
173 174 175 176 177 178 179 180 181 182 183 184 185
  (when (string-match "\\([0-9]+\\)\\( \\([0-9]+\\)\\( \\([0-9]+\\)\
\\( \\([0-9]+\\) ?\\)?\\)?\\)?"
		      geom)
    (apply
     'append
     (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)))))))))
186 187 188

;;;; Keyboard mapping.

189 190
;; These tell read-char how to convert these special chars to ASCII.
(put 'S-tab 'ascii-character (logior 16 ?\t))
191 192 193 194 195 196 197 198 199 200 201 202 203 204

(defvar ns-alternatives-map
  (let ((map (make-sparse-keymap)))
    ;; Map certain keypad keys into ASCII characters
    ;; that people usually expect.
    (define-key map [S-tab] [25])
    (define-key map [M-backspace] [?\M-\d])
    (define-key map [M-delete] [?\M-\d])
    (define-key map [M-tab] [?\M-\t])
    (define-key map [M-linefeed] [?\M-\n])
    (define-key map [M-clear] [?\M-\C-l])
    (define-key map [M-return] [?\M-\C-m])
    (define-key map [M-escape] [?\M-\e])
    map)
205
  "Keymap of alternative meanings for some keys under Nextstep.")
206

207
;; Here are some Nextstep-like bindings for command key sequences.
208
(define-key global-map [?\s-,] 'customize)
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
(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)
249
;; (as in Terminal.app)
250 251 252 253 254 255 256 257 258 259
(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)

260 261 262 263
;;; Allow shift-clicks to work similarly to under Nextstep
(define-key global-map [S-mouse-1] 'mouse-save-then-kill)
(global-unset-key [S-down-mouse-1])

264

265
;; Special Nextstep-generated events are converted to function keys.  Here
266
;; are the bindings for them.
267
(define-key global-map [ns-power-off] 'save-buffers-kill-emacs)
268 269 270 271 272 273 274 275 276
(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-spi-service-call] 'ns-spi-service-call)
277
(define-key global-map [ns-new-frame] 'make-frame)
278
(define-key global-map [ns-toggle-toolbar] 'ns-toggle-toolbar)
279
(define-key global-map [ns-show-prefs] 'customize)
280 281


282 283 284 285 286 287 288 289
;; Set up a number of aliases and other layers to pretend we're using
;; the Choi/Mitsuharu Carbon port.

(defvaralias 'mac-allow-anti-aliasing 'ns-antialias-text)
(defvaralias 'mac-command-modifier 'ns-command-modifier)
(defvaralias 'mac-control-modifier 'ns-control-modifier)
(defvaralias 'mac-option-modifier 'ns-option-modifier)
(defvaralias 'mac-function-modifier 'ns-function-modifier)
290
(declare-function ns-do-applescript "nsfns.m" (script))
291 292
(defalias 'do-applescript 'ns-do-applescript)

293
(defun x-setup-function-keys (frame)
294
  "Set up `function-key-map' on the graphical frame FRAME."
295 296
  (unless (terminal-parameter frame 'x-setup-function-keys)
    (with-selected-frame frame
297 298
      (setq interprogram-cut-function 'x-select-text
	    interprogram-paste-function 'x-cut-buffer-or-selection-value)
299 300 301
      (let ((map (copy-keymap ns-alternatives-map)))
	(set-keymap-parent map (keymap-parent local-function-key-map))
	(set-keymap-parent local-function-key-map map))
302 303 304 305 306 307 308 309 310 311
      (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)
312 313
;             (cons (logior (lsh 0 16)   9) 'ns-insert-working-text)
;             (cons (logior (lsh 0 16)  10) 'ns-delete-working-text)
314
             (cons (logior (lsh 0 16)  11) 'ns-spi-service-call)
315 316 317 318
	     (cons (logior (lsh 0 16)  12) 'ns-new-frame)
	     (cons (logior (lsh 0 16)  13) 'ns-toggle-toolbar)
	     (cons (logior (lsh 0 16)  14) 'ns-show-prefs)
	     (cons (logior (lsh 1 16)  32) 'f1)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
             (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)
398 399
             )))
    (set-terminal-parameter frame 'x-setup-function-keys t)))
400 401 402 403 404 405


;; 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"))

406 407 408 409 410 411
(setq menu-bar-final-items
      (cond ((eq system-type 'darwin)
             '(buffer windows services help-menu))
            ;; Otherwise, GNUstep.
            (t
             '(buffer windows services hide-app quit))))
412

413 414 415 416
;; 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)))
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

(define-key global-map [menu-bar services]
  (cons "Services" (make-sparse-keymap "Services")))
(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))))

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

;;;; Edit menu: Modify slightly

446
;; Substitute a Copy function that works better under X (for GNUstep).
447 448 449
(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
450 451
    :enable mark-active
    :help "Copy text in region between mark and current position")
452 453
  'cut)

454 455
;; Change to same precondition as select-and-paste, as we don't have
;; `x-selection-exists-p'.
456 457 458
(easy-menu-remove-item global-map '("menu-bar" "edit") 'paste)
(define-key-after menu-bar-edit-menu [paste]
  '(menu-item "Paste" yank
459 460
    :enable (and (cdr yank-menu) (not buffer-read-only))
    :help "Paste (yank) text most recently cut/copied")
461 462
  'copy)

463
;; Change text to be more consistent with surrounding menu items `paste', etc.
464 465 466
(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
467 468
    :enable (and (cdr yank-menu) (not buffer-read-only))
    :help "Choose a string from the kill ring and paste it")
469 470
  'paste)

471
;; Separate undo from cut/paste section, add spell for platform consistency.
472 473 474 475 476
(define-key-after menu-bar-edit-menu [separator-undo] '("--") 'undo)
(define-key-after menu-bar-edit-menu [spell] '("Spell" . ispell-menu-map) 'fill)


;;;; Services
477 478
(declare-function ns-perform-service "nsfns.m" (service send))

479 480 481 482
(defun ns-define-service (path)
  (let ((mapping [menu-bar services])
	(service (mapconcat 'identity path "/"))
	(name (intern
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
               (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)))))))
503 504 505 506 507 508 509 510 511 512 513 514
    (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))

515 516 517 518
;; nsterm.m
(defvar ns-input-spi-name)
(defvar ns-input-spi-arg)

519 520
(declare-function dnd-open-file "dnd" (uri action))

521
(defun ns-spi-service-call ()
522
  "Respond to a service request."
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
  (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")))))


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



543 544 545 546 547
;; Composed key sequence handling for Nextstep system input methods.
;; (On Nextstep 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.)
548 549 550 551 552 553 554

(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
555 556
  "Overlay used to highlight working text during compose sequence insert.
When text is in th echo area, this just stores the length of the working text.")
557

558 559 560 561
(defvar ns-working-text)		; nsterm.m

;; Test if in echo area, based on mac-win.el 2007/08/26 unicode-2.
;; This will fail if called from a NONASCII_KEYSTROKE event on the global map.
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
(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)))))))

577 578 579
;; The 'interactive' here stays for subinvocations, so the ns-in-echo-area
;; always returns nil for some reason.  If this WASN'T the case, we could
;; map this to [ns-insert-working-text] and eliminate Fevals in nsterm.m.
580
;; These functions test whether in echo area and delegate accordingly.
581
(defun ns-put-working-text ()
582
  (interactive)
583
  (if (ns-in-echo-area) (ns-echo-working-text) (ns-insert-working-text)))
584 585
(defun ns-unput-working-text ()
  (interactive)
586
  (ns-delete-working-text))
587

588
(defun ns-insert-working-text ()
589
  "Insert contents of `ns-working-text' as UTF-8 string and mark with
590 591 592 593
`ns-working-overlay'.  Any previously existing working text is cleared first.
The overlay is assigned the face `ns-working-text-face'."
  ;; FIXME: if buffer is read-only, don't try to insert anything
  ;;  and if text is bound to a command, execute that instead (Bug#1453)
594
  (interactive)
595
  (ns-delete-working-text)
596 597 598 599
  (let ((start (point)))
    (insert ns-working-text)
    (overlay-put (setq ns-working-overlay (make-overlay start (point)
							(current-buffer) nil t))
600
		 'face 'ns-working-text-face)))
601 602

(defun ns-echo-working-text ()
603
  "Echo contents of `ns-working-text' in message display area.
604 605
See `ns-insert-working-text'."
  (ns-delete-working-text)
606 607 608
  (let* ((msg (current-message))
	 (msglen (length msg))
	 message-log-max)
609
    (setq ns-working-overlay (length ns-working-text))
610
    (setq msg (concat msg ns-working-text))
611
    (put-text-property msglen (+ msglen ns-working-overlay)
612
		       'face 'ns-working-text-face msg)
613
    (message "%s" msg)))
614 615

(defun ns-delete-working-text()
616
  "Delete working text and clear `ns-working-overlay'."
617
  (interactive)
618 619 620 621 622 623 624 625 626 627 628 629 630 631
  (cond
   ((and (overlayp ns-working-overlay)
         ;; Still alive?
         (overlay-buffer ns-working-overlay))
    (with-current-buffer (overlay-buffer ns-working-overlay)
      (delete-region (overlay-start ns-working-overlay)
                     (overlay-end ns-working-overlay))
      (delete-overlay ns-working-overlay)))
   ((integerp ns-working-overlay)
    (let ((msg (current-message))
          message-log-max)
      (setq msg (substring msg 0 (- (length msg) ns-working-overlay)))
      (message "%s" msg))))
  (setq ns-working-overlay nil))
632 633


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

636 637 638 639 640 641 642
;;;; 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)
643
	"Calls `ns-convert-utf8-nfd-to-nfc' to compose char sequences."
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
	(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)))



;;;; Inter-app communications support.

665 666
(defvar ns-input-text)			; nsterm.m

667
(defun ns-insert-text ()
668
  "Insert contents of `ns-input-text' at point."
669 670 671
  (interactive)
  (insert ns-input-text)
  (setq ns-input-text nil))
672

673
(defun ns-insert-file ()
674 675
  "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."
676 677 678 679 680 681 682 683 684
  (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
685
  "Overlay used to highlight areas in files requested by Nextstep apps.")
686 687
(make-variable-buffer-local 'ns-select-overlay)

688 689
(defvar ns-input-line) 			; nsterm.m

690
(defun ns-open-file-select-line ()
691 692
  "Open a buffer containing the file `ns-input-file'.
Lines are highlighted according to `ns-input-line'."
693 694 695 696 697 698 699
  (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)
700 701 702 703
    (goto-char (point-min))
    (forward-line (1- (if (consp ns-input-line)
                          (min (car ns-input-line) (cdr ns-input-line))
                        ns-input-line))))
704 705
   (ns-input-line
    (if (not ns-select-overlay)
706 707
        (overlay-put (setq ns-select-overlay (make-overlay (point-min)
                                                           (point-min)))
708 709
                     'face 'highlight))
    (let ((beg (save-excursion
710 711 712 713 714
                 (goto-char (point-min))
                 (line-beginning-position
                  (if (consp ns-input-line)
                      (min (car ns-input-line) (cdr ns-input-line))
                    ns-input-line))))
715
          (end (save-excursion
716 717 718 719 720
                 (goto-char (point-min))
                 (line-beginning-position
                  (1+ (if (consp ns-input-line)
                          (max (car ns-input-line) (cdr ns-input-line))
                        ns-input-line))))))
721 722 723 724 725 726 727 728
      (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 ()
729
  "Removes any Nextstep highlight a buffer may contain."
730 731 732 733 734 735 736 737
  (if ns-select-overlay
      (setq ns-select-overlay (delete-overlay ns-select-overlay))))

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



;;;; Preferences handling.
738
(declare-function ns-get-resource "nsfns.m" (owner name))
739 740 741 742 743 744 745 746 747

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

748
;; nsterm.m
749

750 751 752
(declare-function ns-read-file-name "nsfns.m"
		  (prompt &optional dir isLoad init))

753 754 755 756 757
;;;; File handling.

(defun ns-open-file-using-panel ()
  "Pop up open-file panel, and load the result in a buffer."
  (interactive)
758
  ;; Prompt dir defaultName isLoad initial.
759 760 761 762 763 764 765 766
  (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)
767
    ;; Prompt dir defaultName isLoad initial.
768 769 770 771
    (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))))

772 773
(defcustom ns-pop-up-frames 'fresh
  "Non-nil means open files upon request from the Workspace in a new frame.
774
If t, always do so.  Any other non-nil value means open a new frame
775 776 777 778 779 780
unless the current buffer is a scratch buffer."
  :type '(choice (const :tag "Never" nil)
                 (const :tag "Always" t)
                 (other :tag "Except for scratch buffer" fresh))
  :version "23.1"
  :group 'ns)
781 782 783

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

784
(defun ns-find-file ()
785
  "Do a `find-file' with the `ns-input-file' as argument."
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
  (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.

815
;; Don't show the frame name; that's redundant with Nextstep.
816 817 818 819 820 821 822 823 824
(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))

825 826
(declare-function ns-hide-others "nsfns.m" ())

827 828 829 830
(defun ns-do-hide-others ()
  (interactive)
  (ns-hide-others))

831 832
(declare-function ns-emacs-info-panel "nsfns.m" ())

833 834 835 836 837 838 839 840
(defun ns-do-emacs-info-panel ()
  (interactive)
  (ns-emacs-info-panel))

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

842 843 844 845 846
(defun ns-prev-frame ()
  "Switch to previous visible frame."
  (interactive)
  (other-frame -1))

847
;; If no position specified, make new frame offset by 25 from current.
848
(defvar parameters)		     ; dynamically bound in make-frame
849
(add-hook 'before-make-frame-hook
850 851 852 853 854 855 856 857 858 859 860 861 862 863
          (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
864
;; (if this is not done, modeline is dimmed until first interaction)
865 866
(add-hook 'after-make-frame-functions 'select-frame)

867 868 869
(defvar tool-bar-mode)
(declare-function tool-bar-mode "tool-bar" (&optional arg))

870 871 872 873 874 875
;; 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)
876 877
  (modify-frame-parameters
   frame (list (cons 'tool-bar-lines
878 879 880 881 882 883 884 885
		       (if (> (or (frame-parameter frame 'tool-bar-lines) 0) 0)
				   0 1)) ))
  (if (not tool-bar-mode) (tool-bar-mode t)))



;;;; Dialog-related functions.

886

887 888 889 890 891
;; 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)
892 893 894 895 896 897 898 899 900
           (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)
901 902 903 904 905 906 907 908 909 910
	  (error "Cancelled")))
    (print-buffer)))


;;;; Font support.

;; Needed for font listing functions under both backend and normal
(setq scalable-fonts-allowed t)

;; Set to use font panel instead
911
(declare-function ns-popup-font-panel "nsfns.m" (&optional frame))
912
(defalias 'x-select-font 'ns-popup-font-panel "Pop up the font panel.
913
This function has been overloaded in Nextstep.")
914
(defalias 'mouse-set-font 'ns-popup-font-panel "Pop up the font panel.
915
This function has been overloaded in Nextstep.")
916

917 918 919 920
;; nsterm.m
(defvar ns-input-font)
(defvar ns-input-fontsize)

921
(defun ns-respond-to-change-font ()
922 923
  "Respond to changeFont: event, expecting `ns-input-font' and\n\
`ns-input-fontsize' of new font."
924 925 926 927 928 929 930 931 932
  (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
933
;; a font is chosen by
934
(defvar ns-standard-fontset-spec
935 936 937 938 939 940 941 942 943
  ;; 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.
944
This defines a fontset consisting of the Courier and other fonts that
945 946
come with OS X.
See the documentation of `create-fontset-from-fontset-spec' for the format.")
947

948
;; Conditional on new-fontset so bootstrapping works on non-GUI compiles.
949 950 951
(if (fboundp 'new-fontset)
    (progn
      ;; Setup the default fontset.
952
      (create-default-fontset)
953
      ;; Create the standard fontset.
954 955
      (condition-case err
	  (create-fontset-from-fontset-spec ns-standard-fontset-spec t)
956
	(error (display-warning
957 958 959
		'initialization
		(format "Creation of the standard fontset failed: %s" err)
		:error)))))
960

961 962
(defvar ns-reg-to-script)               ; nsfont.m

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
;; This maps font registries (not exposed by NS APIs for font selection) to
;; unicode scripts (which can be mapped to unicode character ranges which are).
;; See ../international/fontset.el
(setq ns-reg-to-script
      '(("iso8859-1" . latin)
	("iso8859-2" . latin)
	("iso8859-3" . latin)
	("iso8859-4" . latin)
	("iso8859-5" . cyrillic)
	("microsoft-cp1251" . cyrillic)
	("koi8-r" . cyrillic)
	("iso8859-6" . arabic)
	("iso8859-7" . greek)
	("iso8859-8" . hebrew)
	("iso8859-9" . latin)
	("iso8859-10" . latin)
	("iso8859-11" . thai)
	("tis620" . thai)
	("iso8859-13" . latin)
	("iso8859-14" . latin)
	("iso8859-15" . latin)
	("iso8859-16" . latin)
	("viscii1.1-1" . latin)
	("jisx0201" . kana)
	("jisx0208" . han)
	("jisx0212" . han)
	("jisx0213" . han)
	("gb2312.1980" . han)
	("gb18030" . han)
	("gbk-0" . han)
	("big5" . han)
	("cns11643" . han)
	("sisheng_cwnn" . bopomofo)
	("ksc5601.1987" . hangul)
	("ethiopic-unicode" . ethiopic)
	("is13194-devanagari" . indian-is13194)
	("iso10646.indian-1" . devanagari)))

1001 1002 1003

;;;; Pasteboard support.

1004 1005
(declare-function ns-get-cut-buffer-internal "nsselect.m" (buffer))

1006 1007 1008 1009
(defun ns-get-pasteboard ()
  "Returns the value of the pasteboard."
  (ns-get-cut-buffer-internal 'PRIMARY))

1010 1011
(declare-function ns-store-cut-buffer-internal "nsselect.m" (buffer string))

1012
(defun ns-set-pasteboard (string)
1013
  "Store STRING into the pasteboard of the Nextstep display server."
1014 1015 1016 1017
  ;; Check the data type of STRING.
  (if (not (stringp string)) (error "Nonstring given to pasteboard"))
  (ns-store-cut-buffer-internal 'PRIMARY string))

1018 1019
;; 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
1020
;; from x-cut-buffer-or-selection-value.
1021 1022
(defvar ns-last-selected-text nil)

1023
(defun x-select-text (text &optional push)
Eli Zaretskii's avatar
Eli Zaretskii committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  "Select TEXT, a string, according to the window system.

On X, put TEXT in the primary X selection.  For backward
compatibility with older X applications, set the value of X cut
buffer 0 as well, and if the optional argument PUSH is non-nil,
rotate the cut buffers.  If `x-select-enable-clipboard' is
non-nil, copy the text to the X clipboard as well.

On Windows, make TEXT the current selection.  If
`x-select-enable-clipboard' is non-nil, copy the text to the
clipboard as well.  The argument PUSH is ignored.

On Nextstep, put TEXT in the pasteboard; PUSH is ignored."
1037 1038 1039 1040 1041
  ;; 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))

1042 1043 1044
;; Return the value of the current Nextstep selection.  For
;; compatibility with older Nextstep applications, this checks cut
;; buffer 0 before retrieving the value of the primary selection.
1045
(defun x-cut-buffer-or-selection-value ()
1046
  (let (text)
1047

1048 1049 1050 1051
    ;; 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))
1052

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    (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)))



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

1080 1081
(declare-function scroll-bar-scale "scroll-bar" (num-denom whole))

1082
(defun ns-scroll-bar-move (event)
1083
  "Scroll the frame according to a Nextstep scroller event."
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
  (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)
1103
  "Handle scroll bar EVENT to emulate Nextstep style scrolling."
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  (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))
1115
        ;; track-mouse faster for selected window, slower for unselected.
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
	(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.

1135 1136
(declare-function ns-list-colors "nsfns.m" (&optional frame))

1137
(defvar x-colors (ns-list-colors)
Eli Zaretskii's avatar
Eli Zaretskii committed
1138 1139 1140 1141
  "List of basic colors available on color displays.
For X, the list comes from the `rgb.txt' file,v 10.41 94/02/20.
For Nextstep, this is a list of non-PANTONE colors returned by
the operating system.")
1142

1143
(defun xw-defined-colors (&optional frame)
Eli Zaretskii's avatar
Eli Zaretskii committed
1144
  "Internal function called by `defined-colors'."
1145 1146 1147 1148 1149 1150 1151
  (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))
1152 1153
      ;; (and (face-color-supported-p frame this-color t)
      (setq defined-colors (cons this-color defined-colors))) ;;)
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    defined-colors))

;; Functions for color panel + drag
(defun ns-face-at-pos (pos)
  (let* ((frame (car pos))
         (frame-pos (cons (cadr pos) (cddr pos)))
         (window (window-at (car frame-pos) (cdr frame-pos) frame))
         (window-pos (coordinates-in-window-p frame-pos window))
         (buffer (window-buffer window))
         (edges (window-edges window)))
    (cond
     ((not window-pos)
      nil)
     ((eq window-pos 'mode-line)
      'modeline)
     ((eq window-pos 'vertical-line)
      'default)
     ((consp window-pos)
      (save-excursion
        (set-buffer buffer)
        (let ((p (car (compute-motion (window-start window)
                                      (cons (nth 0 edges) (nth 1 edges))
                                      (window-end window)
                                      frame-pos
                                      (- (window-width window) 1)
                                      nil
                                      window))))
          (cond
           ((eq p (window-point window))
            'cursor)
           ((and mark-active (< (region-beginning) p) (< p (region-end)))
            'region)
           (t
	    (let ((faces (get-char-property p 'face window)))
	      (if (consp faces) (car faces) faces)))))))
     (t
      nil))))

1192 1193
(defvar ns-input-color)			; nsterm.m

1194
(defun ns-set-foreground-at-mouse ()
1195
  "Set the foreground color at the mouse location to `ns-input-color'."
1196 1197 1198 1199 1200 1201
  (interactive)
  (let* ((pos (mouse-position))
         (frame (car pos))
         (face (ns-face-at-pos pos)))
    (cond
     ((eq face 'cursor)
1202
      (modify-frame-parameters frame (list (cons 'cursor-color
1203 1204 1205 1206 1207 1208 1209 1210
                                                 ns-input-color))))
     ((not face)
      (modify-frame-parameters frame (list (cons 'foreground-color
                                                 ns-input-color))))
     (t
      (set-face-foreground face ns-input-color frame)))))

(defun ns-set-background-at-mouse ()
1211
  "Set the background color at the mouse location to `ns-input-color'."
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
  (interactive)
  (let* ((pos (mouse-position))
         (frame (car pos))
         (face (ns-face-at-pos pos)))
    (cond
     ((eq face 'cursor)
      (modify-frame-parameters frame (list (cons 'cursor-color
                                                 ns-input-color))))
     ((not face)
      (modify-frame-parameters frame (list (cons 'background-color
                                                 ns-input-color))))
     (t
      (set-face-background face ns-input-color frame)))))

1226
;; Set some options to be as Nextstep-like as possible.
1227 1228 1229 1230 1231
(setq frame-title-format t
      icon-title-format t)


(defvar ns-initialized nil
1232
  "Non-nil if Nextstep windowing has been initialized.")
1233

1234
(declare-function ns-list-services "nsfns.m" ())
1235
(declare-function x-open-connection "nsfns.m"
1236
                  (display &optional xrm-string must-succeed))
1237

1238 1239
;; Do the actual Nextstep Windows setup here; the above code just
;; defines functions and variables that we use now.
1240
(defun ns-initialize-window-system ()
1241
  "Initialize Emacs for Nextstep (Cocoa / GNUstep) windowing."<