view src/nsfont.m @ 105973:b7d8222914b4

2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-clone-subtree-with-time-shift): Make it work at the end of the buffer. * org-mobile.el (org-mobile-write-checksums): Specify coding system. (org-mobile-timestamp-buffer): Keep local variable/mode line at beginning of buffer. * org-latex.el (org-latex-entities-regexp): Fix typo in regexp. * org.el (org-block-todo-from-children-or-siblings-or-parent) (org-block-todo-from-checkboxes): Do not block changes to a nil TODO state. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-habit.el (org-habit-parse-todo): Indicate which habit is wrongly set up in the error messages. * org-colview.el (org-columns-display-here): Don't try to calculate values if the underlying property is not set. (org-columns-string-to-number): Convert age strings back into fractional days. (org-agenda-colview-summarize): Handle extended summary types properly. * org-colview-xemacs.el (org-columns-display-here): Don't try to calculate values if the underlying property is not set. (org-columns-string-to-number): Convert age strings back into fractional days. (org-agenda-colview-summarize): Handle extended summary types properly. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-export-format-drawer-function): New variable. (org-export-format-drawer): New function. (org-export-preprocess-string): Pass the backend as a parameter to `org-export-remove-or-extract-drawers'. (org-export-remove-or-extract-drawers): New parameter BACKEND. * org-protocol.el (org-protocol-char-to-string): New defsubst. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-diary-entry-in-org-file): Add error message when no block is selected. * org-latex.el (org-export-latex-links): Check for protectedness in the last matched character, not after the match. * org-datetree.el (org-datetree-find-date-create): Respect restriction when KEEP-RESTRICTION is set. (org-datetree-file-entry-under): New function. (org-datetree-cleanup): New command. 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-src.el (org-edit-src-code): New optional argument context allows calling functions to avoid altering the saved window configuration. (org-edit-src-exit): Do not restore window configuration when this function is used in the context of saving the edit buffer. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-out, org-clock-cancel): Revert to instances to switching to with-current-buffer, because these seem to cause problems - no idea why. * org-agenda.el (org-agenda-add-entry-to-org-agenda-diary-file): Require diary-lib for (diary-date-display-form). 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-log-reschedule, org-log-redeadline): New options. (org-log-note-headings): Add templates for rescheduling and deadline changing. (org-startup-options): Add in-buffer settings for logging changing schedule and deadline time stamps. (org-deadline, org-schedule): Check for existing date and arrange for logging if the user requests it. (org-add-log-note): Prepare proper note buffers for rescheduling and deadline changes. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-diary-entry-in-org-file) (org-agenda-add-entry-to-org-agenda-diary-file) (org-agenda-insert-diary-make-new-entry): New functions. (org-agenda-diary-entry): Call `org-agenda-diary-entry-in-org-file' when appropriate. * org.el (org-calendar-insert-diary-entry-key): New option. (org-agenda-diary-file): New option. ("calendar"): Install our insertion function in the calendar. * org-remember.el (org-datetree): Require. (org-remember-templates): Add new positioning option. (org-remember-reference-date): New variable. (org-remember-apply-template): Store the reference date in a local variable. (org-remember-handler): Implement date tree positioning of entries. * org-datetree.el: New file. * org-latex.el (org-export-latex-preprocess): Protect targets in verbatim emphasis. * org-html.el (org-export-as-html): Protect targets in verbatim emphasis. * org-docbook.el (org-export-as-docbook): Protect targets in verbatim emphasis. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-show-notification): Handle messages that contain a percent character. * org-remember.el (org-remember-apply-template): Turn of partial completion. * org-mobile.el (org-mobile-before-process-capture-hook): New hook. (org-mobile-pull): Run `org-mobile-before-process-capture-hook'. * org.el (org-indent-mode): Define variable already in org.el. (org-unfontify-region): Remove line-prefix and wrap-prefix properties only if org-indent-mode is active. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-print-icalendar-entries): Save match data around call to verify function. (org-print-icalendar-entries): Add a call to the verification function. * org.el (org-speedbar-set-agenda-restriction): Remove unnecessary save-restrivtion' form. 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-exp.el (org-export-format-source-code-or-example): restrict scope of preserve-indentp to the let binding. (org-src): require org-src, since org-src-preserve-indentation is used. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-timer.el (org-timer-set-timer): Set variables org-timer-timer[123] correctly. * org-mobile.el (org-mobile-files-alist): Make it work when `agenda-archives' is included in `org-agenda-text-search-extra-files'. (org-mobile-push): Restore agenda after mobile push. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-resolve-clocks-if-idle): Another fix to the way the amount of idle time is presented in the minibuffer. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-print-icalendar-entries): Use org-icalendar-verify-function only if non-nil. * org.el (org-refile): Refile to clock only if the prefix arg is 2. (org-sparse-tree): Fix docstring to be in line with prompt. (org-update-parent-todo-statistics): Call `org-after-todo-statistics-hook' on each level. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-remember.el (org-remember-apply-template): Make sure the buffer exists. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-tab-ind-state): New variable. (org-cycle-level): New function. (org-cycle-level-after-item/entry-creation): New option. (org-flag-subtree): New function. (org-hide-archived-subtrees): Call `org-flag-subtree'. (org-set-effort): Indexed access. * org-list.el (org-cycle-item-indentation): New function. * org.el (org-refile): Make prefix argument 2 refile to current clock. (org-priority): Interpret action `remove' as call to remove the priority cookie. * org-remember.el (org-remember-apply-template): Don't depend on buffer name being like file name. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-play-sound): Expand file in org-clock-sound, to allow ~ for home. * org-remember.el (org-remember-handler): Set text-before-node-creation even if this already looks like a node, because the string might be needed on non-org-mode target files. * org-agenda.el (org-agenda-open-link): Make this work in agenda clocktables. (org-agenda-switch-to): Follow a link at point if org-return-follows-link' is set and there is nothing else to do in this line. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview-xemacs.el: Add in changes from org-colview.el 2009-11-13 Dan Davison <davison@stats.ox.ac.uk> * org-exp-blocks.el: Modify split separator regexp to avoid empty strings. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview.el (org-columns-new): Make this work with the new operators. (org-columns-store-format): Make this work with the new operators. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-src-preserve-indentation): Document that this variable is also used during export. * org-exp.el (org-export-format-source-code-or-example): Preserve indentation if a block has a -i option, or if `org-src-preserve-indentation' is set. * org-exp-blocks.el (org-export-blocks-preprocess): Preserve indentation if a block has a -i option, or if `org-src-preserve-indentation' is set. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-mode-map): Define the new archiving keys. (org-speed-commands-default): Define an archiving key in the speed command map. (org-org-menu): Improve the menu structure concerning archiving. * org-archive.el (org-archive-subtree-default-with-confirmation): New command. * org-agenda.el (org-agenda-mode-map): Define the new archiving keys. (org-agenda-menu): Add the new archiving commands to the menu. (org-agenda-archive-default) (org-agenda-archive-default-with-confirmation): New commands. (org-agenda-archive, org-agenda-archive-to-archive-sibling): Just call `org-agenda-archive-with'. (org-agenda-archive-with): New function. * org-table.el (org-table-convert-region): Inert spaces around "|" to avoid line beginnings like "|-1" which will be mistaken as hlines. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-offer-links-in-entry): Return nil if there are no links, t if a link has been selected. (org-open-at-point): Open attachment directory when called in the headline and there are no links in the entry body. (org-speed-commands-default): Add "o" for open-at-point as a speed command. * org-attach.el (org-attach-reveal): Optional prefix arg IF-EXISTS, which avoids creating the attachment directory if it does not yet exist. * org-agenda.el (org-agenda, org-run-agenda-series): Evaluate MATCH. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el ("abbrev"): Work with abbrev tables only after they have been loaded. * org-list.el (org-list-send-list): Fix bug related to match data. * org-latex.el (org-export-latex-fontify): Apply verbatim emphasis. (org-export-latex-make-header): Insert \obeylines if line breaks should be preserved. * org-exp.el (org-export-protect-verbatim): Add an `org-verbatim-emph' property to such text. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-icalendar.el (org-icalendar-use-plain-timestamp): New option. (org-print-icalendar-entries): Skip entries where the timestamp is not a deadline and not scheduled, if the user requests that. * org-latex.el (org-export-latex-quotation-marks): Allow a bracket before an opening quote. * org-archive.el (org-archive-subtree): Keep archive after archiving something. * org-id.el (org-id-update-id-locations): Add archive files if that is required by `org-id-extra-files'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-src-window-setup): New option. (org-src-switch-to-buffer): New function. (org-edit-src-exit): Add optional argument CONTEXT and use it to restore window configuration. (org-edit-src-code, org-edit-src-continue, org-edit-src-exit): Call `org-src-switch-to-buffer'. * org.el (org-default-properties): Add STYLE property. (org-files-list): Use the function call to get the files. (org-additional-option-like-keywords): Add SETUPFILE to completion list. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-table.el (org-table-convert-region): Correctly interpret quoting in csv import. * org.el (org-icompleting-read): Make iswitchb completion work with lists and tables. * org-agenda.el (org-agenda-add-entry-text): Never add entry text while pushing the mobile agenda. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-clock-auto-clock-resolution): Now takes three values: nil, t and `when-no-clock-is-running'. (org-clock-in): Use `org-clock-auto-clock-resolution' to determine whether or not to resolve Org buffers on clock in. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-colview.el (org-format-time-period): Function to format times in fractional days for display. (org-columns-display-here): Add support for showing a calculated value in place of the property. (org-columns): Set `org-columns-time' to the current time so time difference calculations will work. (org-columns-time): Use to store the current time when column view is displayed, so all time differences will use the same reference point. (org-columns-compile-map): There is now an extra position in each entry specifying the function to use to calculate the displayed value for the non-calculated properties in the column, (org-columns-compute-all): Set `org-columns-time' to the current time so time difference calculations will work. (org-columns-compute): Handle column operators where the values used are calculated from the underlying property. (org-columns-number-to-string): Handle the 'age' column format (org-columns-string-to-number): Correct the function name (was org-column...). Add support for the 'age' column format. (org-columns-compile-format): Support the additional parameter in org-columns-compile-map. 2009-11-13 Bastien Guerry <bzg@altern.org> * org.el (org-mode-hook): Turn `org-mode-hook' into a customizable variable. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-has-been-used): New variable. (org-clock-in): Set `org-clock-has-been-used'. (org-clock-save): Save only if clock data has been used or created during this session. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-persist): New value, to store only the clock history. (org-clock-save): Don't save the clock if only the history should be stored. (org-clock-load): Turn off John Wiegley's auto resolving mechanism when restoring a saved clock. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-clock-display, org-clock-put-overlay): Use `org-time-clock-use-fractional'. * org.el (org-time-clocksum-use-fractional) (org-time-clocksum-fractional-format): Two new customizable variables which allow the user to select fractional times (1.25 instead of 1:25) in the `org-clock-display' report. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-ascii.el (org-export-ascii-table-keep-all-vertical-lines): New option. * org.el (org-tag-alist): Fix customization type. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-update-checksum-for-capture-file): Make sure the regexp search can fail without throwing an error. (org-mobile-apply): Save the inbox buffer after removing successfully applied changes. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-clock.el (org-resolve-clocks-if-idle): Fix to the way idle time is reported after the user comes back (but before they resolve time). * org.el (org-get-repeat): Change so that this function can be called with either `org-scheduled-string' or `org-deadline-string'. * org-clock.el (org-clock-auto-clock-resolution): Renamed `org-clock-disable-clock-resolution', since negatives don't sound good in customization variables. (org-clock-in): Don't use the auto-resolution logic if the user is clocking into a different task while an active clock is running. This then allows the default behavior of clocking out of the open task and then into the new task. * org.el (org-modules): Made this variable more consistent, since it was referring to Org, OrgMode and Org-mode, whereas the docs for the variable always refer to Org-mode. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org.el (org-repeat-re): The changed org-repeat-re no longer matched simple +2d type repeaters. Fix it so it does. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-latex.el (org-export-latex-preprocess): Protect the vspace macro in the VERSE environment. 2009-11-13 John Wiegley <jwiegley@gmail.com> * org-habit.el (org-habit-get-priority): A new function that determines the relative priority of a habit, based on how long past its scheduled date it is, and how near the deadline is. * org-agenda.el (org-agenda-get-scheduled): Set habit priority using `org-habit-get-priority'. * org-habit.el (org-habit-build-graph): Start displaying colors from the first scheduled date, if that date is earlier than the first completion date. * org-habit.el: Changed all "color" variables to faces, and made them appropriate for light and dark backgrounds. * org-habit.el (org-habit-duration-to-days): Made this function more general. (org-habit-parse-todo): Parse the new ".+N/N" style repeater. * org-agenda.el (org-agenda-get-deadlines): Removed all mention of habits, since they don't use DEADLINE anymore. * org.el (org-repeat-re, org-display-custom-time) (org-timestamp-change): Extended to support the new ".+N/N" syntax, used for habits. * org-clock.el (org-clock-resolve-clock): Fixed an incorrect variable reference. * org-agenda.el (org-agenda-set-mode-name): Show Habit in the modeline when habits are being displayed (if that module is being loaded). 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org-clock.el (org-x11-idle-seconds): Add a method to get the X11 idle time using the xscreensaver extension. (org-user-idle-seconds): Use X11 idle time if available. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-next-line): New command. (org-agenda-previous-line): New commands. (org-agenda-show-and-scroll-up, org-agenda-show-scroll-down): New commands. (org-agenda-follow-mode): Do the follow immediately if the mode is turned on here. (previous-line, next-line): Replace keys with the corresponding org functions. (org-agenda-mode-map): Bind backspace and delete to the scrolling command. * org.el (org-icompleting-read): Turn off partial completion mode for the duration of this completion round. * org-latex.el (org-export-latex-fontify-headline): Protect TeX macros in author lines and similar stuff. * org.el (org-file-tags): Fix docstring. (org-get-buffer-tags): Add the #+FILETAGS tags. ("ecb"): Maks ecb show context after jumping into an Org file. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-agenda.el (org-finalize-agenda): Draw habit consistency graphs after everything else in the buffer has been setup. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-apply): Count success and failure. * org.el (org-indent-line-function): Fix regexp replace problem. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-clock.el (org-clock-disable-clock-resolution): New customization variable that disable automatic clock resolution on clock in. (org-clock-in): If `org-clock-disable-clock-resolution' is set, do not automatically resolve anything. This is does not affect idle-time resolution, however, if `org-clock-idle-time' is set. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-habit.el: New file, which implements code to build a "habit consistency graph". * org-agenda.el (org-agenda-get-deadlines) (org-agenda-get-scheduled): Display consistency graphs when outputting habits into the agenda. The graphs are always relative to the current time. (org-format-agenda-item): Added new parameter `habitp', which indicates whether we are formatting a habit or not. Do not display "extra" leading information if habitp is true. * org.el (org-repeat-re): Improved regexp to include .+ and ++ leaders for repeat strings. (org-get-repeat): Now takes a string parameter `tagline', so the caller can obtain the SCHEDULED repeat, or the DEADLINE repeat. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-agenda.el (org-agenda-auto-exclude-function): New customization variable for allowing the user to create an "auto exclusion" filter for doing context-aware auto tag filtering. (org-agenda-filter-by-tag): Changes to support the use of `org-agenda-auto-exclude-function'. See the new manual addition,. 2009-11-13 John Wiegley <johnw@newartisans.com> * org.el (org-files-list): Don't attempt to return a file name for Org buffers which have no associated file. * org-agenda.el (org-agenda-do-action): Fixed a typo. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-locate-entry): Interpret files relative to org-directory. (org-mobile-inbox-for-pull): Document the best location for this file. (org-mobile-check-setup): Verify `org-directory'. (org-mobile-create-index-file): Sort the files to be listed in index.org. 2009-11-13 James TD Smith <ahktenzero@mohorovi.cc> * org.el (org-fast-tag-selection): Add a way to display a description for a tag group. This is done by adding a string to either the startgroup or endgroup cell. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-clock.el (org-clock-resolve, org-resolve-clocks) (org-emacs-idle-seconds): Use `org-float-time' instead of `time-to-seconds' 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-sorting-strategy): Fix customization type. * org.el (org-pre-cycle-hook): Document that `empty' can also be the value of ARG when doing local cycling. 2009-11-13 John Wiegley <johnw@newartisans.com> * org-clock.el (org-clock-resolve-clock): If keeping or subtracting time results in a clock out at a time in the past, and if the resolution occurred due to idleness or invoking `M-x org-resolve-clocks', remember that past moment in time. On the next clock in, the user will be prompted to see if they want to back-date their new clock to then. (org-clock-resolve): Do not jump the user to the location of a dangling clock if the resolution is occuring due to an idle timeout. In that case there is typically only one dangling clock, the active one, and there is no value gained by shuffling their windows around to show it to them. Being prompted to resolve an idle clock should be as inobtrusive as possible. (org-resolve-clocks-if-idle): New function that resolves only the currently active clock if the user has exceeded the time returned by `org-user-idle-seconds', based on the value of `org-clock-idle-time'. (org-clock-in): If, after resolving clocks, (org-clock-out): Cancel the `org-clock-idle-timer' on clock out. * org-clock.el (org-clock-resolve-clock): New function that resolves a clock to a specific time, closing or resuming as need be, and possibly even starting a new clock. (org-clock-resolve): New function used by `org-resolve-clocks' that sets up for the call to `org-clock-resolve-clock'. It determines the time to resolve to based on a single-character selection from the user to either keep time, subtract away time or cancel the clock. (org-resolve-clocks): New user command which resolves dangling clocks -- that is, open but not active -- anywhere in the file list returned by `org-files-list'. (org-clock-in): Automatically resolve dangling clocks whenever a user clocks in. (org-clock-cancel): If the user cancels the solely clock in a LOGBOOK, remove the empty drawer. * org-clock.el (org-clock-idle-time): New user customizable option for detecting whether the user has left a clock idle. Note: it is only used in this commit to test whether it's worthwhile to check OS X to get the Mac user's current idle time. If the Emacs idle time is less than the value, the user hasn't been away long enough to be worth checking (a more expensive test than just getting Emacs idle time). (org-user-idle-seconds, org-mac-idle-seconds) (org-emacs-idle-seconds): This three functions, in conjunction with the user customization variable `org-clock-idle-time', return the number of seconds (as a floating point) that the user has been away from their Emacs (or, if running on OS X, their computer). * org-clock.el (org-find-open-clocks): New function that returns a list of all open clocks in the given FILE. Note that each clock it returns is a cons cell of the format (MARKER . START-TIME). This "clock" value is used by several of the new clock module utility functions. (org-is-active-clock): New inline function which tests whether the given clock value is the same as the currently active clock. Returns non-nil if this is the case. (org-with-clock-position): New macro that evaluates FORMS with point in the buffer and at the position of the given clock. Changes to the current clock are global. (org-with-clock): New macro that evaluates FORMS with point in the buffer and at the position of the given clock. However, changes to the current clock are local and have no effect on the user's active clock. This allows, for example, far any clock to be cancelled without cancelling the active clock. (org-clock-clock-in): New inline function that switches the active clock to the given clock. If either the argument RESUME, or the global `org-clock-in-resume', are non-nil, it will resume a clock that was previously left open. (org-clock-clock-out): New inline function that clocks out the given clock value without affecting the currently active clock. (org-clock-clock-cancel): New inline function that cancels the given clock value without affecting the currently active clock. * org-clock.el (org-clock-in): Before creating `org-clock-mode-line-timer', check to make sure an older timer is not currently running. (org-clock-out): Accept new third parameter `at-time', which permits a clock to be clocked out at a specific time. Note that no attempt is made to verify that the clock out time is later than the clock in time. * org.el (org-files-list): New utility function for returning a list of all open org-mode buffers, plus all files used to build the agenda buffer. Note that not all the files will necessarily be visited by a buffer at time of call. (org-entry-beginning-position): Like the function `line-beginning-position', this inline function returns the beginning position of the current heading/entry. (org-entry-end-position): Like the function `line-end-position', this inline function returns the end position of the current heading/entry. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-list): Mark the all-todo items line as a header line. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-inlinetask-remove-END-maybe): Declare function. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-agenda.el (org-agenda-filter-make-matcher): Allow to filter entries that have no tags. (org-agenda-search-view): New customize group. (org-agenda-search-view-search-words-only): New option. (org-search-view): Implement substring search. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-outline-level): Add doc string. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-inlinetask.el (org-inlinetask-export): Re-introduce variable. (org-inlinetask-export-handler): Only export inline task if the user option calls for it. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-exp.el (org-export-handle-export-tags): Remove inlinetask END if present. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-latex.el (org-export-latex-tables): Don't format in protected regions. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-src.el (org-edit-src-code) (org-edit-src-find-region-and-lang, org-edit-src-exit): Handle macro editing. * org-agenda.el (org-prefix-category-max-length): New variable. (org-format-agenda-item): Use `org-prefix-category-max-length'. (org-compile-prefix-format): Set `org-prefix-category-max-length'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-mobile.el (org-mobile-create-index-file): Improve the listing of tags and todo keywords. * org-latex.el (org-export-latex-format-image): New function. (org-export-latex-links): Use `org-export-latex-format-image'. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org-inlinetask.el (org-inlinetask-get-current-indentation) (org-inlinetask-remove-terminator): New functions. (org-inlinetask-export-handler): Terminate the description list. * org-exp.el (org-export-select-backend-specific-text): Remove the region markers. * org-inlinetask.el (org-inlinetask-export-handler): fix bug for tasks without content. * org-clock.el: Make sure the clock-in target position does not move to a different node by widening the buffer. * org-html.el (org-export-html-format-image): Wrap image into figure div only when there is a caption. * org-archive.el (org-archive-mark-done): Change default value to nil. 2009-11-13 Carsten Dominik <carsten.dominik@gmail.com> * org.el (org-context): Call `bobp', not `eobp'. * org-clock.el (org-clock-cancel): Remove quotes from marker variables. * org.el (org-read-date-prefer-future): New allowed value `time'. (org-read-date-analyze): Shift day to tomorrow depending on time entered and value of `org-read-date-prefer-future'.
author Carsten Dominik <dominik@science.uva.nl>
date Fri, 13 Nov 2009 08:37:55 +0000
parents bb413968898a
children 1d1d5d9bd884
line wrap: on
line source

/* Font back-end driver for the NeXT/Open/GNUstep and MacOSX window system.
   See font.h
   Copyright (C) 2006, 2007, 2008, 2009 Free Software Foundation, Inc.

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/>.

Author: Adrian Robert (arobert@cogsci.ucsd.edu)
*/

/* This should be the first include, as it may set up #defines affecting
   interpretation of even the system includes. */
#include "config.h"
#include <setjmp.h>

#include "lisp.h"
#include "dispextern.h"
#include "composite.h"
#include "blockinput.h"
#include "charset.h"
#include "frame.h"
#include "window.h"
#include "fontset.h"
#include "nsterm.h"
#include "frame.h"
#include "character.h"
#include "font.h"

/* TODO: Drop once we can assume gnustep-gui 0.17.1. */
#ifdef NS_IMPL_GNUSTEP
#import <AppKit/NSFontDescriptor.h>
#endif

#define NSFONT_TRACE 0

extern Lisp_Object Qns;
extern Lisp_Object Qnormal, Qbold, Qitalic, Qcondensed, Qexpanded;
static Lisp_Object Vns_reg_to_script;
static Lisp_Object Qapple, Qroman, Qmedium;
extern Lisp_Object Qappend;
extern int ns_antialias_text;
extern float ns_antialias_threshold;
extern int ns_tmp_flags;
extern struct nsfont_info *ns_tmp_font;

/* font glyph and metrics caching functions, implemented at end */
static void ns_uni_to_glyphs (struct nsfont_info *font_info,
                              unsigned char block);
static void ns_glyph_metrics (struct nsfont_info *font_info,
                              unsigned char block);


/* ==========================================================================

    Utilities

   ========================================================================== */


/* Replace spaces w/another character so emacs core font parsing routines
   aren't thrown off. */
static void
ns_escape_name (char *name)
{
  int i =0, len =strlen (name);
  for ( ; i<len; i++)
    if (name[i] == ' ')
      name[i] = '_';
}


/* Reconstruct spaces in a font family name passed through emacs. */
static void
ns_unescape_name (char *name)
{
  int i =0, len =strlen (name);
  for ( ; i<len; i++)
    if (name[i] == '_')
      name[i] = ' ';
}


/* Extract family name from a font spec. */
static NSString *
ns_get_family (Lisp_Object font_spec)
{
  Lisp_Object tem = AREF (font_spec, FONT_FAMILY_INDEX);
  if (NILP (tem))
      return nil;
  else
    {
      char *tmp = strdup (SDATA (SYMBOL_NAME (tem)));
      NSString *family;
      ns_unescape_name (tmp);
      family = [NSString stringWithUTF8String: tmp];
      free (tmp);
      return family;
    }
}


/* Return 0 if attr not set, else value (which might also be 0).
   On Leopard 0 gets returned even on descriptors where the attribute
   was never set, so there's no way to distinguish between unspecified
   and set to not have.  Callers should assume 0 means unspecified. */
static float
ns_attribute_fvalue (NSFontDescriptor *fdesc, NSString *trait)
{
    NSDictionary *tdict = [fdesc objectForKey: NSFontTraitsAttribute];
    NSNumber *val = [tdict objectForKey: trait];
    return val == nil ? 0.0 : [val floatValue];
}


/* Converts FONT_WEIGHT, FONT_SLANT, FONT_WIDTH, plus family and script/lang
   to NSFont descriptor.  Information under extra only needed for matching. */
#define STYLE_REF 100
static NSFontDescriptor
*ns_spec_to_descriptor(Lisp_Object font_spec)
{
    NSFontDescriptor *fdesc;
    NSMutableDictionary *fdAttrs = [NSMutableDictionary new];
    NSMutableDictionary *tdict = [NSMutableDictionary new];
    NSString *family = ns_get_family (font_spec);
    float n;

    /* add each attr in font_spec to fdAttrs.. */
    n = min (FONT_WEIGHT_NUMERIC (font_spec), 200);
    if (n != -1 && n != STYLE_REF)
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontWeightTrait];
    n = min (FONT_SLANT_NUMERIC (font_spec), 200);
    if (n != -1 && n != STYLE_REF)
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontSlantTrait];
    n = min (FONT_WIDTH_NUMERIC (font_spec), 200);
    if (n > -1 && (n > STYLE_REF + 10 || n < STYLE_REF - 10))
	[tdict setObject: [NSNumber numberWithFloat: (n - 100.0) / 100.0]
		  forKey: NSFontWidthTrait];
    if ([tdict count] > 0)
	[fdAttrs setObject: tdict forKey: NSFontTraitsAttribute];

    fdesc = [NSFontDescriptor fontDescriptorWithFontAttributes: fdAttrs];
    if (family != nil)
	fdesc = [fdesc fontDescriptorWithFamily: family];
    return fdesc;
}


/* Converts NSFont descriptor to FONT_WEIGHT, FONT_SLANT, FONT_WIDTH, etc.. */
static Lisp_Object
ns_descriptor_to_entity (NSFontDescriptor *desc, Lisp_Object extra, char *style)
{
    Lisp_Object font_entity = font_make_entity ();
    /*   NSString *psName = [desc postscriptName]; */
    NSString *family = [desc objectForKey: NSFontFamilyAttribute];
    unsigned int traits = [desc symbolicTraits];
    char *escapedFamily;

    /* Shouldn't happen, but on Tiger fallback desc gets name but no family. */
    if (family == nil)
      family = [desc objectForKey: NSFontNameAttribute];
    if (family == nil)
      family = [[NSFont userFixedPitchFontOfSize: 0] familyName];

    escapedFamily = strdup ([family UTF8String]);
    ns_escape_name (escapedFamily);

    ASET (font_entity, FONT_TYPE_INDEX, Qns);
    ASET (font_entity, FONT_FOUNDRY_INDEX, Qapple);
    ASET (font_entity, FONT_FAMILY_INDEX, intern (escapedFamily));
    ASET (font_entity, FONT_ADSTYLE_INDEX, style ? intern (style) : Qnil);
    ASET (font_entity, FONT_REGISTRY_INDEX, Qiso10646_1);

    FONT_SET_STYLE (font_entity, FONT_WEIGHT_INDEX,
		    traits & NSFontBoldTrait ? Qbold : Qmedium);
/*    FONT_SET_STYLE (font_entity, FONT_WEIGHT_INDEX,
		    make_number (100 + 100
			* ns_attribute_fvalue (desc, NSFontWeightTrait)));*/
    FONT_SET_STYLE (font_entity, FONT_SLANT_INDEX,
		    traits & NSFontItalicTrait ? Qitalic : Qnormal);
/*    FONT_SET_STYLE (font_entity, FONT_SLANT_INDEX,
		    make_number (100 + 100
			 * ns_attribute_fvalue (desc, NSFontSlantTrait)));*/
    FONT_SET_STYLE (font_entity, FONT_WIDTH_INDEX,
		    traits & NSFontCondensedTrait ? Qcondensed :
		    traits & NSFontExpandedTrait ? Qexpanded : Qnormal);
/*    FONT_SET_STYLE (font_entity, FONT_WIDTH_INDEX,
		    make_number (100 + 100
			 * ns_attribute_fvalue (desc, NSFontWidthTrait)));*/

    ASET (font_entity, FONT_SIZE_INDEX, make_number (0));
    ASET (font_entity, FONT_AVGWIDTH_INDEX, make_number (0));
    ASET (font_entity, FONT_SPACING_INDEX,
	  make_number([desc symbolicTraits] & NSFontMonoSpaceTrait
	      ? FONT_SPACING_MONO : FONT_SPACING_PROPORTIONAL));

    ASET (font_entity, FONT_EXTRA_INDEX, extra);
    ASET (font_entity, FONT_OBJLIST_INDEX, Qnil);

    if (NSFONT_TRACE)
      {
	fprintf (stderr, "created font_entity:\n    ");
	debug_print (font_entity);
      }

    free (escapedFamily);
    return font_entity;
}


/* Default font entity. */
static Lisp_Object
ns_fallback_entity ()
{
  return ns_descriptor_to_entity ([[NSFont userFixedPitchFontOfSize: 0]
      fontDescriptor], Qnil, NULL);
}


/* Utility: get width of a char c in screen font sfont */
static float
ns_char_width (NSFont *sfont, int c)
{
    float w;
    NSString *cstr = [NSString stringWithFormat: @"%c", c];
#ifdef NS_IMPL_COCOA
    NSGlyph glyph = [sfont glyphWithName: cstr];
    if (glyph)
      {
	float w = [sfont advancementForGlyph: glyph].width;
	if (w >= 1.5)
	    return w;
      }
#endif
    {
      NSDictionary *attrsDictionary =
        [NSDictionary dictionaryWithObject: sfont forKey: NSFontAttributeName];
      w = [cstr sizeWithAttributes: attrsDictionary].width;
    }
    return max (w, 2.0);
}


/* Return whether set1 covers set2 to a reasonable extent given by pct.
   We check, out of each 16 unicode char range containing chars in set2,
   whether at least one character is present in set1.
   This must be true for pct of the pairs to consider it covering. */
static BOOL
ns_charset_covers(NSCharacterSet *set1, NSCharacterSet *set2, float pct)
{
    const unsigned short *bytes1 = [[set1 bitmapRepresentation] bytes];
    const unsigned short *bytes2 = [[set2 bitmapRepresentation] bytes];
    int i, off = 0, tot = 0;

    for (i=0; i<4096; i++, bytes1++, bytes2++)
	if (*bytes2)
	  {
	    tot++;
	    if (*bytes1 == 0)  // *bytes1 & *bytes2 != *bytes2
		off++;
	  }
//fprintf(stderr, "off = %d\ttot = %d\n", off,tot);
    return (float)off / tot < 1.0 - pct;
}


/* Convert :lang property to a script.  Use of :lang property by font backend
   seems to be limited for now (2009/05) to ja, zh, and ko. */
static NSString
*ns_lang_to_script (Lisp_Object lang)
{
    if (!strcmp (SDATA (SYMBOL_NAME (lang)), "ja"))
	return @"han";
    /* NOTE: ja given for any hanzi that's also a kanji, but Chinese fonts
             have more characters. */
    else if (!strcmp (SDATA (SYMBOL_NAME (lang)), "zh"))
	return @"han";
    else if (!strcmp (SDATA (SYMBOL_NAME (lang)), "ko"))
	return @"hangul";
    else
	return @"";
}


/* Convert OTF 4-letter script code to emacs script name.  (Why can't
   everyone just use some standard unicode names for these?) */
static NSString
*ns_otf_to_script (Lisp_Object otf)
{
    Lisp_Object script = assq_no_quit (XCAR (otf), Votf_script_alist);
    return CONSP (script)
	? [NSString stringWithUTF8String: SDATA (SYMBOL_NAME XCDR ((script)))]
	: @"";
}


/* Convert a font registry, such as  */
static NSString
*ns_registry_to_script (char *reg)
{
    Lisp_Object script, r, rts = Vns_reg_to_script;
    while CONSP (rts)
      {
        r = XCAR (XCAR (rts));
        if (!strncmp(SDATA(r), reg, strlen(SDATA(r))))
          {
            script = XCDR (XCAR (rts));
            return [NSString stringWithUTF8String: SDATA (SYMBOL_NAME (script))];
          }
        rts = XCDR (rts);
      }
    return  @"";
}


/* Searches the :script, :lang, and :otf extra-bundle properties of the spec,
   plus registry regular property, for something that can be mapped to a
   unicode script.  Empty string returned if no script spec found. */
static NSString
*ns_get_req_script (Lisp_Object font_spec)
{
    Lisp_Object reg = AREF (font_spec, FONT_REGISTRY_INDEX);
    Lisp_Object extra = AREF (font_spec, FONT_EXTRA_INDEX);

    /* The extra-bundle properties have priority. */
    for ( ; CONSP (extra); extra = XCDR (extra))
      {
	Lisp_Object tmp = XCAR (extra);
	if (CONSP (tmp))
	  {
	    Lisp_Object key = XCAR (tmp), val = XCDR (tmp);
	    if (EQ (key, QCscript) && SYMBOLP (val))
		return [NSString stringWithUTF8String:
		            SDATA (SYMBOL_NAME (val))];
	    if (EQ (key, QClang) && SYMBOLP (val))
		return ns_lang_to_script (val);
	    if (EQ (key, QCotf) && CONSP (val) && SYMBOLP (XCAR (val)))
		return ns_otf_to_script (val);
	  }
      }

    /* If we get here, check the charset portion of the registry. */
    if (! NILP (reg))
      {
        /* XXX: iso10646 is passed in for non-ascii latin-1 characters
           (which causes box rendering if we don't treat it like iso8858-1)
           but also for ascii (which causes unnecessary font substitution). */
#if 0
        if (EQ (reg, Qiso10646_1))
          reg = Qiso8859_1;
#endif
        return ns_registry_to_script (SDATA (SYMBOL_NAME (reg)));
      }

    return @"";
}


/* This small function is static in fontset.c.  If it can be made public for
   all ports, remove this, but otherwise it doesn't seem worth the ifdefs. */
static void
accumulate_script_ranges (Lisp_Object arg, Lisp_Object range, Lisp_Object val)
{
    if (EQ (XCAR (arg), val))
      {
	if (CONSP (range))
	  XSETCDR (arg, Fcons (Fcons (XCAR (range), XCDR (range)), XCDR (arg)));
	else
	  XSETCDR (arg, Fcons (Fcons (range, range), XCDR (arg)));
      }
}


/* Use the unicode range information in Vchar_script_table to convert a script
   name into an NSCharacterSet. */
static NSCharacterSet
*ns_script_to_charset (NSString *scriptName)
{
    NSMutableCharacterSet *charset = [NSMutableCharacterSet new];
    Lisp_Object script = intern ([scriptName UTF8String]);
    Lisp_Object script_list = XCHAR_TABLE (Vchar_script_table)->extras[0];

    if (! NILP (Fmemq (script, script_list)))
      {
	Lisp_Object ranges, range_list;

	ranges = Fcons (script, Qnil);
	map_char_table (accumulate_script_ranges, Qnil, Vchar_script_table,
			ranges);
	range_list = Fnreverse (XCDR (ranges));
	if (! NILP (range_list))
	  {
	    for (; CONSP (range_list); range_list = XCDR (range_list))
	      {
		int start = XINT (XCAR (XCAR (range_list)));
		int end = XINT (XCDR (XCAR (range_list)));
		if (NSFONT_TRACE)
		    debug_print (XCAR (range_list));
		if (end < 0x10000)
		    [charset addCharactersInRange:
			NSMakeRange (start, end-start)];
	      }
	  }
      }
    return charset;
}


/* Return an array of font families containing characters for the given
   script, for the given coverage criterion, including at least LastResort.
   Results are cached by script for faster access.
   If none are found, we reduce the percentage and try again, until 5%.
   This provides a font with at least some characters if such can be found.
   We don't use isSupersetOfSet: because (a) it doesn't work on Tiger, and
   (b) need approximate match as fonts covering full unicode ranges are rare. */
static NSSet
*ns_get_covering_families (NSString *script, float pct)
{
    static NSMutableDictionary *scriptToFamilies = nil;
    NSMutableSet *families;

    if (NSFONT_TRACE)
	NSLog(@"Request covering families for script: '%@'", script);

    if (scriptToFamilies == nil)
        scriptToFamilies = [[NSMutableDictionary alloc] init];

    if ((families = [scriptToFamilies objectForKey: script]) == nil)
      {
	NSFontManager *fontMgr = [NSFontManager sharedFontManager];
	NSArray *allFamilies = [fontMgr availableFontFamilies];

	if ([script length] == 0)
	    families = [NSMutableSet setWithArray: allFamilies];
	else
	  {
	    NSCharacterSet *charset = ns_script_to_charset (script);
	    NSString *family;
	    families = [NSMutableSet setWithCapacity: 10];
	    while (1)
	      {
		NSEnumerator *allFamiliesEnum = [allFamilies objectEnumerator];
		while (family = [allFamiliesEnum nextObject])
		  {
		    NSCharacterSet *fset = [[fontMgr fontWithFamily: family
                        traits: 0 weight: 5 size: 12.0]	coveredCharacterSet];
                    /* Some fonts on OS X, maybe many on GNUstep, return nil. */
                    if (fset == nil)
                      fset = [NSCharacterSet characterSetWithRange:
                                               NSMakeRange (0, 127)];
		    if (ns_charset_covers(fset, charset, pct))
			[families addObject: family];
		  }
                pct -= 0.2;
		if ([families count] > 0 || pct < 0.05)
		    break;
	      }
	  }
#ifdef NS_IMPL_COCOA
	if ([families count] == 0)
	    [families addObject: @"LastResort"];
#endif
	[scriptToFamilies setObject: families forKey: script];
      }

    if (NSFONT_TRACE)
	NSLog(@"    returning %d families", [families count]);
    return families;
}


/* Implementation for list() and match().  List() can return nil, match()
must return something.  Strategy is to drop family name from attribute
matching set for match. */
static Lisp_Object
ns_findfonts (Lisp_Object font_spec, BOOL isMatch)
{
    Lisp_Object tem, list = Qnil;
    NSFontDescriptor *fdesc, *desc;
    NSMutableSet *fkeys;
    NSArray *matchingDescs;
    NSEnumerator *dEnum;
    NSString *family;
    NSSet *cFamilies;
    BOOL foundItal = NO;

    if (NSFONT_TRACE)
      {
	fprintf (stderr, "nsfont: %s for fontspec:\n    ",
		 (isMatch ? "match" : "list"));
	debug_print (font_spec);
      }

    cFamilies = ns_get_covering_families (ns_get_req_script (font_spec), 0.90);

    fdesc = ns_spec_to_descriptor (font_spec);
    fkeys = [NSMutableSet setWithArray: [[fdesc fontAttributes] allKeys]];
    if (isMatch)
	[fkeys removeObject: NSFontFamilyAttribute];

    matchingDescs = [fdesc matchingFontDescriptorsWithMandatoryKeys: fkeys];
    if (NSFONT_TRACE)
	NSLog(@"Got desc %@ and found %d matching fonts from it: ", fdesc,
	      [matchingDescs count]);

    for (dEnum = [matchingDescs objectEnumerator]; desc = [dEnum nextObject]; )
      {
	if (![cFamilies containsObject:
	         [desc objectForKey: NSFontFamilyAttribute]])
	    continue;
        tem = ns_descriptor_to_entity (desc,
					 AREF (font_spec, FONT_EXTRA_INDEX),
                                       NULL);
        if (isMatch)
          return tem;
	list = Fcons (tem, list);
	if (fabs (ns_attribute_fvalue (desc, NSFontSlantTrait)) > 0.05)
	    foundItal = YES;
      }

    /* Add synthItal member if needed. */
    family = [fdesc objectForKey: NSFontFamilyAttribute];
    if (family != nil && !foundItal && XINT (Flength (list)) > 0)
      {
	NSFontDescriptor *sDesc = [[[NSFontDescriptor new]
	    fontDescriptorWithSymbolicTraits: NSFontItalicTrait]
	    fontDescriptorWithFamily: family];
	list = Fcons (ns_descriptor_to_entity (sDesc,
					 AREF (font_spec, FONT_EXTRA_INDEX),
					 "synthItal"), list);
      }

    /* Return something if was a match and nothing found. */
    if (isMatch)
      return ns_fallback_entity ();

    if (NSFONT_TRACE)
	fprintf (stderr, "    Returning %ld entities.\n",
                 (long) XINT (Flength (list)));

    return list;
}



/* ==========================================================================

    Font driver implementation

   ========================================================================== */


static Lisp_Object nsfont_get_cache (FRAME_PTR frame);
static Lisp_Object nsfont_list (Lisp_Object frame, Lisp_Object font_spec);
static Lisp_Object nsfont_match (Lisp_Object frame, Lisp_Object font_spec);
static Lisp_Object nsfont_list_family (Lisp_Object frame);
static Lisp_Object nsfont_open (FRAME_PTR f, Lisp_Object font_entity,
                                 int pixel_size);
static void nsfont_close (FRAME_PTR f, struct font *font);
static int nsfont_has_char (Lisp_Object entity, int c);
static unsigned int nsfont_encode_char (struct font *font, int c);
static int nsfont_text_extents (struct font *font, unsigned int *code,
                                int nglyphs, struct font_metrics *metrics);
static int nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
                        int with_background);

struct font_driver nsfont_driver =
  {
    0,				/* Qns */
    1,				/* case sensitive */
    nsfont_get_cache,
    nsfont_list,
    nsfont_match,
    nsfont_list_family,
    NULL,			/*free_entity */
    nsfont_open,
    nsfont_close,
    NULL,			/* prepare_face */
    NULL,			/* done_face */
    nsfont_has_char,
    nsfont_encode_char,
    nsfont_text_extents,
    nsfont_draw,
    /* excluded: get_bitmap, free_bitmap, get_outline, free_outline,
                 anchor_point, otf_capability, otf_driver,
      		 start_for_frame, end_for_frame, shape */
  };


/* Return a cache of font-entities on FRAME.  The cache must be a
   cons whose cdr part is the actual cache area.  */
static Lisp_Object
nsfont_get_cache (FRAME_PTR frame)
{
  Display_Info *dpyinfo = FRAME_NS_DISPLAY_INFO (frame);
  return (dpyinfo->name_list_element);
}


/* List fonts exactly matching with FONT_SPEC on FRAME.  The value is a
   **list** of font-entities.  This and match () are sole APIs that allocate
   font-entities.  Properties to be considered (2009/05/19) are:
   regular: foundry, family, adstyle, registry
   extended: script, lang, otf
  "Extended" properties are not part of the vector but get stored as
   lisp properties under FONT_EXTRA_INDEX.

   The returned entities should have type set (to 'ns), plus the following:
   foundry, family, adstyle, registry,
   weight, slant, width, size (0 if scalable),
   dpi, spacing, avgwidth (0 if scalable)  */
static Lisp_Object
nsfont_list (Lisp_Object frame, Lisp_Object font_spec)
{
    return ns_findfonts (font_spec, NO);
}


/* Return a font entity most closely maching with FONT_SPEC on
   FRAME.  The closeness is determined by the font backend, thus
   `face-font-selection-order' is ignored here.
   Properties to be considered are same as for list(). */
