* lisp/progmodes/grep.el (grep-mode): Disable default
[emacs.git] / lisp / net / xesam.el
blob64c26cfb2c9eebfd7138927b02ccf3518b81197a
1 ;;; xesam.el --- Xesam interface to search engines.
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Michael Albinus <michael.albinus@gmx.de>
6 ;; Keywords: tools, hypermedia
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This package provides an interface to Xesam, a D-Bus based "eXtEnsible
26 ;; Search And Metadata specification". It has been tested with
28 ;; xesam-glib 0.3.4, xesam-tools 0.6.1
29 ;; beagle 0.3.7, beagle-xesam 0.2
30 ;; strigi 0.5.11
32 ;; The precondition for this package is a D-Bus aware Emacs. This is
33 ;; configured per default, when Emacs is built on a machine running
34 ;; D-Bus. Furthermore, there must be at least one search engine
35 ;; running, which supports the Xesam interface. Beagle and strigi have
36 ;; been tested; tracker, pinot and recoll are also said to support
37 ;; Xesam. You can check the existence of such a search engine by
39 ;; (dbus-list-queued-owners :session "org.freedesktop.xesam.searcher")
41 ;; In order to start a search, you must load xesam.el:
43 ;; (require 'xesam)
45 ;; xesam.el supports two types of queries, which are explained *very* short:
47 ;; * Full text queries. Just search keys shall be given, like
49 ;; hello world
51 ;; A full text query in xesam.el is restricted to files.
53 ;; * Xesam End User Search Language queries. The Xesam query language
54 ;; is described at <http://xesam.org/main/XesamUserSearchLanguage>,
55 ;; which must be consulted for the whole features.
57 ;; A query string consists of search keys, collectors, selectors,
58 ;; and phrases. Search keys are words like in a full text query:
60 ;; hello word
62 ;; A selector is a tuple <keyword><relation>. <keyword> can be any
63 ;; predefined Xesam keyword, the most common keywords are "ext"
64 ;; (file name extension), "format " (mime type), "tag" (user
65 ;; keywords) and "type" (types of items, like "audio", "file",
66 ;; "picture", "attachment"). <relation> is a comparison to a value,
67 ;; which must be a string (relation ":" or "=") or number (relation
68 ;; "<=", ">=", "<", ">"):
70 ;; type:attachment ext=el
72 ;; A collector is one of the items "AND", "and", "&&", "OR", "or",
73 ;; "||", or "-". The default collector on multiple terms is "AND";
74 ;; "-" means "AND NOT".
76 ;; albinus -type:file
78 ;; A phrase is a string enclosed in quotes, with appended modifiers
79 ;; (single letters). Examples of modifiers are "c" (case
80 ;; sensitive), "C" (case insensitive), "e" (exact match), "r"
81 ;; (regular expression):
83 ;; "Hello world"c
85 ;; You can customize, whether you want to apply a Xesam user query, or
86 ;; a full text query. Note, that not every search engine supports
87 ;; both query types.
89 ;; (setq xesam-query-type 'fulltext-query)
91 ;; Another option to be customised is the number of hits to be
92 ;; presented at once.
94 ;; (setq xesam-hits-per-page 50)
96 ;; A search can be started by the command
98 ;; M-x xesam-search
100 ;; When several search engines are registered, the engine to be used
101 ;; can be selected via minibuffer completion. Afterwards, the query
102 ;; shall be entered in the minibuffer.
104 ;; Search results are presented in a new buffer. This buffer has the
105 ;; major mode `xesam-mode', with the following keybindings:
107 ;; SPC `scroll-up'
108 ;; DEL `scroll-down'
109 ;; < `beginning-of-buffer'
110 ;; > `end-of-buffer'
111 ;; q `quit-window'
112 ;; z `kill-this-buffer'
113 ;; g `revert-buffer'
115 ;; The search results are represented by widgets. Navigation commands
116 ;; are the usual widget navigation commands:
118 ;; TAB `widget-forward'
119 ;; <backtab> `widget-backward'
121 ;; Applying RET, <down-mouse-1>, or <down-mouse-2> on a URL belonging
122 ;; to the widget, brings up more details of the search hit. The way,
123 ;; how this hit is presented, depends on the type of the hit. HTML
124 ;; files are opened via `browse-url'. Local files are opened in a new
125 ;; buffer, with highlighted search hits (highlighting can be toggled
126 ;; by `xesam-minor-mode' in that buffer).
128 ;;; Code:
130 ;; D-Bus support in the Emacs core can be disabled with configuration
131 ;; option "--without-dbus". Declare used subroutines and variables.
132 (declare-function dbus-call-method "dbusbind.c")
133 (declare-function dbus-register-signal "dbusbind.c")
135 (require 'dbus)
137 ;; Pacify byte compiler.
138 (eval-when-compile
139 (require 'cl))
141 ;; Widgets are used to highlight the search results.
142 (require 'widget)
143 (require 'wid-edit)
145 ;; `run-at-time' is used in the signal handler.
146 (require 'timer)
148 ;; The default search field is "xesam:url". It must be inspected.
149 (require 'url)
151 (defgroup xesam nil
152 "Xesam compatible interface to search engines."
153 :group 'extensions
154 :group 'comm
155 :version "23.1")
157 (defcustom xesam-query-type 'user-query
158 "Xesam query language type."
159 :group 'xesam
160 :type '(choice
161 (const :tag "Xesam user query" user-query)
162 (const :tag "Xesam fulltext query" fulltext-query)))
164 (defcustom xesam-hits-per-page 20
165 "Number of search hits to be displayed in the result buffer."
166 :group 'xesam
167 :type 'integer)
169 (defface xesam-mode-line '((t :inherit mode-line-emphasis))
170 "Face to highlight mode line."
171 :group 'xesam)
173 (defface xesam-highlight '((t :inherit match))
174 "Face to highlight query entries.
175 It will be overlayed by `widget-documentation-face', so it shall
176 be different at least in one face property not set in that face."
177 :group 'xesam)
179 (defvar xesam-debug nil
180 "Insert debug information in the help echo.")
182 (defconst xesam-service-search "org.freedesktop.xesam.searcher"
183 "The D-Bus name used to talk to Xesam.")
185 (defconst xesam-path-search "/org/freedesktop/xesam/searcher/main"
186 "The D-Bus object path used to talk to Xesam.")
188 ;; Methods: "NewSession", "SetProperty", "GetProperty",
189 ;; "CloseSession", "NewSearch", "StartSearch", "GetHitCount",
190 ;; "GetHits", "GetHitData", "CloseSearch" and "GetState".
191 ;; Signals: "HitsAdded", "HitsRemoved", "HitsModified", "SearchDone"
192 ;; and "StateChanged".
193 (defconst xesam-interface-search "org.freedesktop.xesam.Search"
194 "The D-Bus Xesam search interface.")
196 (defconst xesam-all-fields
197 '("xesam:35mmEquivalent" "xesam:aimContactMedium" "xesam:aperture"
198 "xesam:aspectRatio" "xesam:attachmentEncoding" "xesam:attendee"
199 "xesam:audioBirate" "xesam:audioChannels" "xesam:audioCodec"
200 "xesam:audioCodecType" "xesam:audioSampleFormat" "xesam:audioSampleRate"
201 "xesam:author" "xesam:bcc" "xesam:birthDate" "xesam:blogContactURL"
202 "xesam:cameraManufacturer" "xesam:cameraModel" "xesam:cc" "xesam:ccdWidth"
203 "xesam:cellPhoneNumber" "xesam:characterCount" "xesam:charset"
204 "xesam:colorCount" "xesam:colorSpace" "xesam:columnCount" "xesam:comment"
205 "xesam:commentCharacterCount" "xesam:conflicts" "xesam:contactMedium"
206 "xesam:contactName" "xesam:contactNick" "xesam:contactPhoto"
207 "xesam:contactURL" "xesam:contains" "xesam:contenKeyword"
208 "xesam:contentComment" "xesam:contentCreated" "xesam:contentModified"
209 "xesam:contentType" "xesam:contributor" "xesam:copyright" "xesam:creator"
210 "xesam:definesClass" "xesam:definesFunction" "xesam:definesGlobalVariable"
211 "xesam:deletionTime" "xesam:depends" "xesam:description" "xesam:device"
212 "xesam:disclaimer" "xesam:documentCategory" "xesam:duration"
213 "xesam:emailAddress" "xesam:eventEnd" "xesam:eventLocation"
214 "xesam:eventStart" "xesam:exposureBias" "xesam:exposureProgram"
215 "xesam:exposureTime" "xesam:faxPhoneNumber" "xesam:fileExtension"
216 "xesam:fileSystemType" "xesam:flashUsed" "xesam:focalLength"
217 "xesam:focusDistance" "xesam:formatSubtype" "xesam:frameCount"
218 "xesam:frameRate" "xesam:freeSpace" "xesam:gender" "xesam:generator"
219 "xesam:generatorOptions" "xesam:group" "xesam:hash" "xesam:hash"
220 "xesam:height" "xesam:homeEmailAddress" "xesam:homePhoneNumber"
221 "xesam:homePostalAddress" "xesam:homepageContactURL"
222 "xesam:horizontalResolution" "xesam:icqContactMedium" "xesam:id"
223 "xesam:imContactMedium" "xesam:interests" "xesam:interlaceMode"
224 "xesam:isEncrypted" "xesam:isImportant" "xesam:isInProgress"
225 "xesam:isPasswordProtected" "xesam:isRead" "xesam:isoEquivalent"
226 "xesam:jabberContactMedium" "xesam:keyword" "xesam:language" "xesam:legal"
227 "xesam:license" "xesam:licenseType" "xesam:lineCount" "xesam:links"
228 "xesam:mailingPostalAddress" "xesam:maintainer" "xesam:md5Hash"
229 "xesam:mediaCodec" "xesam:mediaCodecBitrate" "xesam:mediaCodecType"
230 "xesam:meteringMode" "xesam:mimeType" "xesam:mountPoint"
231 "xesam:msnContactMedium" "xesam:name" "xesam:occupiedSpace"
232 "xesam:orientation" "xesam:originalLocation" "xesam:owner"
233 "xesam:pageCount" "xesam:permissions" "xesam:phoneNumber"
234 "xesam:physicalAddress" "xesam:pixelFormat" "xesam:primaryRecipient"
235 "xesam:programmingLanguage" "xesam:rating" "xesam:receptionTime"
236 "xesam:recipient" "xesam:related" "xesam:remoteUser" "xesam:rowCount"
237 "xesam:sampleBitDepth" "xesam:sampleFormat" "xesam:secondaryRecipient"
238 "xesam:sha1Hash" "xesam:size" "xesam:skypeContactMedium"
239 "xesam:sourceCreated" "xesam:sourceModified" "xesam:storageSize"
240 "xesam:subject" "xesam:supercedes" "xesam:title" "xesam:to"
241 "xesam:totalSpace" "xesam:totalUncompressedSize" "xesam:url"
242 "xesam:usageIntensity" "xesam:userComment" "xesam:userKeyword"
243 "xesam:uuid" "xesam:version" "xesam:verticalResolution" "xesam:videoBirate"
244 "xesam:videoCodec" "xesam:videoCodecType" "xesam:whiteBalance"
245 "xesam:width" "xesam:wordCount" "xesam:workEmailAddress"
246 "xesam:workPhoneNumber" "xesam:workPostalAddress"
247 "xesam:yahooContactMedium")
248 "All fields from the Xesam Core Ontology.
249 This defconst can be used to check for a new search engine, which
250 fields are supported.")
252 (defconst xesam-user-query
253 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
254 <request xmlns=\"http://freedesktop.org/standards/xesam/1.0/query\">
255 <userQuery>
257 </userQuery>
258 </request>"
259 "The Xesam user query XML.")
261 (defconst xesam-fulltext-query
262 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
263 <request xmlns=\"http://freedesktop.org/standards/xesam/1.0/query\">
264 <query content=\"xesam:Document\" source=\"xesam:File\">
265 <fullText>
266 <string>%s</string>
267 </fullText>
268 </query>
269 </request>"
270 "The Xesam fulltext query XML.")
272 (declare-function dbus-get-unique-name "dbusbind.c" (bus))
274 (defvar xesam-dbus-unique-names
275 (list (cons :system (dbus-get-unique-name :system))
276 (cons :session (dbus-get-unique-name :session)))
277 "The unique names, under which Emacs is registered at D-Bus.")
279 (defun xesam-dbus-call-method (&rest args)
280 "Apply a D-Bus method call.
281 `dbus-call-method' is to be preferred, because it is more
282 performant. If the target D-Bus service is owned by Emacs, this
283 is not applicable, and `dbus-call-method-non-blocking' must be
284 used instead. ARGS are identical to the argument list of both
285 functions."
286 (apply
287 ;; The first argument is the bus, the second argument the targt service.
288 (if (string-equal (cdr (assoc (car args) xesam-dbus-unique-names))
289 (cadr args))
290 'dbus-call-method-non-blocking 'dbus-call-method)
291 args))
293 (defun xesam-get-property (engine property)
294 "Return the PROPERTY value of ENGINE."
295 ;; "GetProperty" returns a variant, so we must use the car.
296 (car (xesam-dbus-call-method
297 :session (car engine) xesam-path-search
298 xesam-interface-search "GetProperty"
299 (xesam-get-cached-property engine "session") property)))
301 (defun xesam-set-property (engine property value)
302 "Set the PROPERTY of ENGINE to VALUE.
303 VALUE can be a string, a non-negative integer, a boolean
304 value (nil or t), or a list of them. It returns the new value of
305 PROPERTY in the search engine. This new value can be different
306 from VALUE, depending on what the search engine accepts."
307 ;; "SetProperty" returns a variant, so we must use the car.
308 (car (xesam-dbus-call-method
309 :session (car engine) xesam-path-search
310 xesam-interface-search "SetProperty"
311 (xesam-get-cached-property engine "session") property
312 ;; The value must be a variant. It can be only a string, an
313 ;; unsigned int, a boolean, or an array of them. So we need
314 ;; no type keyword; we let the type check to the search
315 ;; engine.
316 (list :variant value))))
318 (defvar xesam-minibuffer-vendor-history nil
319 "Interactive vendor history.")
321 (defvar xesam-minibuffer-query-history nil
322 "Interactive query history.")
324 ;; Pacify byte compiler.
325 (defvar xesam-vendor nil)
326 (make-variable-buffer-local 'xesam-vendor)
327 (put 'xesam-vendor 'permanent-local t)
329 (defvar xesam-engine nil)
330 (defvar xesam-search nil)
331 (defvar xesam-type nil)
332 (defvar xesam-query nil)
333 (defvar xesam-xml-string nil)
334 (defvar xesam-objects nil)
335 (defvar xesam-current nil)
336 (defvar xesam-count nil)
337 (defvar xesam-to nil)
338 (defvar xesam-notify-function nil)
339 (defvar xesam-refreshing nil)
342 ;;; Search engines.
344 (defvar xesam-search-engines nil
345 "List of available Xesam search engines.
346 Every entry is an association list, with a car denoting the
347 unique D-Bus service name of the engine. The rest of the entry
348 are cached associations of engine attributes, like the session
349 identifier, and the display name. Example:
351 \(\(\":1.59\"
352 \(\"session\" . \"0t1214948020ut358230u0p2698r3912347765k3213849828\")
353 \(\"vendor.display\" . \"Tracker Xesam Service\"))
354 \(\":1.27\"
355 \(\"session\" . \"strigisession1369133069\")
356 \(\"vendor.display\" . \"Strigi Desktop Search\")))
358 A Xesam-compatible search engine is identified as a queued D-Bus
359 service of the known service `xesam-service-search'.")
361 (defun xesam-get-cached-property (engine property)
362 "Return the PROPERTY value of ENGINE from the cache.
363 If PROPERTY is not existing, retrieve it from ENGINE first."
364 ;; If the property has not been cached yet, we retrieve it from the
365 ;; engine, and cache it.
366 (unless (assoc property engine)
367 (xesam-set-cached-property
368 engine property (xesam-get-property engine property)))
369 (cdr (assoc property engine)))
371 (defun xesam-set-cached-property (engine property value)
372 "Set the PROPERTY of ENGINE to VALUE in the cache."
373 (setcdr engine (append (cdr engine) (list (cons property value)))))
375 (defun xesam-delete-search-engine (&rest args)
376 "Remove service from `xesam-search-engines'."
377 (setq xesam-search-engines
378 (delete (assoc (car args) xesam-search-engines) xesam-search-engines)))
380 (defvar dbus-debug)
382 (defun xesam-search-engines ()
383 "Return Xesam search engines, stored in `xesam-search-engines'.
384 The first search engine is the name owner of `xesam-service-search'.
385 If there is no registered search engine at all, the function returns `nil'."
386 (let ((services (dbus-ignore-errors
387 (dbus-list-queued-owners
388 :session xesam-service-search)))
389 engine vendor-id hit-fields)
390 (dolist (service services)
391 (unless (assoc-string service xesam-search-engines)
393 ;; Open a new session, and add it to the search engines list.
394 (add-to-list 'xesam-search-engines (list service) 'append)
395 (setq engine (assoc service xesam-search-engines))
397 ;; Add the session string.
398 (xesam-set-cached-property
399 engine "session"
400 (xesam-dbus-call-method
401 :session service xesam-path-search
402 xesam-interface-search "NewSession"))
404 ;; Unset the "search.live" property; we don't want to be
405 ;; informed by changed results.
406 (xesam-set-property engine "search.live" nil)
408 ;; Check the vendor properties.
409 (setq vendor-id (xesam-get-property engine "vendor.id")
410 hit-fields (xesam-get-property engine "hit.fields"))
412 ;; Ususally, `hit.fields' shall describe supported fields.
413 ;; That is not the case now, so we set it ourselves.
414 ;; Hopefully, this will change later.
415 (setq hit-fields
416 (case (intern vendor-id)
417 (Beagle
418 '("xesam:mimeType" "xesam:url"))
419 (Strigi
420 '("xesam:author" "xesam:cc" "xesam:charset"
421 "xesam:contentType" "xesam:fileExtension"
422 "xesam:id" "xesam:lineCount" "xesam:links"
423 "xesam:mimeType" "xesam:name" "xesam:size"
424 "xesam:sourceModified" "xesam:subject" "xesam:to"
425 "xesam:url"))
426 (TrackerXesamSession
427 '("xesam:relevancyRating" "xesam:url"))
428 (Debbugs
429 '("xesam:keyword" "xesam:owner" "xesam:title"
430 "xesam:url" "xesam:sourceModified" "xesam:mimeType"
431 "debbugs:key"))
432 ;; xesam-tools yahoo service.
433 (t '("xesam:contentModified" "xesam:mimeType" "xesam:summary"
434 "xesam:title" "xesam:url" "yahoo:displayUrl"))))
436 (xesam-set-property engine "hit.fields" hit-fields)
437 (xesam-set-property engine "hit.fields.extended" '("xesam:snippet"))
439 ;; Let us notify, when the search engine disappears.
440 (dbus-register-signal
441 :session dbus-service-dbus dbus-path-dbus
442 dbus-interface-dbus "NameOwnerChanged"
443 'xesam-delete-search-engine service))))
444 xesam-search-engines)
447 ;;; Search buffers.
449 (defvar xesam-mode-map
450 (let ((map (copy-keymap special-mode-map)))
451 (set-keymap-parent xesam-mode-map widget-keymap)
452 map))
454 (define-derived-mode xesam-mode special-mode "Xesam"
455 "Major mode for presenting search results of a Xesam search.
456 In this mode, widgets represent the search results.
458 \\{xesam-mode-map}
459 Turning on Xesam mode runs the normal hook `xesam-mode-hook'. It
460 can be used to set `xesam-notify-function', which must a search
461 engine specific, widget :notify function to visualize xesam:url."
462 (set (make-local-variable 'xesam-notify-function) nil)
463 ;; Maybe we implement something useful, later on.
464 (set (make-local-variable 'revert-buffer-function) 'ignore)
465 ;; `xesam-engine', `xesam-search', `xesam-type', `xesam-query', and
466 ;; `xesam-xml-string' will be set in `xesam-new-search'.
467 (set (make-local-variable 'xesam-engine) nil)
468 (set (make-local-variable 'xesam-search) nil)
469 (set (make-local-variable 'xesam-type) "")
470 (set (make-local-variable 'xesam-query) "")
471 (set (make-local-variable 'xesam-xml-string) "")
472 (set (make-local-variable 'xesam-objects) nil)
473 ;; `xesam-current' is the last hit put into the search buffer,
474 (set (make-local-variable 'xesam-current) 0)
475 ;; `xesam-count' is the number of hits reported by the search engine.
476 (set (make-local-variable 'xesam-count) 0)
477 ;; `xesam-to' is the upper hit number to be presented.
478 (set (make-local-variable 'xesam-to) xesam-hits-per-page)
479 ;; `xesam-notify-function' can be a search engine specific function
480 ;; to visualize xesam:url. It can be overwritten in `xesam-mode'.
481 (set (make-local-variable 'xesam-notify-function) nil)
482 ;; `xesam-refreshing' is an indicator, whether the buffer is just
483 ;; being updated. Needed, because `xesam-refresh-search-buffer'
484 ;; can be triggered by an event.
485 (set (make-local-variable 'xesam-refreshing) nil)
486 ;; Mode line position returns hit counters.
487 (set (make-local-variable 'mode-line-position)
488 (list '(-3 "%p%")
489 '(10 (:eval (format " (%d/%d)" xesam-current xesam-count)))))
490 ;; Header line contains the query string.
491 (set (make-local-variable 'header-line-format)
492 (list '(20
493 (:eval
494 (list "Type: "
495 (propertize xesam-type 'face 'xesam-mode-line))))
496 '(10
497 (:eval
498 (list " Query: "
499 (propertize
500 xesam-query
501 'face 'xesam-mode-line
502 'help-echo (when xesam-debug xesam-xml-string)))))))
504 (when (not (called-interactively-p 'interactive))
505 ;; Initialize buffer.
506 (setq buffer-read-only t)
507 (let ((inhibit-read-only t))
508 (erase-buffer))))
510 ;; It doesn't make sense to call it interactively.
511 (put 'xesam-mode 'disabled t)
513 ;; The very first buffer created with `xesam-mode' does not have the
514 ;; keymap etc. So we create a dummy buffer. Stupid.
515 (with-temp-buffer (xesam-mode))
517 (define-minor-mode xesam-minor-mode
518 "Toggle Xesam minor mode.
519 With no argument, this command toggles the mode.
520 Non-null prefix argument turns on the mode.
521 Null prefix argument turns off the mode.
523 When Xesam minor mode is enabled, all text which matches a
524 previous Xesam query in this buffer is highlighted."
525 :group 'xesam
526 :init-value nil
527 :lighter " Xesam"
528 (when (local-variable-p 'xesam-query)
529 ;; Run only if the buffer is related to a Xesam search.
530 (save-excursion
531 (if xesam-minor-mode
532 ;; Highlight hits.
533 (let ((query-regexp (regexp-opt (split-string xesam-query nil t) t))
534 (case-fold-search t))
535 ;; I have no idea whether people will like setting
536 ;; `isearch-case-fold-search' and `query-regexp'. Maybe
537 ;; this shall be controlled by a custom option.
538 (unless isearch-case-fold-search (isearch-toggle-case-fold))
539 (isearch-update-ring query-regexp t)
540 ;; Create overlays.
541 (goto-char (point-min))
542 (while (re-search-forward query-regexp nil t)
543 (overlay-put
544 (make-overlay
545 (match-beginning 0) (match-end 0)) 'face 'xesam-highlight)))
546 ;; Remove overlays.
547 (dolist (ov (overlays-in (point-min) (point-max)))
548 (delete-overlay ov))))))
550 (defun xesam-buffer-name (service search)
551 "Return the buffer name where to present search results.
552 SERVICE is the D-Bus unique service name of the Xesam search engine.
553 SEARCH is the search identification in that engine. Both must be strings."
554 (format "*%s/%s*" service search))
556 (defun xesam-highlight-string (string)
557 "Highlight text enclosed by <b> and </b>.
558 Return propertized STRING."
559 (while (string-match "\\(.*\\)\\(<b>\\)\\(.*\\)\\(</b>\\)\\(.*\\)" string)
560 (setq string
561 (format
562 "%s%s%s"
563 (match-string 1 string)
564 (propertize (match-string 3 string) 'face 'xesam-highlight)
565 (match-string 5 string))))
566 string)
568 (defun xesam-refresh-entry (engine entry)
569 "Refreshes one entry in the search buffer."
570 (let* ((result (nth (1- xesam-current) xesam-objects))
571 widget)
573 ;; Create widget.
574 (setq widget (widget-convert 'link))
575 (when xesam-debug
576 (widget-put widget :help-echo ""))
578 ;; Take all results.
579 (dolist (field (xesam-get-cached-property engine "hit.fields"))
580 (when (cond
581 ((stringp (caar result)) (not (zerop (length (caar result)))))
582 ((numberp (caar result)) (not (zerop (caar result))))
583 ((caar result) t))
584 (when xesam-debug
585 (widget-put
586 widget :help-echo
587 (format "%s%s: %s\n"
588 (widget-get widget :help-echo) field (caar result))))
589 (widget-put widget (intern (concat ":" field)) (caar result)))
590 (setq result (cdr result)))
592 ;; Strigi doesn't return URLs in xesam:url. We must fix this.
593 (when
594 (not (url-type (url-generic-parse-url (widget-get widget :xesam:url))))
595 (widget-put
596 widget :xesam:url (concat "file://" (widget-get widget :xesam:url))))
598 ;; Strigi returns xesam:size as string. We must fix this.
599 (when (and (widget-member widget :xesam:size)
600 (stringp (widget-get widget :xesam:size)))
601 (widget-put
602 widget :xesam:size (string-to-number (widget-get widget :xesam:url))))
604 ;; First line: :tag.
605 (cond
606 ((widget-member widget :xesam:title)
607 (widget-put widget :tag (widget-get widget :xesam:title)))
608 ((widget-member widget :xesam:subject)
609 (widget-put widget :tag (widget-get widget :xesam:subject)))
610 ((widget-member widget :xesam:mimeType)
611 (widget-put widget :tag (widget-get widget :xesam:mimeType)))
612 ((widget-member widget :xesam:name)
613 (widget-put widget :tag (widget-get widget :xesam:name))))
615 ;; Highlight the search items.
616 (when (widget-member widget :tag)
617 (widget-put
618 widget :tag (xesam-highlight-string (widget-get widget :tag))))
620 ;; Last Modified.
621 (when (and (widget-member widget :xesam:sourceModified)
622 (not
623 (zerop
624 (string-to-number (widget-get widget :xesam:sourceModified)))))
625 (widget-put
626 widget :tag
627 (format
628 "%s\nLast Modified: %s"
629 (or (widget-get widget :tag) "")
630 (format-time-string
631 "%d %B %Y, %T"
632 (seconds-to-time
633 (string-to-number (widget-get widget :xesam:sourceModified)))))))
635 ;; Second line: :value.
636 (widget-put widget :value (widget-get widget :xesam:url))
638 (cond
639 ;; A search engine can set `xesam-notify-function' via
640 ;; `xesam-mode-hooks'.
641 (xesam-notify-function
642 (widget-put widget :notify xesam-notify-function))
644 ;; In case of HTML, we use a URL link.
645 ((and (widget-member widget :xesam:mimeType)
646 (string-equal "text/html" (widget-get widget :xesam:mimeType)))
647 (setcar widget 'url-link))
649 ;; For local files, we will open the file as default action.
650 ((string-match "file"
651 (url-type (url-generic-parse-url
652 (widget-get widget :xesam:url))))
653 (widget-put
654 widget :notify
655 (lambda (widget &rest ignore)
656 (let ((query xesam-query))
657 (find-file
658 (url-filename (url-generic-parse-url (widget-value widget))))
659 (set (make-local-variable 'xesam-query) query)
660 (xesam-minor-mode 1))))
661 (widget-put
662 widget :value
663 (url-filename (url-generic-parse-url (widget-get widget :xesam:url))))))
665 ;; Third line: :doc.
666 (cond
667 ((widget-member widget :xesam:summary)
668 (widget-put widget :doc (widget-get widget :xesam:summary)))
669 ((widget-member widget :xesam:snippet)
670 (widget-put widget :doc (widget-get widget :xesam:snippet))))
672 (when (widget-member widget :doc)
673 (with-temp-buffer
674 (insert
675 (xesam-highlight-string (widget-get widget :doc)))
676 (fill-region-as-paragraph (point-min) (point-max))
677 (widget-put widget :doc (buffer-string)))
678 (widget-put widget :help-echo (widget-get widget :doc)))
680 ;; Format the widget.
681 (widget-put
682 widget :format
683 (format "%d. %s%%[%%v%%]\n%s\n" xesam-current
684 (if (widget-member widget :tag) "%{%t%}\n" "")
685 (if (widget-member widget :doc) "%h" "")))
687 ;; Write widget.
688 (goto-char (point-max))
689 (widget-default-create widget)
690 (set-buffer-modified-p nil)
691 (force-mode-line-update)
692 (redisplay)))
694 (defun xesam-get-hits (engine search hits)
695 "Retrieve hits from ENGINE."
696 (with-current-buffer (xesam-buffer-name (car engine) search)
697 (setq xesam-objects
698 (append xesam-objects
699 (xesam-dbus-call-method
700 :session (car engine) xesam-path-search
701 xesam-interface-search "GetHits" search hits)))))
703 (defun xesam-refresh-search-buffer (engine search)
704 "Refreshes the buffer, presenting results of SEARCH."
705 (with-current-buffer (xesam-buffer-name (car engine) search)
706 ;; Work only if nobody else is here.
707 (unless (or xesam-refreshing (>= xesam-current xesam-to))
708 (setq xesam-refreshing t)
709 (unwind-protect
710 (let (widget)
712 ;; Retrieve needed hits for visualization.
713 (while (> (min xesam-to xesam-count) (length xesam-objects))
714 (xesam-get-hits
715 engine search
716 (min xesam-hits-per-page
717 (- (min xesam-to xesam-count) (length xesam-objects)))))
719 ;; Add all result widgets.
720 (while (< xesam-current (min xesam-to xesam-count))
721 (setq xesam-current (1+ xesam-current))
722 (xesam-refresh-entry engine search))
724 ;; Add "NEXT" widget.
725 (when (> xesam-count xesam-to)
726 (goto-char (point-max))
727 (widget-create
728 'link
729 :notify
730 (lambda (widget &rest ignore)
731 (setq xesam-to (+ xesam-to xesam-hits-per-page))
732 (widget-delete widget)
733 (xesam-refresh-search-buffer xesam-engine xesam-search))
734 "NEXT")
735 (widget-beginning-of-line))
737 ;; Prefetch next hits.
738 (when (> (min (+ xesam-hits-per-page xesam-to) xesam-count)
739 (length xesam-objects))
740 (xesam-get-hits
741 engine search
742 (min xesam-hits-per-page
743 (- (min (+ xesam-hits-per-page xesam-to) xesam-count)
744 (length xesam-objects)))))
746 ;; Add "DONE" widget.
747 (when (= xesam-current xesam-count)
748 (goto-char (point-max))
749 (widget-create 'link :notify 'ignore "DONE")
750 (widget-beginning-of-line)))
752 ;; Return with save settings.
753 (setq xesam-refreshing nil)))))
756 ;;; Search functions.
758 (defun xesam-signal-handler (&rest args)
759 "Handles the different D-Bus signals of a Xesam search."
760 (let* ((service (dbus-event-service-name last-input-event))
761 (member (dbus-event-member-name last-input-event))
762 (search (nth 0 args))
763 (buffer (xesam-buffer-name service search)))
765 (when (get-buffer buffer)
766 (with-current-buffer buffer
767 (cond
769 ((string-equal member "HitsAdded")
770 (setq xesam-count (+ xesam-count (nth 1 args)))
771 ;; We use `run-at-time' in order to not block the event queue.
772 (run-at-time
773 0 nil
774 'xesam-refresh-search-buffer
775 (assoc service xesam-search-engines) search))
777 ((string-equal member "SearchDone")
778 (setq mode-line-process
779 (propertize " Done" 'face 'xesam-mode-line))
780 (force-mode-line-update)))))))
782 (defun xesam-kill-buffer-function ()
783 "Send the CloseSearch indication."
784 (when (and (eq major-mode 'xesam-mode) (stringp xesam-search))
785 (ignore-errors ;; The D-Bus service could have disappeared.
786 (xesam-dbus-call-method
787 :session (car xesam-engine) xesam-path-search
788 xesam-interface-search "CloseSearch" xesam-search))))
790 (defun xesam-new-search (engine type query)
791 "Create a new search session.
792 ENGINE identifies the search engine. TYPE is the query type, it
793 can be either `fulltext-query', or `user-query'. QUERY is a
794 string in the Xesam query language. A string, identifying the
795 search, is returned."
796 (let* ((service (car engine))
797 (session (xesam-get-cached-property engine "session"))
798 (xml-string
799 (format
800 (if (eq type 'user-query) xesam-user-query xesam-fulltext-query)
801 (url-insert-entities-in-string query)))
802 (search (xesam-dbus-call-method
803 :session service xesam-path-search
804 xesam-interface-search "NewSearch" session xml-string)))
806 ;; Let us notify for relevant signals. We ignore "HitsRemoved",
807 ;; "HitsModified" and "StateChanged"; there is nothing to do for
808 ;; us.
809 (dbus-register-signal
810 :session service xesam-path-search
811 xesam-interface-search "HitsAdded"
812 'xesam-signal-handler search)
813 (dbus-register-signal
814 :session service xesam-path-search
815 xesam-interface-search "SearchDone"
816 'xesam-signal-handler search)
818 ;; Create the search buffer.
819 (with-current-buffer
820 (generate-new-buffer (xesam-buffer-name service search))
821 (switch-to-buffer-other-window (current-buffer))
822 ;; Inialize buffer with `xesam-mode'. `xesam-vendor' must be
823 ;; set before calling `xesam-mode', because we want to give the
824 ;; hook functions a chance to identify their search engine.
825 (setq xesam-vendor (xesam-get-cached-property engine "vendor.id"))
826 (xesam-mode)
827 (setq xesam-engine engine
828 xesam-search search
829 ;; `xesam-type', `xesam-query' and `xesam-xml-string'
830 ;; are displayed in the header line.
831 xesam-type (symbol-name type)
832 xesam-query query
833 xesam-xml-string xml-string
834 xesam-objects nil
835 ;; The buffer identification shall indicate the search
836 ;; engine. The `help-echo' property is used for debug
837 ;; information, when applicable.
838 mode-line-buffer-identification
839 (if (not xesam-debug)
840 (list 12 (propertized-buffer-identification xesam-vendor))
841 (propertize
842 xesam-vendor
843 'help-echo
844 (mapconcat
845 (lambda (x)
846 (format "%s: %s" x (xesam-get-cached-property engine x)))
847 '("vendor.id" "vendor.version" "vendor.display" "vendor.xesam"
848 "vendor.ontology.fields" "vendor.ontology.contents"
849 "vendor.ontology.sources" "vendor.extensions"
850 "vendor.ontologies" "vendor.maxhits")
851 "\n"))))
852 (add-hook 'kill-buffer-hook 'xesam-kill-buffer-function)
853 (force-mode-line-update))
855 ;; Start the search.
856 (xesam-dbus-call-method
857 :session (car engine) xesam-path-search
858 xesam-interface-search "StartSearch" search)
860 ;; Return search id.
861 search))
863 ;;;###autoload
864 (defun xesam-search (engine query)
865 "Perform an interactive search.
866 ENGINE is the Xesam search engine to be applied, it must be one of the
867 entries of `xesam-search-engines'. QUERY is the search string in the
868 Xesam user query language. If the search engine does not support
869 the Xesam user query language, a Xesam fulltext search is applied.
871 The default search engine is the first entry in `xesam-search-engines'.
872 Example:
874 (xesam-search (car (xesam-search-engines)) \"emacs\")"
875 (interactive
876 (let* ((vendors (mapcar
877 (lambda (x) (xesam-get-cached-property x "vendor.display"))
878 (xesam-search-engines)))
879 (vendor
880 (if (> (length vendors) 1)
881 (completing-read
882 "Enter search engine: " vendors nil t
883 (try-completion "" vendors) 'xesam-minibuffer-vendor-history)
884 (car vendors))))
885 (list
886 ;; ENGINE.
887 (when vendor
888 (dolist (elt (xesam-search-engines) engine)
889 (when (string-equal
890 (xesam-get-cached-property elt "vendor.display") vendor)
891 (setq engine elt))))
892 ;; QUERY.
893 (when vendor
894 (read-from-minibuffer
895 "Enter search string: " nil nil nil
896 'xesam-minibuffer-query-history)))))
898 (if (null engine)
899 (message "No search engine running")
900 (if (zerop (length query))
901 (message "No query applied")
902 (xesam-new-search engine xesam-query-type query))))
904 (provide 'xesam)
906 ;;; TODO:
908 ;; * Buffer highlighting needs better analysis of query string.
909 ;; * Accept input while retrieving prefetched hits. `run-at-time'?
910 ;; * With prefix, let's choose search engine.
911 ;; * Minibuffer completion for user queries.
912 ;; * `revert-buffer-function' implementation.
914 ;; * Mid term
915 ;; - If available, use ontologies for field selection.
916 ;; - Search engines for Emacs bugs database, wikipedia, google,
917 ;; yahoo, ebay, ...
918 ;; - Construct complex queries via widgets, like in mairix.el.
920 ;;; xesam.el ends here