Spelling fixes.
[bpt/emacs.git] / lisp / net / xesam.el
CommitLineData
24008bc4
MA
1;;; xesam.el --- Xesam interface to search engines.
2
73b0cd50 3;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
24008bc4
MA
4
5;; Author: Michael Albinus <michael.albinus@gmx.de>
6;; Keywords: tools, hypermedia
7
8;; This file is part of GNU Emacs.
9
5d4cc458 10;; GNU Emacs is free software: you can redistribute it and/or modify
24008bc4 11;; it under the terms of the GNU General Public License as published by
5d4cc458
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
24008bc4
MA
14
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.
19
20;; You should have received a copy of the GNU General Public License
5d4cc458 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24008bc4
MA
22
23;;; Commentary:
24
3cf235eb 25;; This package provides an interface to Xesam, a D-Bus based "eXtEnsible
24008bc4
MA
26;; Search And Metadata specification". It has been tested with
27;;
28;; xesam-glib 0.3.4, xesam-tools 0.6.1
29;; beagle 0.3.7, beagle-xesam 0.2
5dd33078 30;; strigi 0.5.11
24008bc4
MA
31
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
3cf235eb 35;; running, which supports the Xesam interface. Beagle and strigi have
24008bc4
MA
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
38;;
39;; (dbus-list-queued-owners :session "org.freedesktop.xesam.searcher")
40
41;; In order to start a search, you must load xesam.el:
42;;
43;; (require 'xesam)
44
45;; xesam.el supports two types of queries, which are explained *very* short:
46;;
47;; * Full text queries. Just search keys shall be given, like
48;;
49;; hello world
50;;
51;; A full text query in xesam.el is restricted to files.
52;;
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.
56;;
57;; A query string consists of search keys, collectors, selectors,
58;; and phrases. Search keys are words like in a full text query:
59;;
60;; hello word
61;;
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;; "<=", ">=", "<", ">"):
69;;
70;; type:attachment ext=el
71;;
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".
75;;
76;; albinus -type:file
77;;
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):
82;;
83;; "Hello world"c
84
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.
88;;
89;; (setq xesam-query-type 'fulltext-query)
90;;
e1dbe924 91;; Another option to be customized is the number of hits to be
24008bc4
MA
92;; presented at once.
93;;
94;; (setq xesam-hits-per-page 50)
95
96;; A search can be started by the command
97;;
98;; M-x xesam-search
99;;
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.
103
17668903
MA
104;; Search results are presented in a new buffer. This buffer has the
105;; major mode `xesam-mode', with the following keybindings:
106
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'
114
115;; The search results are represented by widgets. Navigation commands
116;; are the usual widget navigation commands:
117
118;; TAB `widget-forward'
119;; <backtab> `widget-backward'
120
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).
127
24008bc4
MA
128;;; Code:
129
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")
134
135(require 'dbus)
136
137;; Pacify byte compiler.
138(eval-when-compile
139 (require 'cl))
140
141;; Widgets are used to highlight the search results.
142(require 'widget)
4edefb46 143(require 'wid-edit)
24008bc4
MA
144
145;; `run-at-time' is used in the signal handler.
146(require 'timer)
147
148;; The default search field is "xesam:url". It must be inspected.
149(require 'url)
150
151(defgroup xesam nil
152 "Xesam compatible interface to search engines."
153 :group 'extensions
26f4b8ab 154 :group 'comm
24008bc4
MA
155 :version "23.1")
156
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)))
163
164(defcustom xesam-hits-per-page 20
4edefb46 165 "Number of search hits to be displayed in the result buffer."
24008bc4
MA
166 :group 'xesam
167 :type 'integer)
168
4edefb46
MA
169(defface xesam-mode-line '((t :inherit mode-line-emphasis))
170 "Face to highlight mode line."
171 :group 'xesam)
172
173(defface xesam-highlight '((t :inherit match))
174 "Face to highlight query entries.
175It will be overlayed by `widget-documentation-face', so it shall
176be different at least in one face property not set in that face."
177 :group 'xesam)
178
24008bc4 179(defvar xesam-debug nil
de8bb89e 180 "Insert debug information in the help echo.")
24008bc4
MA
181
182(defconst xesam-service-search "org.freedesktop.xesam.searcher"
183 "The D-Bus name used to talk to Xesam.")
184
185(defconst xesam-path-search "/org/freedesktop/xesam/searcher/main"
186 "The D-Bus object path used to talk to Xesam.")
187
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.")
195
196(defconst xesam-all-fields
818f12ce
MA
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"
24008bc4
MA
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.
249This defconst can be used to check for a new search engine, which
250fields are supported.")
251
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>
256 %s
257 </userQuery>
258</request>"
259 "The Xesam user query XML.")
260
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.")
271
f0e35aeb
GM
272(declare-function dbus-get-unique-name "dbusbind.c" (bus))
273
818f12ce
MA
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.")
278
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
282performant. If the target D-Bus service is owned by Emacs, this
283is not applicable, and `dbus-call-method-non-blocking' must be
284used instead. ARGS are identical to the argument list of both
285functions."
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))
292
24008bc4
MA
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.
818f12ce 296 (car (xesam-dbus-call-method
24008bc4
MA
297 :session (car engine) xesam-path-search
298 xesam-interface-search "GetProperty"
818f12ce 299 (xesam-get-cached-property engine "session") property)))
24008bc4
MA
300
301(defun xesam-set-property (engine property value)
302 "Set the PROPERTY of ENGINE to VALUE.
303VALUE can be a string, a non-negative integer, a boolean
304value (nil or t), or a list of them. It returns the new value of
305PROPERTY in the search engine. This new value can be different
306from VALUE, depending on what the search engine accepts."
307 ;; "SetProperty" returns a variant, so we must use the car.
818f12ce 308 (car (xesam-dbus-call-method
24008bc4
MA
309 :session (car engine) xesam-path-search
310 xesam-interface-search "SetProperty"
818f12ce 311 (xesam-get-cached-property engine "session") property
24008bc4
MA
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))))
317
318(defvar xesam-minibuffer-vendor-history nil
319 "Interactive vendor history.")
320
321(defvar xesam-minibuffer-query-history nil
322 "Interactive query history.")
323
324;; Pacify byte compiler.
96038f81
MA
325(defvar xesam-vendor nil)
326(make-variable-buffer-local 'xesam-vendor)
327(put 'xesam-vendor 'permanent-local t)
328
24008bc4
MA
329(defvar xesam-engine nil)
330(defvar xesam-search nil)
5dd33078
MA
331(defvar xesam-type nil)
332(defvar xesam-query nil)
333(defvar xesam-xml-string nil)
4edefb46 334(defvar xesam-objects nil)
24008bc4
MA
335(defvar xesam-current nil)
336(defvar xesam-count nil)
24008bc4 337(defvar xesam-to nil)
96038f81 338(defvar xesam-notify-function nil)
24008bc4
MA
339(defvar xesam-refreshing nil)
340
341\f
342;;; Search engines.
343
344(defvar xesam-search-engines nil
345 "List of available Xesam search engines.
818f12ce
MA
346Every entry is an association list, with a car denoting the
347unique D-Bus service name of the engine. The rest of the entry
348are cached associations of engine attributes, like the session
349identifier, and the display name. Example:
350
351 \(\(\":1.59\"
352 \(\"session\" . \"0t1214948020ut358230u0p2698r3912347765k3213849828\")
353 \(\"vendor.display\" . \"Tracker Xesam Service\"))
354 \(\":1.27\"
355 \(\"session\" . \"strigisession1369133069\")
356 \(\"vendor.display\" . \"Strigi Desktop Search\")))
24008bc4
MA
357
358A Xesam-compatible search engine is identified as a queued D-Bus
818f12ce
MA
359service of the known service `xesam-service-search'.")
360
361(defun xesam-get-cached-property (engine property)
362 "Return the PROPERTY value of ENGINE from the cache.
363If 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)))
370
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)))))
24008bc4
MA
374
375(defun xesam-delete-search-engine (&rest args)
818f12ce
MA
376 "Remove service from `xesam-search-engines'."
377 (setq xesam-search-engines
378 (delete (assoc (car args) xesam-search-engines) xesam-search-engines)))
24008bc4 379
f0e35aeb
GM
380(defvar dbus-debug)
381
24008bc4
MA
382(defun xesam-search-engines ()
383 "Return Xesam search engines, stored in `xesam-search-engines'.
384The first search engine is the name owner of `xesam-service-search'.
385If 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)
392
393 ;; Open a new session, and add it to the search engines list.
818f12ce
MA
394 (add-to-list 'xesam-search-engines (list service) 'append)
395 (setq engine (assoc service xesam-search-engines))
396
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"))
403
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)
24008bc4
MA
407
408 ;; Check the vendor properties.
409 (setq vendor-id (xesam-get-property engine "vendor.id")
410 hit-fields (xesam-get-property engine "hit.fields"))
411
8350f087 412 ;; Usually, `hit.fields' shall describe supported fields.
24008bc4
MA
413 ;; That is not the case now, so we set it ourselves.
414 ;; Hopefully, this will change later.
415 (setq hit-fields
3cf235eb 416 (case (intern vendor-id)
0adf5618 417 (Beagle
3cf235eb 418 '("xesam:mimeType" "xesam:url"))
0adf5618 419 (Strigi
3cf235eb
MA
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"))
0adf5618 426 (TrackerXesamSession
3cf235eb 427 '("xesam:relevancyRating" "xesam:url"))
0adf5618 428 (Debbugs
3cf235eb
MA
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"))))
24008bc4
MA
435
436 (xesam-set-property engine "hit.fields" hit-fields)
437 (xesam-set-property engine "hit.fields.extended" '("xesam:snippet"))
438
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)
445
446\f
447;;; Search buffers.
448
abef340a
SS
449(defvar xesam-mode-map
450 (let ((map (copy-keymap special-mode-map)))
451 (set-keymap-parent xesam-mode-map widget-keymap)
452 map))
453
454(define-derived-mode xesam-mode special-mode "Xesam"
24008bc4
MA
455 "Major mode for presenting search results of a Xesam search.
456In this mode, widgets represent the search results.
457
458\\{xesam-mode-map}
96038f81
MA
459Turning on Xesam mode runs the normal hook `xesam-mode-hook'. It
460can be used to set `xesam-notify-function', which must a search
461engine specific, widget :notify function to visualize xesam:url."
462 (set (make-local-variable 'xesam-notify-function) nil)
5dd33078
MA
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) "")
4edefb46 472 (set (make-local-variable 'xesam-objects) nil)
5dd33078
MA
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)
96038f81
MA
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)
5dd33078
MA
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: "
4edefb46 495 (propertize xesam-type 'face 'xesam-mode-line))))
5dd33078
MA
496 '(10
497 (:eval
498 (list " Query: "
499 (propertize
500 xesam-query
4edefb46 501 'face 'xesam-mode-line
818f12ce 502 'help-echo (when xesam-debug xesam-xml-string)))))))
5dd33078 503
32226619 504 (when (not (called-interactively-p 'interactive))
de8bb89e
MA
505 ;; Initialize buffer.
506 (setq buffer-read-only t)
507 (let ((inhibit-read-only t))
5dd33078
MA
508 (erase-buffer))))
509
510;; It doesn't make sense to call it interactively.
511(put 'xesam-mode 'disabled t)
24008bc4 512
4edefb46
MA
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))
516
17668903
MA
517(define-minor-mode xesam-minor-mode
518 "Toggle Xesam minor mode.
ac6c8639
CY
519With a prefix argument ARG, enable Xesam minor mode if ARG is
520positive, and disable it otherwise. If called from Lisp, enable
521the mode if ARG is omitted or nil.
17668903
MA
522
523When Xesam minor mode is enabled, all text which matches a
524previous 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))))))
549
24008bc4
MA
550(defun xesam-buffer-name (service search)
551 "Return the buffer name where to present search results.
552SERVICE is the D-Bus unique service name of the Xesam search engine.
553SEARCH is the search identification in that engine. Both must be strings."
554 (format "*%s/%s*" service search))
555
4edefb46 556(defun xesam-highlight-string (string)
f7a17e30
MA
557 "Highlight text enclosed by <b> and </b>.
558Return propertized STRING."
4edefb46
MA
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)
567
568(defun xesam-refresh-entry (engine entry)
24008bc4 569 "Refreshes one entry in the search buffer."
4edefb46 570 (let* ((result (nth (1- xesam-current) xesam-objects))
24008bc4
MA
571 widget)
572
573 ;; Create widget.
574 (setq widget (widget-convert 'link))
de8bb89e
MA
575 (when xesam-debug
576 (widget-put widget :help-echo ""))
24008bc4
MA
577
578 ;; Take all results.
818f12ce 579 (dolist (field (xesam-get-cached-property engine "hit.fields"))
4edefb46
MA
580 (when (cond
581 ((stringp (caar result)) (not (zerop (length (caar result)))))
582 ((numberp (caar result)) (not (zerop (caar result))))
583 ((caar result) t))
24008bc4 584 (when xesam-debug
de8bb89e
MA
585 (widget-put
586 widget :help-echo
587 (format "%s%s: %s\n"
588 (widget-get widget :help-echo) field (caar result))))
24008bc4
MA
589 (widget-put widget (intern (concat ":" field)) (caar result)))
590 (setq result (cdr result)))
591
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))))
597
4edefb46
MA
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))))
603
24008bc4
MA
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))))
614
4edefb46
MA
615 ;; Highlight the search items.
616 (when (widget-member widget :tag)
617 (widget-put
618 widget :tag (xesam-highlight-string (widget-get widget :tag))))
619
24008bc4 620 ;; Last Modified.
f7a17e30
MA
621 (when (and (widget-member widget :xesam:sourceModified)
622 (not
623 (zerop
624 (string-to-number (widget-get widget :xesam:sourceModified)))))
24008bc4
MA
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)))))))
634
635 ;; Second line: :value.
636 (widget-put widget :value (widget-get widget :xesam:url))
637
638 (cond
96038f81
MA
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))
643
24008bc4
MA
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))
648
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
c7041c35 655 (lambda (widget &rest ignore)
f7a17e30
MA
656 (let ((query xesam-query))
657 (find-file
658 (url-filename (url-generic-parse-url (widget-value widget))))
17668903
MA
659 (set (make-local-variable 'xesam-query) query)
660 (xesam-minor-mode 1))))
24008bc4
MA
661 (widget-put
662 widget :value
663 (url-filename (url-generic-parse-url (widget-get widget :xesam:url))))))
664
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))))
671
672 (when (widget-member widget :doc)
24008bc4 673 (with-temp-buffer
4edefb46
MA
674 (insert
675 (xesam-highlight-string (widget-get widget :doc)))
24008bc4 676 (fill-region-as-paragraph (point-min) (point-max))
4edefb46
MA
677 (widget-put widget :doc (buffer-string)))
678 (widget-put widget :help-echo (widget-get widget :doc)))
24008bc4
MA
679
680 ;; Format the widget.
681 (widget-put
682 widget :format
de8bb89e 683 (format "%d. %s%%[%%v%%]\n%s\n" xesam-current
24008bc4
MA
684 (if (widget-member widget :tag) "%{%t%}\n" "")
685 (if (widget-member widget :doc) "%h" "")))
686
687 ;; Write widget.
688 (goto-char (point-max))
689 (widget-default-create widget)
690 (set-buffer-modified-p nil)
de8bb89e 691 (force-mode-line-update)
24008bc4
MA
692 (redisplay)))
693
4edefb46
MA
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)))))
702
24008bc4
MA
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.
4edefb46 707 (unless (or xesam-refreshing (>= xesam-current xesam-to))
24008bc4
MA
708 (setq xesam-refreshing t)
709 (unwind-protect
4edefb46
MA
710 (let (widget)
711
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)))))
718
719 ;; Add all result widgets.
de8bb89e 720 (while (< xesam-current (min xesam-to xesam-count))
4edefb46 721 (setq xesam-current (1+ xesam-current))
de8bb89e 722 (xesam-refresh-entry engine search))
24008bc4
MA
723
724 ;; Add "NEXT" widget.
4edefb46 725 (when (> xesam-count xesam-to)
24008bc4
MA
726 (goto-char (point-max))
727 (widget-create
728 'link
729 :notify
c7041c35
MA
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))
24008bc4 734 "NEXT")
4edefb46
MA
735 (widget-beginning-of-line))
736
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)
c7041c35 744 (length xesam-objects)))))
24008bc4 745
3cf235eb
MA
746 ;; Add "DONE" widget.
747 (when (= xesam-current xesam-count)
748 (goto-char (point-max))
749 (widget-create 'link :notify 'ignore "DONE")
c7041c35 750 (widget-beginning-of-line)))
3cf235eb 751
24008bc4
MA
752 ;; Return with save settings.
753 (setq xesam-refreshing nil)))))
754
755\f
756;;; Search functions.
757
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)))
764
765 (when (get-buffer buffer)
766 (with-current-buffer buffer
767 (cond
768
769 ((string-equal member "HitsAdded")
de8bb89e 770 (setq xesam-count (+ xesam-count (nth 1 args)))
24008bc4
MA
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))
776
777 ((string-equal member "SearchDone")
778 (setq mode-line-process
4edefb46 779 (propertize " Done" 'face 'xesam-mode-line))
24008bc4
MA
780 (force-mode-line-update)))))))
781
4edefb46
MA
782(defun xesam-kill-buffer-function ()
783 "Send the CloseSearch indication."
784 (when (and (eq major-mode 'xesam-mode) (stringp xesam-search))
30fe660e
MA
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))))
4edefb46 789
5dd33078 790(defun xesam-new-search (engine type query)
24008bc4 791 "Create a new search session.
5dd33078
MA
792ENGINE identifies the search engine. TYPE is the query type, it
793can be either `fulltext-query', or `user-query'. QUERY is a
794string in the Xesam query language. A string, identifying the
795search, is returned."
24008bc4 796 (let* ((service (car engine))
818f12ce 797 (session (xesam-get-cached-property engine "session"))
5dd33078
MA
798 (xml-string
799 (format
800 (if (eq type 'user-query) xesam-user-query xesam-fulltext-query)
c7041c35 801 (url-insert-entities-in-string query)))
818f12ce 802 (search (xesam-dbus-call-method
24008bc4 803 :session service xesam-path-search
5dd33078 804 xesam-interface-search "NewSearch" session xml-string)))
de8bb89e 805
24008bc4
MA
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)
de8bb89e 817
24008bc4
MA
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))
96038f81
MA
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"))
24008bc4
MA
826 (xesam-mode)
827 (setq xesam-engine engine
828 xesam-search search
5dd33078
MA
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
4edefb46 834 xesam-objects nil
de8bb89e
MA
835 ;; The buffer identification shall indicate the search
836 ;; engine. The `help-echo' property is used for debug
837 ;; information, when applicable.
24008bc4 838 mode-line-buffer-identification
de8bb89e 839 (if (not xesam-debug)
96038f81 840 (list 12 (propertized-buffer-identification xesam-vendor))
de8bb89e 841 (propertize
96038f81 842 xesam-vendor
818f12ce 843 'help-echo
de8bb89e 844 (mapconcat
c7041c35
MA
845 (lambda (x)
846 (format "%s: %s" x (xesam-get-cached-property engine x)))
de8bb89e
MA
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")
5dd33078 851 "\n"))))
4edefb46
MA
852 (add-hook 'kill-buffer-hook 'xesam-kill-buffer-function)
853 (force-mode-line-update))
5dd33078
MA
854
855 ;; Start the search.
818f12ce 856 (xesam-dbus-call-method
5dd33078
MA
857 :session (car engine) xesam-path-search
858 xesam-interface-search "StartSearch" search)
24008bc4
MA
859
860 ;; Return search id.
861 search))
862
3cf235eb 863;;;###autoload
24008bc4
MA
864(defun xesam-search (engine query)
865 "Perform an interactive search.
866ENGINE is the Xesam search engine to be applied, it must be one of the
867entries of `xesam-search-engines'. QUERY is the search string in the
868Xesam user query language. If the search engine does not support
869the Xesam user query language, a Xesam fulltext search is applied.
870
871The default search engine is the first entry in `xesam-search-engines'.
872Example:
873
874 (xesam-search (car (xesam-search-engines)) \"emacs\")"
875 (interactive
876 (let* ((vendors (mapcar
c7041c35 877 (lambda (x) (xesam-get-cached-property x "vendor.display"))
24008bc4
MA
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)
818f12ce
MA
889 (when (string-equal
890 (xesam-get-cached-property elt "vendor.display") vendor)
24008bc4
MA
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)))))
897
5dd33078
MA
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))))
24008bc4
MA
903
904(provide 'xesam)
905
906;;; TODO:
907
f7a17e30 908;; * Buffer highlighting needs better analysis of query string.
4edefb46 909;; * Accept input while retrieving prefetched hits. `run-at-time'?
818f12ce 910;; * With prefix, let's choose search engine.
24008bc4 911;; * Minibuffer completion for user queries.
de8bb89e 912;; * `revert-buffer-function' implementation.
de8bb89e 913;;
24008bc4
MA
914;; * Mid term
915;; - If available, use ontologies for field selection.
916;; - Search engines for Emacs bugs database, wikipedia, google,
917;; yahoo, ebay, ...
4edefb46 918;; - Construct complex queries via widgets, like in mairix.el.
24008bc4
MA
919
920;;; xesam.el ends here