static Lisp_Object
nsfont_match (Lisp_Object frame, Lisp_Object font_spec)
{
    return ns_findfonts(font_spec, YES);
}


/* List available families.  The value is a list of family names
   (symbols). */
static Lisp_Object
nsfont_list_family (Lisp_Object frame)
{
  Lisp_Object list = Qnil;
  NSEnumerator *families =
    [[[NSFontManager sharedFontManager] availableFontFamilies]
      objectEnumerator];
  NSString *family;
  while (family = [families nextObject])
      list = Fcons (intern ([family UTF8String]), list);
  /* FIXME: escape the name? */

  if (NSFONT_TRACE)
    fprintf (stderr, "nsfont: list families returning %ld entries\n",
            (long) XINT (Flength (list)));

  return list;
}


/* Open a font specified by FONT_ENTITY on frame F.  If the font is
   scalable, open it with PIXEL_SIZE.  */
static Lisp_Object
nsfont_open (FRAME_PTR f, Lisp_Object font_entity, int pixel_size)
{
  BOOL synthItal;
  unsigned int traits = 0;
  struct nsfont_info *font_info;
  struct font *font;
  NSFontDescriptor *fontDesc = ns_spec_to_descriptor (font_entity);
  NSFontManager *fontMgr = [NSFontManager sharedFontManager];
  NSString *family;
  NSFont *nsfont, *sfont;
  Lisp_Object tem;
  NSRect brect;
  Lisp_Object font_object;
  int i;
  int fixLeopardBug;
  static NSMutableDictionary *fontCache = nil;
  NSNumber *cached;

  /* 2008/03/08: The same font may end up being requested for different
     entities, due to small differences in numeric values or other issues,
     or for different copies of the same entity.  Therefore we cache to
     avoid creating multiple struct font objects (with metrics cache, etc.)
     for the same NSFont object. */
  if (fontCache == nil)
    fontCache = [[NSMutableDictionary alloc] init];

  if (NSFONT_TRACE)
    {
      fprintf (stderr, "nsfont: open size %d of fontentity:\n    ", pixel_size);
      debug_print (font_entity);
    }

  if (pixel_size <= 0)
    {
      /* try to get it out of frame params */
        Lisp_Object tem = get_frame_param (f, Qfontsize);
        pixel_size = NILP (tem) ? 0 : XFASTINT (tem);
    }

  tem = AREF (font_entity, FONT_ADSTYLE_INDEX);
  synthItal = !NILP (tem) && !strncmp ("synthItal", SDATA (SYMBOL_NAME (tem)),
                                       9);
  family = ns_get_family (font_entity);
  if (family == nil)
    family = [[NSFont userFixedPitchFontOfSize: 0] familyName];
  /* Should be > 0.23 as some font descriptors (e.g. Terminus) set to that
     when setting family in ns_spec_to_descriptor(). */
  if (ns_attribute_fvalue (fontDesc, NSFontWeightTrait) > 0.50)
      traits |= NSBoldFontMask;
  if (fabs (ns_attribute_fvalue (fontDesc, NSFontSlantTrait) > 0.05))
      traits |= NSItalicFontMask;

  /* see http://cocoadev.com/forums/comments.php?DiscussionID=74 */
  fixLeopardBug = traits & NSBoldFontMask ? 10 : 5;
  nsfont = [fontMgr fontWithFamily: family
                            traits: traits weight: fixLeopardBug
			      size: pixel_size];
  /* if didn't find, try synthetic italic */
  if (nsfont == nil && synthItal)
    {
      nsfont = [fontMgr fontWithFamily: family
                                traits: traits & ~NSItalicFontMask
                                weight: fixLeopardBug size: pixel_size];
    }
#ifdef NS_IMPL_COCOA
  /* LastResort not really a family */
  if (nsfont == nil && [@"LastResort" isEqualToString: family])
      nsfont = [NSFont fontWithName: @"LastResort" size: pixel_size];
#endif

  if (nsfont == nil)
    {
      message_with_string ("*** Warning: font in family '%s' not found",
                          build_string ([family UTF8String]), 1);
      nsfont = [NSFont userFixedPitchFontOfSize: pixel_size];
    }

  if (NSFONT_TRACE)
    NSLog (@"%@\n", nsfont);

  /* Check the cache */
  cached = [fontCache objectForKey: nsfont];
  if (cached != nil && !synthItal)
    {
      if (NSFONT_TRACE)
        fprintf(stderr, "*** nsfont_open CACHE HIT!\n");
      /* FIXME: Cast from (unsigned long) to Lisp_Object. */
      XHASH (font_object) = [cached unsignedLongValue];
      return font_object;
    }
  else
    {
      font_object = font_make_object (VECSIZE (struct nsfont_info),
                                      font_entity, pixel_size);
      if (!synthItal)
        [fontCache setObject: [NSNumber numberWithUnsignedLong:
					  (unsigned long) XHASH (font_object)]
		      forKey: nsfont];
    }

  font_info = (struct nsfont_info *) XFONT_OBJECT (font_object);
  font = (struct font *) font_info;
  if (!font)
    return Qnil; /* FIXME: other terms do, but return Qnil causes segfault */

  font_info->glyphs = (unsigned short **)
    xmalloc (0x100 * sizeof (unsigned short *));
  font_info->metrics = (struct font_metrics **)
    xmalloc (0x100 * sizeof (struct font_metrics *));
  if (!font_info->glyphs || !font_info->metrics)
    return Qnil;
  bzero (font_info->glyphs, 0x100 * sizeof (unsigned short *));
  bzero (font_info->metrics, 0x100 * sizeof (struct font_metrics *));

  BLOCK_INPUT;

  /* for metrics */
  sfont = [nsfont screenFont];
  if (sfont == nil)
    sfont = nsfont;

  /* non-metric backend font struct fields */
  font = (struct font *) font_info;
  font->pixel_size = [sfont pointSize];
  font->driver = &nsfont_driver;
  font->encoding_type = FONT_ENCODING_NOT_DECIDED;
  font->encoding_charset = -1;
  font->repertory_charset = -1;
  font->default_ascent = 0;
  font->vertical_centering = 0;
  font->baseline_offset = 0;
  font->relative_compose = 0;
  font->font_encoder = NULL;

  font->props[FONT_FORMAT_INDEX] = Qns;
  font->props[FONT_FILE_INDEX] = Qnil;

  {
    double expand, hshrink;
    float full_height, min_height, hd;
    const char *fontName = [[nsfont fontName] UTF8String];
    int len = strlen (fontName);

#ifdef NS_IMPL_GNUSTEP
    font_info->nsfont = sfont;
#else
    font_info->nsfont = nsfont;
#endif
    [font_info->nsfont retain];

    /* set up ns_font (defined in nsgui.h) */
    font_info->name = (char *)xmalloc (strlen (fontName) + 1);
    bcopy (fontName, font_info->name, strlen (fontName) + 1);
    font_info->bold = [fontMgr traitsOfFont: nsfont] & NSBoldFontMask;
    font_info->ital =
      synthItal || ([fontMgr traitsOfFont: nsfont] & NSItalicFontMask);

    /* Metrics etc.; some fonts return an unusually large max advance, so we
       only use it for fonts that have wide characters. */
    font_info->width = ([sfont numberOfGlyphs] > 2000) ?
      [sfont maximumAdvancement].width : ns_char_width (sfont, '0');

    brect =  [sfont boundingRectForFont];
    full_height = brect.size.height;
    min_height = [sfont ascender] - [sfont descender];
    hd = full_height - min_height;

    /* standard height, similar to Carbon. Emacs.app: was 0.5 by default. */
    expand = 0.0;
    hshrink = 1.0;

    font_info->underpos = 2; /*[sfont underlinePosition] is often clipped out */
    font_info->underwidth = [sfont underlineThickness];
    font_info->size = font->pixel_size;
    font_info->voffset = lrint (hshrink * [sfont ascender] + expand * hd / 2);

    /* max bounds */
    font_info->max_bounds.ascent =
      lrint (hshrink * [sfont ascender] + expand * hd/2);
    font_info->max_bounds.descent =
      -lrint (hshrink* [sfont descender] - expand*hd/2);
    font_info->height =
      font_info->max_bounds.ascent + font_info->max_bounds.descent;
    font_info->max_bounds.width = lrint (font_info->width);
    font_info->max_bounds.lbearing = lrint (brect.origin.x);
    font_info->max_bounds.rbearing =
      lrint (brect.size.width - font_info->width);

#ifdef NS_IMPL_COCOA
    /* set up synthItal and the CG font */
    font_info->synthItal = synthItal;
    {
      ATSFontRef atsFont = ATSFontFindFromPostScriptName
        ((CFStringRef)[nsfont fontName], kATSOptionFlagsDefault);

      if (atsFont == kATSFontRefUnspecified)
        {
          /* see if we can get it by dropping italic (then synthesizing) */
          atsFont = ATSFontFindFromPostScriptName ((CFStringRef)
              [[fontMgr convertFont: nsfont toNotHaveTrait: NSItalicFontMask]
                fontName], kATSOptionFlagsDefault);
          if (atsFont != kATSFontRefUnspecified)
              font_info->synthItal = YES;
          else
            {
              /* last resort fallback */
              atsFont = ATSFontFindFromPostScriptName
                ((CFStringRef)@"Monaco", kATSOptionFlagsDefault);
            }
        }
      font_info->cgfont = CGFontCreateWithPlatformFont ((void*)&atsFont);
    }
#endif

    /* set up metrics portion of font struct */
    font->ascent = [sfont ascender];
    font->descent = -[sfont descender];
    font->min_width = ns_char_width(sfont, '|');
    font->space_width = lrint (ns_char_width (sfont, ' '));
    font->average_width = lrint (font_info->width);
    font->max_width = lrint (font_info->max_bounds.width);
    font->height = lrint (font_info->height);
    font->underline_position = lrint (font_info->underpos);
    font->underline_thickness = lrint (font_info->underwidth);

    font->props[FONT_NAME_INDEX] = Ffont_xlfd_name (font_object, Qnil);
    font->props[FONT_FULLNAME_INDEX] =
      make_unibyte_string (font_info->name, strlen (font_info->name));
  }
  UNBLOCK_INPUT;

  return font_object;
}


/* Close FONT on frame F. */
static void
nsfont_close (FRAME_PTR f, struct font *font)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  int i;

  /* FIXME: this occurs apparently due to same failure to detect same font
            that causes need for cache in nsfont_open () */
  if (!font_info)
      return;

  for (i =0; i<0x100; i++)
    {
      xfree (font_info->glyphs[i]);
      xfree (font_info->metrics[i]);
    }
  [font_info->nsfont release];
#ifdef NS_IMPL_COCOA
  CGFontRelease (font_info->cgfont);
#endif
  xfree (font_info->name);
  xfree (font_info);
}


/* If FONT_ENTITY has a glyph for character C (Unicode code point),
   return 1.  If not, return 0.  If a font must be opened to check
   it, return -1. */
static int
nsfont_has_char (Lisp_Object entity, int c)
{
  return -1;
}


/* Return a glyph code of FONT for character C (Unicode code point).
   If FONT doesn't have such a glyph, return FONT_INVALID_CODE. */
static unsigned int
nsfont_encode_char (struct font *font, int c)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  unsigned char high = (c & 0xff00) >> 8, low = c & 0x00ff;
  unsigned short g;

  if (c > 0xFFFF)
    return FONT_INVALID_CODE;

  /* did we already cache this block? */
  if (!font_info->glyphs[high])
    ns_uni_to_glyphs (font_info, high);

  g = font_info->glyphs[high][low];
  return g == 0xFFFF ? FONT_INVALID_CODE : g;
}


/* Perform the size computation of glyphs of FONT and fill in members
   of METRICS.  The glyphs are specified by their glyph codes in
   CODE (length NGLYPHS). */
static int
nsfont_text_extents (struct font *font, unsigned int *code, int nglyphs,
                     struct font_metrics *metrics)
{
  struct nsfont_info *font_info = (struct nsfont_info *)font;
  struct font_metrics *pcm;
  unsigned char high, low;
  int totalWidth = 0;
  int i;

  bzero (metrics, sizeof (struct font_metrics));

  for (i =0; i<nglyphs; i++)
    {
      /* get metrics for this glyph, filling cache if need be */
      /* TODO: get metrics for whole string from an NSLayoutManager
               (if not too slow) */
      high = (code[i] & 0xFF00) >> 8;
      low = code[i] & 0x00FF;
      if (!font_info->metrics[high])
        ns_glyph_metrics (font_info, high);
      pcm = &(font_info->metrics[high][low]);

      if (metrics->lbearing > totalWidth + pcm->lbearing)
	metrics->lbearing = totalWidth + pcm->lbearing;
      if (metrics->rbearing < totalWidth + pcm->rbearing)
	metrics->rbearing = totalWidth + pcm->rbearing;
      if (metrics->ascent < pcm->ascent)
	metrics->ascent = pcm->ascent;
      if (metrics->descent < pcm->descent)
	metrics->descent = pcm->descent;

      totalWidth += pcm->width;
    }

  metrics->width = totalWidth;

  return totalWidth; /* not specified in doc, but xfont.c does it */
}


/* Draw glyphs between FROM and TO of S->char2b at (X Y) pixel
   position of frame F with S->FACE and S->GC.  If WITH_BACKGROUND
   is nonzero, fill the background in advance.  It is assured that
   WITH_BACKGROUND is zero when (FROM > 0 || TO < S->nchars). */
static int
nsfont_draw (struct glyph_string *s, int from, int to, int x, int y,
             int with_background)
/* NOTE: focus and clip must be set
     also, currently assumed (true in nsterm.m call) from ==0, to ==nchars */
{
  static char cbuf[1024];
  char *c = cbuf;
#ifdef NS_IMPL_GNUSTEP
  static float advances[1024];
  float *adv = advances;
#else
  static CGSize advances[1024];
  CGSize *adv = advances;
#endif
  struct face *face;
  NSRect r;
  struct nsfont_info *font = ns_tmp_font;
  NSColor *col, *bgCol;
  unsigned short *t = s->char2b;
  int i, len;
  char isComposite = s->first_glyph->type == COMPOSITE_GLYPH;
  int end = isComposite ? s->cmp_to : s->nchars;

  /* Select face based on input flags */
  switch (ns_tmp_flags)
    {
    case NS_DUMPGLYPH_CURSOR:
      face = s->face;
      break;
    case NS_DUMPGLYPH_MOUSEFACE:
      face = FACE_FROM_ID (s->f,
                           FRAME_NS_DISPLAY_INFO (s->f)->mouse_face_face_id);
      if (!face)
        face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
      break;
    default:
      face = s->face;
    }

  r.origin.x = s->x;
  if (s->face->box != FACE_NO_BOX && s->first_glyph->left_box_line_p)
    r.origin.x += abs (s->face->box_line_width);

  r.origin.y = s->y;
  r.size.height = FONT_HEIGHT (font);

  /* Convert UTF-16 (?) to UTF-8 and determine advances.  Note if we just ask
     NS to render the string, it will come out differently from the individual
     character widths added up because of layout processing. */
  {
    XCharStruct *cs;
    int cwidth, twidth = 0;
    int hi, lo;
    /* FIXME: composition: no vertical displacement is considered. */
    t += s->cmp_from; /* advance into composition */
    for (i = s->cmp_from; i < end; i++, t++)
      {
        hi = (*t & 0xFF00) >> 8;
        lo = *t & 0x00FF;
        if (isComposite)
          {
	    if (!s->first_glyph->u.cmp.automatic)
		cwidth = s->cmp->offsets[i * 2] /* (H offset) */ - twidth;
	    else
	      {
		Lisp_Object gstring = composition_gstring_from_id (s->cmp_id);
		Lisp_Object glyph = LGSTRING_GLYPH (gstring, i);
		if (NILP (LGLYPH_ADJUSTMENT (glyph)))
		    cwidth = LGLYPH_WIDTH (glyph);
		else
		  {
		    cwidth = LGLYPH_WADJUST (glyph);
#ifdef NS_IMPL_GNUSTEP
		    *(adv-1) += LGLYPH_XOFF (glyph);
#else
		    (*(adv-1)).width += LGLYPH_XOFF (glyph);
#endif
		  }
	      }
          }
        else
          {
            if (!font->metrics[hi]) /* FIXME: why/how can we need this now? */
              ns_glyph_metrics (font, hi);
            cwidth = font->metrics[hi][lo].width;
          }
        twidth += cwidth;
#ifdef NS_IMPL_GNUSTEP
        *adv++ = cwidth;
        CHAR_STRING_ADVANCE (*t, c); /* this converts the char to UTF-8 */
#else
        (*adv++).width = cwidth;
#endif
      }
    len = adv - advances;
    r.size.width = twidth;
    *c = 0;
  }

  /* fill background if requested */
  if (with_background && !isComposite)
    {
      NSRect br = r;
      int fibw = FRAME_INTERNAL_BORDER_WIDTH (s->f);
      int mbox_line_width = max (s->face->box_line_width, 0);

      if (s->row->full_width_p)
        {
          if (br.origin.x <= fibw + 1 + mbox_line_width)
            {
              br.size.width += br.origin.x - mbox_line_width;
              br.origin.x = mbox_line_width;
            }
          if (FRAME_PIXEL_WIDTH (s->f) - (br.origin.x + br.size.width)
                <= fibw+1)
            br.size.width += fibw;
        }
      if (s->face->box == FACE_NO_BOX)
        {
          /* expand unboxed top row over internal border */
          if (br.origin.y <= fibw + 1 + mbox_line_width)
            {
              br.size.height += br.origin.y;
              br.origin.y = 0;
            }
        }
      else
        {
          int correction = abs (s->face->box_line_width)+1;
          br.origin.y += correction;
          br.size.height -= 2*correction;
          br.origin.x += correction;
          br.size.width -= 2*correction;
        }

      if (!s->face->stipple)
        [(NS_FACE_BACKGROUND (face) != 0
          ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
          : FRAME_BACKGROUND_COLOR (s->f)) set];
      else
        {
          struct ns_display_info *dpyinfo = FRAME_NS_DISPLAY_INFO (s->f);
          [[dpyinfo->bitmaps[face->stipple-1].img stippleMask] set];
        }
      NSRectFill (br);
    }


  /* set up for character rendering */
  r.origin.y += font->voffset + (s->height - font->height)/2;

  col = (NS_FACE_FOREGROUND (face) != 0
         ? ns_lookup_indexed_color (NS_FACE_FOREGROUND (face), s->f)
         : FRAME_FOREGROUND_COLOR (s->f));
  /* FIXME: find another way to pass this */
  bgCol = (ns_tmp_flags != NS_DUMPGLYPH_FOREGROUND ? nil
           : (NS_FACE_BACKGROUND (face) != 0
              ? ns_lookup_indexed_color (NS_FACE_BACKGROUND (face), s->f)
              : FRAME_BACKGROUND_COLOR (s->f)));

  /* render under GNUstep using DPS */
#ifdef NS_IMPL_GNUSTEP
  {
    NSGraphicsContext *context = GSCurrentContext ();

    DPSgsave (context);
    [font->nsfont set];

    /* do erase if "foreground" mode */
    if (bgCol != nil)
      {
        [bgCol set];
        DPSmoveto (context, r.origin.x, r.origin.y);
/*[context GSSetTextDrawingMode: GSTextFillStroke]; /// not implemented yet */
        DPSxshow (context, cbuf, advances, len);
        DPSstroke (context);
        [col set];
/*[context GSSetTextDrawingMode: GSTextFill]; /// not implemented yet */
      }

    /* do underline */
    if (face->underline_p)
      {
        if (face->underline_color != 0)
          [ns_lookup_indexed_color (face->underline_color, s->f) set];
        else
          [col set];
        DPSmoveto (context, r.origin.x, r.origin.y + font->underpos);
        DPSlineto (context, r.origin.x+r.size.width, r.origin.y+font->underpos);
        if (face->underline_color != 0)
          [col set];
      }
    else
      [col set];

    /* draw with DPSxshow () */
    DPSmoveto (context, r.origin.x, r.origin.y);
    DPSxshow (context, cbuf, advances, len);
    DPSstroke (context);

    DPSgrestore (context);
    return to-from;
  }

#else  /* NS_IMPL_COCOA */
  {
    CGContextRef gcontext =
      [[NSGraphicsContext currentContext] graphicsPort];
    static CGAffineTransform fliptf;
    static BOOL firstTime = YES;

    if (firstTime)
      {
        firstTime = NO;
        fliptf = CGAffineTransformMakeScale (1.0, -1.0);
      }

    CGContextSaveGState (gcontext);

    fliptf.c =  font->synthItal ? Fix2X (kATSItalicQDSkew) : 0.0;

    CGContextSetFont (gcontext, font->cgfont);
    CGContextSetFontSize (gcontext, font->size);
    if (ns_antialias_text == Qnil || font->size <= ns_antialias_threshold)
      CGContextSetShouldAntialias (gcontext, 0);
    else
      CGContextSetShouldAntialias (gcontext, 1);

    CGContextSetTextMatrix (gcontext, fliptf);

    if (bgCol != nil)
      {
        /* foreground drawing; erase first to avoid overstrike */
        [bgCol set];
        CGContextSetTextDrawingMode (gcontext, kCGTextFillStroke);
        CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
        CGContextShowGlyphsWithAdvances (gcontext, s->char2b, advances, len);
        CGContextSetTextDrawingMode (gcontext, kCGTextFill);
      }

    if (face->underline_p)
      {
        if (face->underline_color != 0)
          [ns_lookup_indexed_color (face->underline_color, s->f) set];
        else
          [col set];
        CGContextBeginPath (gcontext);
        CGContextMoveToPoint (gcontext,
                              r.origin.x, r.origin.y + font->underpos);
        CGContextAddLineToPoint (gcontext, r.origin.x + r.size.width,
                                r.origin.y + font->underpos);
        CGContextStrokePath (gcontext);
        if (face->underline_color != 0)
          [col set];
      }
    else
      [col set];

    CGContextSetTextPosition (gcontext, r.origin.x, r.origin.y);
    CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
                                    advances, len);

    if (face->overstrike)
      {
        CGContextSetTextPosition (gcontext, r.origin.x+0.5, r.origin.y);
        CGContextShowGlyphsWithAdvances (gcontext, s->char2b + s->cmp_from,
                                        advances, len);
      }

    CGContextRestoreGState (gcontext);
    return;
  }
#endif  /* NS_IMPL_COCOA */

}



/* ==========================================================================

    Font glyph and metrics caching functions

   ========================================================================== */

/* Find and cache corresponding glyph codes for unicode values in given
   hi-byte block of 256. */
static void
ns_uni_to_glyphs (struct nsfont_info *font_info, unsigned char block)
{
#ifdef NS_IMPL_COCOA
  static EmacsGlyphStorage *glyphStorage;
  static char firstTime = 1;
#endif
  unichar *unichars = xmalloc (0x101 * sizeof (unichar));
  unsigned int i, g, idx;
  unsigned short *glyphs;

  if (NSFONT_TRACE)
    fprintf (stderr, "%p\tFinding glyphs for glyphs in block %d\n",
            font_info, block);

 BLOCK_INPUT;

#ifdef NS_IMPL_COCOA
  if (firstTime)
    {
      firstTime = 0;
      glyphStorage = [[EmacsGlyphStorage alloc] initWithCapacity: 0x100];
    }
#endif

  font_info->glyphs[block] = xmalloc (0x100 * sizeof (unsigned short));
  if (!unichars || !(font_info->glyphs[block]))
    abort ();

  /* create a string containing all unicode characters in this block */
  for (idx = block<<8, i =0; i<0x100; idx++, i++)
    if (idx < 0xD800 || idx > 0xDFFF)
      unichars[i] = idx;
    else
      unichars[i] = 0xFEFF;
  unichars[0x100] = 0;

  {
#ifdef NS_IMPL_COCOA
    NSString *allChars = [[NSString alloc]
                               initWithCharactersNoCopy: unichars
                                                 length: 0x100
                                           freeWhenDone: NO];
    NSGlyphGenerator *glyphGenerator = [NSGlyphGenerator sharedGlyphGenerator];
    /*NSCharacterSet *coveredChars = [nsfont coveredCharacterSet]; */
    unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
    NSUInteger gInd =0, cInd =0;

    [glyphStorage setString: allChars font: font_info->nsfont];
    [glyphGenerator generateGlyphsForGlyphStorage: glyphStorage
                        desiredNumberOfCharacters: glyphStorage->maxChar
                                       glyphIndex: &gInd characterIndex: &cInd];
#endif
    glyphs = font_info->glyphs[block];
    for (i =0; i<0x100; i++, glyphs++)
      {
#ifdef NS_IMPL_GNUSTEP
        g = unichars[i];
#else
        g = glyphStorage->cglyphs[i];
        /* TODO: is this a good check?  maybe need to use coveredChars.. */
        if (g > numGlyphs)
          g = 0xFFFF; /* hopefully unused... */
#endif
        *glyphs = g;
      }

#ifdef NS_IMPL_COCOA
    [allChars release];
#endif
  }

  UNBLOCK_INPUT;
  xfree (unichars);
}


/* Determine and cache metrics for corresponding glyph codes in given
   hi-byte block of 256. */
static void
ns_glyph_metrics (struct nsfont_info *font_info, unsigned char block)
{
  unsigned int i, g;
  unsigned int numGlyphs = [font_info->nsfont numberOfGlyphs];
  NSFont *sfont;
  struct font_metrics *metrics;

  if (NSFONT_TRACE)
    fprintf (stderr, "%p\tComputing metrics for glyphs in block %d\n",
            font_info, block);

#ifdef NS_IMPL_GNUSTEP
  /* not implemented yet (as of startup 0.18), so punt */
  if (numGlyphs == 0)
    numGlyphs = 0x10000;
#endif

 BLOCK_INPUT;
 sfont = [font_info->nsfont screenFont];

  font_info->metrics[block] = xmalloc (0x100 * sizeof (struct font_metrics));
  bzero (font_info->metrics[block], 0x100 * sizeof (struct font_metrics));
  if (!(font_info->metrics[block]))
    abort ();

  metrics = font_info->metrics[block];
  for (g = block<<8, i =0; i<0x100 && g < numGlyphs; g++, i++, metrics++)
    {
      float w, lb, rb;
      NSRect r = [sfont boundingRectForGlyph: g];

      w = max ([sfont advancementForGlyph: g].width, 2.0);
      metrics->width = lrint (w);

      lb = r.origin.x;
      rb = r.size.width - w;
      if (lb < 0)
        metrics->lbearing = round (lb);
      if (font_info->ital)
        rb += 0.22 * font_info->height;
      metrics->rbearing = lrint (w + rb);

      metrics->descent = r.origin.y < 0 ? -r.origin.y : 0;
 /*lrint (hshrink * [sfont ascender] + expand * hd/2); */
      metrics->ascent = r.size.height - metrics->descent;
/*-lrint (hshrink* [sfont descender] - expand * hd/2); */
    }
  UNBLOCK_INPUT;
}


#ifdef NS_IMPL_COCOA
/* helper for font glyph setup */
@implementation EmacsGlyphStorage

- init
{
  return [self initWithCapacity: 1024];
}

- initWithCapacity: (unsigned long) c
{
  self = [super init];
  maxChar = 0;
  maxGlyph = 0;
  dict = [NSMutableDictionary new];
  cglyphs = (CGGlyph *)xmalloc (c * sizeof (CGGlyph));
  return self;
}

- (void) dealloc
{
  if (attrStr != nil)
    [attrStr release];
  [dict release];
  xfree (cglyphs);
  [super dealloc];
}

- (void) setString: (NSString *)str font: (NSFont *)font
{
  [dict setObject: font forKey: NSFontAttributeName];
  attrStr = [[NSAttributedString alloc] initWithString: str attributes: dict];
  maxChar = [str length];
  maxGlyph = 0;
}

/* NSGlyphStorage protocol */
- (NSUInteger)layoutOptions
{
  return 0;
}

- (NSAttributedString *)attributedString
{
  return attrStr;
}

- (void)insertGlyphs: (const NSGlyph *)glyphs length: (NSUInteger)length
        forStartingGlyphAtIndex: (NSUInteger)glyphIndex
        characterIndex: (NSUInteger)charIndex
{
  len = glyphIndex+length;
  for (i =glyphIndex; i<len; i++)
    cglyphs[i] = glyphs[i-glyphIndex];
  if (len > maxGlyph)
    maxGlyph = len;
}

- (void)setIntAttribute: (NSInteger)attributeTag value: (NSInteger)val
        forGlyphAtIndex: (NSUInteger)glyphIndex
{
  return;
}

@end
#endif /* NS_IMPL_COCOA */


/* Debugging */
void
ns_dump_glyphstring (struct glyph_string *s)
{
  int i;

  fprintf (stderr, "Glyph string len = %d at (%d, %d) overhang (%d, %d),"
"overlap = %d, bg_filled = %d:",
           s->nchars, s->x, s->y, s->left_overhang, s->right_overhang,
           s->row->overlapping_p, s->background_filled_p);
  for (i =0; i<s->nchars; i++)
    fprintf (stderr, "%c", s->first_glyph[i].u.ch);
  fprintf (stderr, "\n");
}


void
syms_of_nsfont ()
{
  nsfont_driver.type = Qns;
  register_font_driver (&nsfont_driver, NULL);
  DEFSYM (Qapple, "apple");
  DEFSYM (Qroman, "roman");
  DEFSYM (Qmedium, "medium");
  DEFVAR_LISP ("ns-reg-to-script", &Vns_reg_to_script,
               doc: /* Internal use: maps font registry to unicode script. */);
}

// arch-tag: d6c3c6f0-62de-4978-8b1e-b7966fe02cae