Home | History | Annotate | Line # | Download | only in makemandb
apropos-utils.c revision 1.15
      1  1.15  christos /*	$NetBSD: apropos-utils.c,v 1.15 2013/04/02 17:16:50 christos Exp $	*/
      2   1.1     joerg /*-
      3   1.1     joerg  * Copyright (c) 2011 Abhinav Upadhyay <er.abhinav.upadhyay (at) gmail.com>
      4   1.1     joerg  * All rights reserved.
      5   1.1     joerg  *
      6   1.1     joerg  * This code was developed as part of Google's Summer of Code 2011 program.
      7   1.1     joerg  *
      8   1.1     joerg  * Redistribution and use in source and binary forms, with or without
      9   1.1     joerg  * modification, are permitted provided that the following conditions
     10   1.1     joerg  * are met:
     11   1.1     joerg  *
     12   1.1     joerg  * 1. Redistributions of source code must retain the above copyright
     13   1.1     joerg  *    notice, this list of conditions and the following disclaimer.
     14   1.1     joerg  * 2. Redistributions in binary form must reproduce the above copyright
     15   1.1     joerg  *    notice, this list of conditions and the following disclaimer in
     16   1.1     joerg  *    the documentation and/or other materials provided with the
     17   1.1     joerg  *    distribution.
     18   1.1     joerg  *
     19   1.1     joerg  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     20   1.1     joerg  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     21   1.1     joerg  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     22   1.1     joerg  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
     23   1.1     joerg  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     24   1.1     joerg  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
     25   1.1     joerg  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     26   1.1     joerg  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     27   1.1     joerg  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     28   1.1     joerg  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     29   1.1     joerg  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30   1.1     joerg  * SUCH DAMAGE.
     31   1.1     joerg  */
     32   1.1     joerg 
     33   1.1     joerg #include <sys/cdefs.h>
     34  1.15  christos __RCSID("$NetBSD: apropos-utils.c,v 1.15 2013/04/02 17:16:50 christos Exp $");
     35   1.1     joerg 
     36   1.7       wiz #include <sys/queue.h>
     37   1.1     joerg #include <sys/stat.h>
     38   1.1     joerg 
     39   1.1     joerg #include <assert.h>
     40   1.1     joerg #include <ctype.h>
     41   1.1     joerg #include <err.h>
     42   1.1     joerg #include <math.h>
     43   1.1     joerg #include <stdio.h>
     44   1.1     joerg #include <stdlib.h>
     45   1.1     joerg #include <string.h>
     46   1.1     joerg #include <util.h>
     47   1.1     joerg #include <zlib.h>
     48   1.9  christos #include <term.h>
     49   1.9  christos #undef tab	// XXX: manconf.h
     50   1.1     joerg 
     51   1.1     joerg #include "apropos-utils.h"
     52   1.7       wiz #include "manconf.h"
     53   1.8  christos #include "dist/mandoc.h"
     54   1.1     joerg #include "sqlite3.h"
     55   1.1     joerg 
     56   1.1     joerg typedef struct orig_callback_data {
     57   1.1     joerg 	void *data;
     58   1.1     joerg 	int (*callback) (void *, const char *, const char *, const char *,
     59   1.1     joerg 		const char *, size_t);
     60   1.1     joerg } orig_callback_data;
     61   1.1     joerg 
     62   1.1     joerg typedef struct inverse_document_frequency {
     63   1.1     joerg 	double value;
     64   1.1     joerg 	int status;
     65   1.1     joerg } inverse_document_frequency;
     66   1.1     joerg 
     67   1.1     joerg /* weights for individual columns */
     68   1.1     joerg static const double col_weights[] = {
     69   1.1     joerg 	2.0,	// NAME
     70   1.1     joerg 	2.00,	// Name-description
     71   1.1     joerg 	0.55,	// DESCRIPTION
     72   1.1     joerg 	0.10,	// LIBRARY
     73   1.1     joerg 	0.001,	//RETURN VALUES
     74   1.1     joerg 	0.20,	//ENVIRONMENT
     75   1.1     joerg 	0.01,	//FILES
     76   1.1     joerg 	0.001,	//EXIT STATUS
     77   1.1     joerg 	2.00,	//DIAGNOSTICS
     78   1.1     joerg 	0.05,	//ERRORS
     79   1.1     joerg 	0.00,	//md5_hash
     80   1.1     joerg 	1.00	//machine
     81   1.1     joerg };
     82   1.1     joerg 
     83   1.1     joerg /*
     84   1.1     joerg  * lower --
     85   1.1     joerg  *  Converts the string str to lower case
     86   1.1     joerg  */
     87   1.1     joerg char *
     88   1.1     joerg lower(char *str)
     89   1.1     joerg {
     90   1.1     joerg 	assert(str);
     91   1.1     joerg 	int i = 0;
     92   1.1     joerg 	char c;
     93   1.1     joerg 	while (str[i] != '\0') {
     94   1.1     joerg 		c = tolower((unsigned char) str[i]);
     95   1.1     joerg 		str[i++] = c;
     96   1.1     joerg 	}
     97   1.1     joerg 	return str;
     98   1.1     joerg }
     99   1.1     joerg 
    100   1.1     joerg /*
    101   1.1     joerg * concat--
    102  1.10  christos *  Utility function. Concatenates together: dst, a space character and src.
    103  1.10  christos * dst + " " + src
    104   1.1     joerg */
    105   1.1     joerg void
    106   1.1     joerg concat(char **dst, const char *src)
    107   1.1     joerg {
    108   1.1     joerg 	concat2(dst, src, strlen(src));
    109   1.1     joerg }
    110   1.1     joerg 
    111   1.1     joerg void
    112   1.1     joerg concat2(char **dst, const char *src, size_t srclen)
    113   1.1     joerg {
    114   1.1     joerg 	size_t total_len, dst_len;
    115   1.1     joerg 	assert(src != NULL);
    116   1.1     joerg 
    117   1.1     joerg 	/* If destination buffer dst is NULL, then simply strdup the source buffer */
    118   1.1     joerg 	if (*dst == NULL) {
    119   1.1     joerg 		*dst = estrdup(src);
    120   1.1     joerg 		return;
    121   1.1     joerg 	}
    122   1.1     joerg 
    123   1.1     joerg 	dst_len = strlen(*dst);
    124   1.1     joerg 	/*
    125   1.1     joerg 	 * NUL Byte and separator space
    126   1.1     joerg 	 */
    127   1.1     joerg 	total_len = dst_len + srclen + 2;
    128   1.1     joerg 
    129   1.1     joerg 	*dst = erealloc(*dst, total_len);
    130   1.1     joerg 
    131   1.1     joerg 	/* Append a space at the end of dst */
    132   1.1     joerg 	(*dst)[dst_len++] = ' ';
    133   1.1     joerg 
    134  1.10  christos 	/* Now, copy src at the end of dst */
    135   1.1     joerg 	memcpy(*dst + dst_len, src, srclen + 1);
    136   1.1     joerg }
    137   1.1     joerg 
    138   1.1     joerg void
    139   1.1     joerg close_db(sqlite3 *db)
    140   1.1     joerg {
    141   1.1     joerg 	sqlite3_close(db);
    142   1.1     joerg 	sqlite3_shutdown();
    143   1.1     joerg }
    144   1.1     joerg 
    145   1.1     joerg /*
    146   1.1     joerg  * create_db --
    147   1.1     joerg  *  Creates the database schema.
    148   1.1     joerg  */
    149   1.1     joerg static int
    150   1.1     joerg create_db(sqlite3 *db)
    151   1.1     joerg {
    152   1.1     joerg 	const char *sqlstr = NULL;
    153   1.1     joerg 	char *schemasql;
    154   1.1     joerg 	char *errmsg = NULL;
    155  1.10  christos 
    156   1.1     joerg /*------------------------ Create the tables------------------------------*/
    157   1.1     joerg 
    158   1.1     joerg #if NOTYET
    159   1.1     joerg 	sqlite3_exec(db, "PRAGMA journal_mode = WAL", NULL, NULL, NULL);
    160   1.1     joerg #else
    161   1.1     joerg 	sqlite3_exec(db, "PRAGMA journal_mode = DELETE", NULL, NULL, NULL);
    162   1.1     joerg #endif
    163   1.1     joerg 
    164   1.1     joerg 	schemasql = sqlite3_mprintf("PRAGMA user_version = %d",
    165   1.1     joerg 	    APROPOS_SCHEMA_VERSION);
    166   1.1     joerg 	sqlite3_exec(db, schemasql, NULL, NULL, &errmsg);
    167   1.1     joerg 	if (errmsg != NULL)
    168   1.1     joerg 		goto out;
    169   1.1     joerg 	sqlite3_free(schemasql);
    170   1.1     joerg 
    171   1.1     joerg 	sqlstr = "CREATE VIRTUAL TABLE mandb USING fts4(section, name, "
    172   1.1     joerg 			    "name_desc, desc, lib, return_vals, env, files, "
    173   1.1     joerg 			    "exit_status, diagnostics, errors, md5_hash UNIQUE, machine, "
    174   1.1     joerg 			    "compress=zip, uncompress=unzip, tokenize=porter); "	//mandb
    175   1.1     joerg 			"CREATE TABLE IF NOT EXISTS mandb_meta(device, inode, mtime, "
    176   1.1     joerg 			    "file UNIQUE, md5_hash UNIQUE, id  INTEGER PRIMARY KEY); "
    177   1.1     joerg 				//mandb_meta
    178   1.1     joerg 			"CREATE TABLE IF NOT EXISTS mandb_links(link, target, section, "
    179   1.5       wiz 			    "machine, md5_hash); ";	//mandb_links
    180   1.1     joerg 
    181   1.1     joerg 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    182   1.1     joerg 	if (errmsg != NULL)
    183   1.1     joerg 		goto out;
    184   1.1     joerg 
    185   1.1     joerg 	sqlstr = "CREATE INDEX IF NOT EXISTS index_mandb_links ON mandb_links "
    186   1.1     joerg 			"(link); "
    187   1.1     joerg 			"CREATE INDEX IF NOT EXISTS index_mandb_meta_dev ON mandb_meta "
    188   1.5       wiz 			"(device, inode); "
    189   1.5       wiz 			"CREATE INDEX IF NOT EXISTS index_mandb_links_md5 ON mandb_links "
    190   1.5       wiz 			"(md5_hash);";
    191   1.1     joerg 	sqlite3_exec(db, sqlstr, NULL, NULL, &errmsg);
    192   1.1     joerg 	if (errmsg != NULL)
    193   1.1     joerg 		goto out;
    194   1.1     joerg 	return 0;
    195   1.1     joerg 
    196   1.1     joerg out:
    197   1.1     joerg 	warnx("%s", errmsg);
    198   1.1     joerg 	free(errmsg);
    199   1.1     joerg 	sqlite3_close(db);
    200   1.1     joerg 	sqlite3_shutdown();
    201   1.1     joerg 	return -1;
    202   1.1     joerg }
    203   1.1     joerg 
    204   1.1     joerg /*
    205   1.1     joerg  * zip --
    206   1.1     joerg  *  User defined Sqlite function to compress the FTS table
    207   1.1     joerg  */
    208   1.1     joerg static void
    209   1.1     joerg zip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    210  1.10  christos {
    211   1.1     joerg 	int nin;
    212   1.1     joerg 	long int nout;
    213   1.1     joerg 	const unsigned char * inbuf;
    214   1.1     joerg 	unsigned char *outbuf;
    215   1.1     joerg 
    216   1.1     joerg 	assert(nval == 1);
    217   1.1     joerg 	nin = sqlite3_value_bytes(apval[0]);
    218   1.1     joerg 	inbuf = (const unsigned char *) sqlite3_value_blob(apval[0]);
    219   1.1     joerg 	nout = nin + 13 + (nin + 999) / 1000;
    220   1.1     joerg 	outbuf = emalloc(nout);
    221   1.1     joerg 	compress(outbuf, (unsigned long *) &nout, inbuf, nin);
    222   1.1     joerg 	sqlite3_result_blob(pctx, outbuf, nout, free);
    223   1.1     joerg }
    224   1.1     joerg 
    225   1.1     joerg /*
    226   1.1     joerg  * unzip --
    227   1.1     joerg  *  User defined Sqlite function to uncompress the FTS table.
    228   1.1     joerg  */
    229   1.1     joerg static void
    230   1.1     joerg unzip(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    231   1.1     joerg {
    232   1.1     joerg 	unsigned int rc;
    233   1.1     joerg 	unsigned char *outbuf;
    234   1.1     joerg 	z_stream stream;
    235   1.1     joerg 
    236   1.1     joerg 	assert(nval == 1);
    237   1.1     joerg 	stream.next_in = __UNCONST(sqlite3_value_blob(apval[0]));
    238   1.1     joerg 	stream.avail_in = sqlite3_value_bytes(apval[0]);
    239   1.1     joerg 	stream.avail_out = stream.avail_in * 2 + 100;
    240   1.1     joerg 	stream.next_out = outbuf = emalloc(stream.avail_out);
    241   1.1     joerg 	stream.zalloc = NULL;
    242   1.1     joerg 	stream.zfree = NULL;
    243   1.1     joerg 
    244   1.1     joerg 	if (inflateInit(&stream) != Z_OK) {
    245   1.1     joerg 		free(outbuf);
    246   1.1     joerg 		return;
    247   1.1     joerg 	}
    248   1.1     joerg 
    249   1.1     joerg 	while ((rc = inflate(&stream, Z_SYNC_FLUSH)) != Z_STREAM_END) {
    250   1.1     joerg 		if (rc != Z_OK ||
    251   1.1     joerg 		    (stream.avail_out != 0 && stream.avail_in == 0)) {
    252   1.1     joerg 			free(outbuf);
    253   1.1     joerg 			return;
    254   1.1     joerg 		}
    255   1.1     joerg 		outbuf = erealloc(outbuf, stream.total_out * 2);
    256   1.1     joerg 		stream.next_out = outbuf + stream.total_out;
    257   1.1     joerg 		stream.avail_out = stream.total_out;
    258   1.1     joerg 	}
    259   1.1     joerg 	if (inflateEnd(&stream) != Z_OK) {
    260   1.1     joerg 		free(outbuf);
    261   1.1     joerg 		return;
    262   1.1     joerg 	}
    263   1.1     joerg 	outbuf = erealloc(outbuf, stream.total_out);
    264   1.1     joerg 	sqlite3_result_text(pctx, (const char *) outbuf, stream.total_out, free);
    265   1.1     joerg }
    266   1.1     joerg 
    267   1.7       wiz /*
    268   1.7       wiz  * get_dbpath --
    269   1.7       wiz  *   Read the path of the database from man.conf and return.
    270   1.7       wiz  */
    271   1.7       wiz char *
    272   1.7       wiz get_dbpath(const char *manconf)
    273   1.7       wiz {
    274   1.7       wiz 	TAG *tp;
    275   1.7       wiz 	char *dbpath;
    276   1.7       wiz 
    277   1.7       wiz 	config(manconf);
    278   1.7       wiz 	tp = gettag("_mandb", 1);
    279   1.7       wiz 	if (!tp)
    280   1.7       wiz 		return NULL;
    281  1.10  christos 
    282   1.7       wiz 	if (TAILQ_EMPTY(&tp->entrylist))
    283   1.7       wiz 		return NULL;
    284   1.7       wiz 
    285   1.7       wiz 	dbpath = TAILQ_LAST(&tp->entrylist, tqh)->s;
    286   1.7       wiz 	return dbpath;
    287   1.7       wiz }
    288   1.7       wiz 
    289   1.1     joerg /* init_db --
    290   1.1     joerg  *   Prepare the database. Register the compress/uncompress functions and the
    291   1.1     joerg  *   stopword tokenizer.
    292  1.10  christos  *	 db_flag specifies the mode in which to open the database. 3 options are
    293   1.1     joerg  *   available:
    294   1.1     joerg  *   	1. DB_READONLY: Open in READONLY mode. An error if db does not exist.
    295   1.1     joerg  *  	2. DB_READWRITE: Open in read-write mode. An error if db does not exist.
    296   1.1     joerg  *  	3. DB_CREATE: Open in read-write mode. It will try to create the db if
    297   1.1     joerg  *			it does not exist already.
    298   1.1     joerg  *  RETURN VALUES:
    299  1.10  christos  *		The function will return NULL in case the db does not exist and DB_CREATE
    300  1.10  christos  *  	was not specified. And in case DB_CREATE was specified and yet NULL is
    301   1.1     joerg  *  	returned, then there was some other error.
    302   1.1     joerg  *  	In normal cases the function should return a handle to the db.
    303   1.1     joerg  */
    304   1.1     joerg sqlite3 *
    305   1.7       wiz init_db(int db_flag, const char *manconf)
    306   1.1     joerg {
    307   1.1     joerg 	sqlite3 *db = NULL;
    308   1.1     joerg 	sqlite3_stmt *stmt;
    309   1.1     joerg 	struct stat sb;
    310   1.1     joerg 	int rc;
    311   1.1     joerg 	int create_db_flag = 0;
    312   1.1     joerg 
    313   1.7       wiz 	char *dbpath = get_dbpath(manconf);
    314   1.7       wiz 	if (dbpath == NULL)
    315   1.7       wiz 		errx(EXIT_FAILURE, "_mandb entry not found in man.conf");
    316   1.1     joerg 	/* Check if the database exists or not */
    317   1.7       wiz 	if (!(stat(dbpath, &sb) == 0 && S_ISREG(sb.st_mode))) {
    318   1.1     joerg 		/* Database does not exist, check if DB_CREATE was specified, and set
    319   1.1     joerg 		 * flag to create the database schema
    320   1.1     joerg 		 */
    321   1.1     joerg 		if (db_flag != (MANDB_CREATE)) {
    322   1.1     joerg 			warnx("Missing apropos database. "
    323   1.1     joerg 			      "Please run makemandb to create it.");
    324   1.1     joerg 			return NULL;
    325   1.1     joerg 		}
    326   1.1     joerg 		create_db_flag = 1;
    327   1.1     joerg 	}
    328   1.1     joerg 
    329   1.1     joerg 	/* Now initialize the database connection */
    330   1.1     joerg 	sqlite3_initialize();
    331   1.7       wiz 	rc = sqlite3_open_v2(dbpath, &db, db_flag, NULL);
    332  1.10  christos 
    333   1.1     joerg 	if (rc != SQLITE_OK) {
    334   1.1     joerg 		warnx("%s", sqlite3_errmsg(db));
    335   1.1     joerg 		sqlite3_shutdown();
    336   1.1     joerg 		return NULL;
    337   1.1     joerg 	}
    338   1.1     joerg 
    339   1.1     joerg 	if (create_db_flag && create_db(db) < 0) {
    340   1.1     joerg 		warnx("%s", "Unable to create database schema");
    341   1.1     joerg 		goto error;
    342   1.1     joerg 	}
    343   1.1     joerg 
    344   1.1     joerg 	rc = sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &stmt, NULL);
    345   1.1     joerg 	if (rc != SQLITE_OK) {
    346   1.3       apb 		warnx("Unable to query schema version: %s",
    347   1.3       apb 		    sqlite3_errmsg(db));
    348   1.1     joerg 		goto error;
    349   1.1     joerg 	}
    350   1.1     joerg 	if (sqlite3_step(stmt) != SQLITE_ROW) {
    351   1.1     joerg 		sqlite3_finalize(stmt);
    352   1.3       apb 		warnx("Unable to query schema version: %s",
    353   1.3       apb 		    sqlite3_errmsg(db));
    354   1.1     joerg 		goto error;
    355   1.1     joerg 	}
    356   1.1     joerg 	if (sqlite3_column_int(stmt, 0) != APROPOS_SCHEMA_VERSION) {
    357   1.1     joerg 		sqlite3_finalize(stmt);
    358   1.1     joerg 		warnx("Incorrect schema version found. "
    359   1.1     joerg 		      "Please run makemandb -f.");
    360   1.1     joerg 		goto error;
    361   1.1     joerg 	}
    362   1.1     joerg 	sqlite3_finalize(stmt);
    363   1.1     joerg 
    364   1.1     joerg 	sqlite3_extended_result_codes(db, 1);
    365  1.10  christos 
    366   1.1     joerg 	/* Register the zip and unzip functions for FTS compression */
    367   1.1     joerg 	rc = sqlite3_create_function(db, "zip", 1, SQLITE_ANY, NULL, zip, NULL, NULL);
    368   1.1     joerg 	if (rc != SQLITE_OK) {
    369   1.3       apb 		warnx("Unable to register function: compress: %s",
    370   1.3       apb 		    sqlite3_errmsg(db));
    371   1.1     joerg 		goto error;
    372   1.1     joerg 	}
    373   1.1     joerg 
    374  1.10  christos 	rc = sqlite3_create_function(db, "unzip", 1, SQLITE_ANY, NULL,
    375   1.1     joerg                                  unzip, NULL, NULL);
    376   1.1     joerg 	if (rc != SQLITE_OK) {
    377   1.3       apb 		warnx("Unable to register function: uncompress: %s",
    378   1.3       apb 		    sqlite3_errmsg(db));
    379   1.1     joerg 		goto error;
    380   1.1     joerg 	}
    381   1.1     joerg 	return db;
    382   1.7       wiz 
    383   1.1     joerg error:
    384   1.1     joerg 	sqlite3_close(db);
    385   1.1     joerg 	sqlite3_shutdown();
    386   1.1     joerg 	return NULL;
    387   1.1     joerg }
    388   1.1     joerg 
    389   1.1     joerg /*
    390   1.1     joerg  * rank_func --
    391   1.1     joerg  *  Sqlite user defined function for ranking the documents.
    392   1.1     joerg  *  For each phrase of the query, it computes the tf and idf and adds them over.
    393   1.1     joerg  *  It computes the final rank, by multiplying tf and idf together.
    394  1.10  christos  *  Weight of term t for document d = (term frequency of t in d *
    395  1.10  christos  *                                      inverse document frequency of t)
    396   1.1     joerg  *
    397  1.10  christos  *  Term Frequency of term t in document d = Number of times t occurs in d /
    398  1.10  christos  *	                                        Number of times t appears in all
    399   1.1     joerg  *											documents
    400   1.1     joerg  *
    401  1.10  christos  *  Inverse document frequency of t = log(Total number of documents /
    402   1.1     joerg  *										Number of documents in which t occurs)
    403   1.1     joerg  */
    404   1.1     joerg static void
    405   1.1     joerg rank_func(sqlite3_context *pctx, int nval, sqlite3_value **apval)
    406   1.1     joerg {
    407   1.1     joerg 	inverse_document_frequency *idf = sqlite3_user_data(pctx);
    408   1.1     joerg 	double tf = 0.0;
    409   1.1     joerg 	const unsigned int *matchinfo;
    410   1.1     joerg 	int ncol;
    411   1.1     joerg 	int nphrase;
    412   1.1     joerg 	int iphrase;
    413   1.1     joerg 	int ndoc;
    414   1.1     joerg 	int doclen = 0;
    415   1.1     joerg 	const double k = 3.75;
    416   1.1     joerg 	/* Check that the number of arguments passed to this function is correct. */
    417   1.1     joerg 	assert(nval == 1);
    418   1.1     joerg 
    419   1.1     joerg 	matchinfo = (const unsigned int *) sqlite3_value_blob(apval[0]);
    420   1.1     joerg 	nphrase = matchinfo[0];
    421   1.1     joerg 	ncol = matchinfo[1];
    422   1.1     joerg 	ndoc = matchinfo[2 + 3 * ncol * nphrase + ncol];
    423   1.1     joerg 	for (iphrase = 0; iphrase < nphrase; iphrase++) {
    424   1.1     joerg 		int icol;
    425   1.1     joerg 		const unsigned int *phraseinfo = &matchinfo[2 + ncol+ iphrase * ncol * 3];
    426   1.1     joerg 		for(icol = 1; icol < ncol; icol++) {
    427  1.10  christos 
    428   1.1     joerg 			/* nhitcount: number of times the current phrase occurs in the current
    429   1.1     joerg 			 *            column in the current document.
    430   1.1     joerg 			 * nglobalhitcount: number of times current phrase occurs in the current
    431   1.1     joerg 			 *                  column in all documents.
    432  1.10  christos 			 * ndocshitcount:   number of documents in which the current phrase
    433   1.1     joerg 			 *                  occurs in the current column at least once.
    434   1.1     joerg 			 */
    435   1.1     joerg   			int nhitcount = phraseinfo[3 * icol];
    436   1.1     joerg 			int nglobalhitcount = phraseinfo[3 * icol + 1];
    437   1.1     joerg 			int ndocshitcount = phraseinfo[3 * icol + 2];
    438   1.1     joerg 			doclen = matchinfo[2 + icol ];
    439   1.1     joerg 			double weight = col_weights[icol - 1];
    440   1.1     joerg 			if (idf->status == 0 && ndocshitcount)
    441   1.1     joerg 				idf->value += log(((double)ndoc / ndocshitcount))* weight;
    442   1.1     joerg 
    443  1.10  christos 			/* Dividing the tf by document length to normalize the effect of
    444   1.1     joerg 			 * longer documents.
    445   1.1     joerg 			 */
    446   1.1     joerg 			if (nglobalhitcount > 0 && nhitcount)
    447   1.1     joerg 				tf += (((double)nhitcount  * weight) / (nglobalhitcount * doclen));
    448   1.1     joerg 		}
    449   1.1     joerg 	}
    450   1.1     joerg 	idf->status = 1;
    451  1.10  christos 
    452   1.1     joerg 	/* Final score = (tf * idf)/ ( k + tf)
    453  1.10  christos 	 *	Dividing by k+ tf further normalizes the weight leading to better
    454   1.1     joerg 	 *  results.
    455   1.1     joerg 	 *  The value of k is experimental
    456   1.1     joerg 	 */
    457   1.1     joerg 	double score = (tf * idf->value/ ( k + tf)) ;
    458   1.1     joerg 	sqlite3_result_double(pctx, score);
    459   1.1     joerg 	return;
    460   1.1     joerg }
    461   1.1     joerg 
    462   1.1     joerg /*
    463   1.1     joerg  *  run_query --
    464   1.1     joerg  *  Performs the searches for the keywords entered by the user.
    465   1.1     joerg  *  The 2nd param: snippet_args is an array of strings providing values for the
    466   1.1     joerg  *  last three parameters to the snippet function of sqlite. (Look at the docs).
    467  1.10  christos  *  The 3rd param: args contains rest of the search parameters. Look at
    468   1.1     joerg  *  arpopos-utils.h for the description of individual fields.
    469  1.10  christos  *
    470   1.1     joerg  */
    471  1.15  christos static int
    472  1.15  christos run_query_internal(sqlite3 *db, const char *snippet_args[3], query_args *args)
    473   1.1     joerg {
    474   1.1     joerg 	const char *default_snippet_args[3];
    475   1.1     joerg 	char *section_clause = NULL;
    476   1.1     joerg 	char *limit_clause = NULL;
    477   1.1     joerg 	char *machine_clause = NULL;
    478   1.1     joerg 	char *query;
    479   1.1     joerg 	const char *section;
    480   1.1     joerg 	char *name;
    481   1.1     joerg 	const char *name_desc;
    482   1.1     joerg 	const char *machine;
    483   1.1     joerg 	const char *snippet;
    484   1.4       wiz 	const char *name_temp;
    485   1.4       wiz 	char *slash_ptr;
    486   1.1     joerg 	char *m = NULL;
    487   1.1     joerg 	int rc;
    488   1.1     joerg 	inverse_document_frequency idf = {0, 0};
    489   1.1     joerg 	sqlite3_stmt *stmt;
    490   1.1     joerg 
    491   1.1     joerg 	if (args->machine)
    492   1.1     joerg 		easprintf(&machine_clause, "AND machine = \'%s\' ", args->machine);
    493   1.1     joerg 
    494   1.1     joerg 	/* Register the rank function */
    495  1.10  christos 	rc = sqlite3_create_function(db, "rank_func", 1, SQLITE_ANY, (void *)&idf,
    496   1.1     joerg 	                             rank_func, NULL, NULL);
    497   1.1     joerg 	if (rc != SQLITE_OK) {
    498   1.3       apb 		warnx("Unable to register the ranking function: %s",
    499   1.3       apb 		    sqlite3_errmsg(db));
    500   1.1     joerg 		sqlite3_close(db);
    501   1.1     joerg 		sqlite3_shutdown();
    502   1.3       apb 		exit(EXIT_FAILURE);
    503   1.1     joerg 	}
    504  1.10  christos 
    505   1.1     joerg 	/* We want to build a query of the form: "select x,y,z from mandb where
    506   1.1     joerg 	 * mandb match :query [AND (section LIKE '1' OR section LIKE '2' OR...)]
    507   1.1     joerg 	 * ORDER BY rank DESC..."
    508  1.10  christos 	 * NOTES: 1. The portion in square brackets is optional, it will be there
    509  1.10  christos 	 * only if the user has specified an option on the command line to search in
    510   1.1     joerg 	 * one or more specific sections.
    511   1.1     joerg 	 * 2. I am using LIKE operator because '=' or IN operators do not seem to be
    512   1.1     joerg 	 * working with the compression option enabled.
    513   1.1     joerg 	 */
    514   1.1     joerg 
    515   1.1     joerg 	if (args->sec_nums) {
    516   1.1     joerg 		char *temp;
    517   1.1     joerg 		int i;
    518   1.1     joerg 
    519   1.1     joerg 		for (i = 0; i < SECMAX; i++) {
    520   1.1     joerg 			if (args->sec_nums[i] == 0)
    521   1.1     joerg 				continue;
    522   1.1     joerg 			easprintf(&temp, " OR section = \'%d\'", i + 1);
    523   1.1     joerg 			if (section_clause) {
    524   1.1     joerg 				concat(&section_clause, temp);
    525   1.1     joerg 				free(temp);
    526   1.1     joerg 			} else {
    527   1.1     joerg 				section_clause = temp;
    528   1.1     joerg 			}
    529   1.1     joerg 		}
    530   1.1     joerg 		if (section_clause) {
    531   1.1     joerg 			/*
    532   1.1     joerg 			 * At least one section requested, add glue for query.
    533   1.1     joerg 			 */
    534   1.1     joerg 			temp = section_clause;
    535   1.1     joerg 			/* Skip " OR " before first term. */
    536   1.1     joerg 			easprintf(&section_clause, " AND (%s)", temp + 4);
    537   1.1     joerg 			free(temp);
    538   1.1     joerg 		}
    539   1.1     joerg 	}
    540   1.1     joerg 	if (args->nrec >= 0) {
    541   1.1     joerg 		/* Use the provided number of records and offset */
    542   1.1     joerg 		easprintf(&limit_clause, " LIMIT %d OFFSET %d",
    543   1.1     joerg 		    args->nrec, args->offset);
    544   1.1     joerg 	}
    545   1.1     joerg 
    546   1.1     joerg 	if (snippet_args == NULL) {
    547   1.1     joerg 		default_snippet_args[0] = "";
    548   1.1     joerg 		default_snippet_args[1] = "";
    549   1.1     joerg 		default_snippet_args[2] = "...";
    550   1.1     joerg 		snippet_args = default_snippet_args;
    551   1.1     joerg 	}
    552  1.12  christos 	if (args->legacy) {
    553  1.13  christos 	    char *wild;
    554  1.13  christos 	    easprintf(&wild, "%%%s%%", args->search_str);
    555  1.12  christos 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    556  1.13  christos 		" snippet(mandb, %Q, %Q, %Q, -1, 40 )"
    557  1.12  christos 		" FROM mandb"
    558  1.13  christos 		" WHERE name LIKE %Q OR name_desc LIKE %Q "
    559  1.12  christos 		"%s"
    560  1.12  christos 		"%s",
    561  1.12  christos 		snippet_args[0], snippet_args[1], snippet_args[2],
    562  1.13  christos 		wild,
    563  1.12  christos 		section_clause ? section_clause : "",
    564  1.12  christos 		snippet_args[0], snippet_args[1], snippet_args[2],
    565  1.12  christos 		section_clause ? section_clause : "",
    566  1.12  christos 		limit_clause ? limit_clause : "");
    567  1.13  christos 		free(wild);
    568  1.12  christos 	} else {
    569  1.12  christos 	    query = sqlite3_mprintf("SELECT section, name, name_desc, machine,"
    570  1.12  christos 		" snippet(mandb, %Q, %Q, %Q, -1, 40 ),"
    571  1.12  christos 		" rank_func(matchinfo(mandb, \"pclxn\")) AS rank"
    572  1.12  christos 		" FROM mandb"
    573  1.12  christos 		" WHERE mandb MATCH %Q %s "
    574  1.12  christos 		"%s"
    575  1.12  christos 		" ORDER BY rank DESC"
    576  1.12  christos 		"%s",
    577  1.12  christos 		snippet_args[0], snippet_args[1], snippet_args[2],
    578  1.12  christos 		args->search_str, machine_clause ? machine_clause : "",
    579  1.12  christos 		section_clause ? section_clause : "",
    580  1.12  christos 		limit_clause ? limit_clause : "");
    581  1.12  christos 	}
    582   1.1     joerg 
    583   1.1     joerg 	free(machine_clause);
    584   1.1     joerg 	free(section_clause);
    585   1.1     joerg 	free(limit_clause);
    586   1.1     joerg 
    587   1.1     joerg 	if (query == NULL) {
    588   1.1     joerg 		*args->errmsg = estrdup("malloc failed");
    589   1.1     joerg 		return -1;
    590   1.1     joerg 	}
    591   1.1     joerg 	rc = sqlite3_prepare_v2(db, query, -1, &stmt, NULL);
    592   1.1     joerg 	if (rc == SQLITE_IOERR) {
    593   1.1     joerg 		warnx("Corrupt database. Please rerun makemandb");
    594   1.1     joerg 		sqlite3_free(query);
    595   1.1     joerg 		return -1;
    596   1.1     joerg 	} else if (rc != SQLITE_OK) {
    597   1.1     joerg 		warnx("%s", sqlite3_errmsg(db));
    598   1.1     joerg 		sqlite3_free(query);
    599   1.1     joerg 		return -1;
    600   1.1     joerg 	}
    601   1.1     joerg 
    602   1.1     joerg 	while (sqlite3_step(stmt) == SQLITE_ROW) {
    603   1.1     joerg 		section = (const char *) sqlite3_column_text(stmt, 0);
    604   1.4       wiz 		name_temp = (const char *) sqlite3_column_text(stmt, 1);
    605   1.1     joerg 		name_desc = (const char *) sqlite3_column_text(stmt, 2);
    606   1.1     joerg 		machine = (const char *) sqlite3_column_text(stmt, 3);
    607   1.1     joerg 		snippet = (const char *) sqlite3_column_text(stmt, 4);
    608   1.4       wiz 		if ((slash_ptr = strrchr(name_temp, '/')) != NULL)
    609   1.4       wiz 			name_temp = slash_ptr + 1;
    610   1.1     joerg 		if (machine && machine[0]) {
    611   1.1     joerg 			m = estrdup(machine);
    612   1.1     joerg 			easprintf(&name, "%s/%s", lower(m),
    613   1.4       wiz 				name_temp);
    614   1.1     joerg 			free(m);
    615   1.1     joerg 		} else {
    616   1.1     joerg 			name = estrdup((const char *) sqlite3_column_text(stmt, 1));
    617   1.1     joerg 		}
    618   1.1     joerg 
    619   1.1     joerg 		(args->callback)(args->callback_data, section, name, name_desc, snippet,
    620   1.1     joerg 			strlen(snippet));
    621   1.1     joerg 
    622   1.1     joerg 		free(name);
    623   1.1     joerg 	}
    624   1.1     joerg 
    625   1.1     joerg 	sqlite3_finalize(stmt);
    626   1.1     joerg 	sqlite3_free(query);
    627   1.1     joerg 	return *(args->errmsg) == NULL ? 0 : -1;
    628   1.1     joerg }
    629   1.1     joerg 
    630   1.1     joerg /*
    631   1.1     joerg  * callback_html --
    632   1.1     joerg  *  Callback function for run_query_html. It builds the html output and then
    633   1.1     joerg  *  calls the actual user supplied callback function.
    634   1.1     joerg  */
    635   1.1     joerg static int
    636   1.1     joerg callback_html(void *data, const char *section, const char *name,
    637   1.1     joerg 	const char *name_desc, const char *snippet, size_t snippet_length)
    638   1.1     joerg {
    639   1.1     joerg 	const char *temp = snippet;
    640   1.1     joerg 	int i = 0;
    641   1.1     joerg 	size_t sz = 0;
    642   1.1     joerg 	int count = 0;
    643   1.1     joerg 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    644  1.10  christos 	int (*callback) (void *, const char *, const char *, const char *,
    645   1.1     joerg 		const char *, size_t) = orig_data->callback;
    646   1.1     joerg 
    647   1.1     joerg 	/* First scan the snippet to find out the number of occurrences of {'>', '<'
    648   1.1     joerg 	 * '"', '&'}.
    649   1.1     joerg 	 * Then allocate a new buffer with sufficient space to be able to store the
    650   1.1     joerg 	 * quoted versions of the special characters {&gt;, &lt;, &quot;, &amp;}.
    651   1.1     joerg 	 * Copy over the characters from the original snippet to this buffer while
    652   1.1     joerg 	 * replacing the special characters with their quoted versions.
    653   1.1     joerg 	 */
    654   1.1     joerg 
    655   1.1     joerg 	while (*temp) {
    656   1.1     joerg 		sz = strcspn(temp, "<>\"&\002\003");
    657   1.1     joerg 		temp += sz + 1;
    658   1.1     joerg 		count++;
    659   1.1     joerg 	}
    660   1.1     joerg 	size_t qsnippet_length = snippet_length + count * 5;
    661   1.1     joerg 	char *qsnippet = emalloc(qsnippet_length + 1);
    662   1.1     joerg 	sz = 0;
    663   1.1     joerg 	while (*snippet) {
    664   1.1     joerg 		sz = strcspn(snippet, "<>\"&\002\003");
    665   1.1     joerg 		if (sz) {
    666   1.1     joerg 			memcpy(&qsnippet[i], snippet, sz);
    667   1.1     joerg 			snippet += sz;
    668   1.1     joerg 			i += sz;
    669   1.1     joerg 		}
    670   1.1     joerg 
    671   1.1     joerg 		switch (*snippet++) {
    672   1.1     joerg 		case '<':
    673   1.1     joerg 			memcpy(&qsnippet[i], "&lt;", 4);
    674   1.1     joerg 			i += 4;
    675   1.1     joerg 			break;
    676   1.1     joerg 		case '>':
    677   1.1     joerg 			memcpy(&qsnippet[i], "&gt;", 4);
    678   1.1     joerg 			i += 4;
    679   1.1     joerg 			break;
    680   1.1     joerg 		case '\"':
    681   1.1     joerg 			memcpy(&qsnippet[i], "&quot;", 6);
    682   1.1     joerg 			i += 6;
    683   1.1     joerg 			break;
    684   1.1     joerg 		case '&':
    685   1.1     joerg 			/* Don't perform the quoting if this & is part of an mdoc escape
    686   1.1     joerg 			 * sequence, e.g. \&
    687   1.1     joerg 			 */
    688   1.1     joerg 			if (i && *(snippet - 2) != '\\') {
    689   1.1     joerg 				memcpy(&qsnippet[i], "&amp;", 5);
    690   1.1     joerg 				i += 5;
    691   1.1     joerg 			} else {
    692   1.1     joerg 				qsnippet[i++] = '&';
    693   1.1     joerg 			}
    694   1.1     joerg 			break;
    695   1.1     joerg 		case '\002':
    696   1.1     joerg 			memcpy(&qsnippet[i], "<b>", 3);
    697   1.1     joerg 			i += 3;
    698   1.1     joerg 			break;
    699   1.1     joerg 		case '\003':
    700   1.1     joerg 			memcpy(&qsnippet[i], "</b>", 4);
    701   1.1     joerg 			i += 4;
    702   1.1     joerg 			break;
    703   1.1     joerg 		default:
    704   1.1     joerg 			break;
    705   1.1     joerg 		}
    706   1.1     joerg 	}
    707   1.1     joerg 	qsnippet[++i] = 0;
    708   1.1     joerg 	(*callback)(orig_data->data, section, name, name_desc,
    709   1.1     joerg 		(const char *)qsnippet,	qsnippet_length);
    710   1.1     joerg 	free(qsnippet);
    711   1.1     joerg 	return 0;
    712   1.1     joerg }
    713   1.1     joerg 
    714   1.1     joerg /*
    715   1.1     joerg  * run_query_html --
    716   1.1     joerg  *  Utility function to output query result in HTML format.
    717  1.10  christos  *  It internally calls run_query only, but it first passes the output to it's
    718   1.1     joerg  *  own custom callback function, which preprocess the snippet for quoting
    719   1.1     joerg  *  inline HTML fragments.
    720   1.1     joerg  *  After that it delegates the call the actual user supplied callback function.
    721   1.1     joerg  */
    722  1.15  christos static int
    723   1.1     joerg run_query_html(sqlite3 *db, query_args *args)
    724   1.1     joerg {
    725   1.1     joerg 	struct orig_callback_data orig_data;
    726   1.1     joerg 	orig_data.callback = args->callback;
    727   1.1     joerg 	orig_data.data = args->callback_data;
    728   1.1     joerg 	const char *snippet_args[] = {"\002", "\003", "..."};
    729   1.1     joerg 	args->callback = &callback_html;
    730   1.1     joerg 	args->callback_data = (void *) &orig_data;
    731  1.15  christos 	return run_query_internal(db, snippet_args, args);
    732   1.1     joerg }
    733   1.1     joerg 
    734   1.1     joerg /*
    735   1.9  christos  * underline a string, pager style.
    736   1.9  christos  */
    737   1.9  christos static char *
    738  1.14  christos ul_pager(int ul, const char *s)
    739   1.9  christos {
    740   1.9  christos 	size_t len;
    741   1.9  christos 	char *dst, *d;
    742   1.9  christos 
    743  1.14  christos 	if (!ul)
    744  1.14  christos 		return estrdup(s);
    745  1.14  christos 
    746   1.9  christos 	// a -> _\ba
    747   1.9  christos 	len = strlen(s) * 3 + 1;
    748   1.9  christos 
    749   1.9  christos 	d = dst = emalloc(len);
    750   1.9  christos 	while (*s) {
    751   1.9  christos 		*d++ = '_';
    752   1.9  christos 		*d++ = '\b';
    753   1.9  christos 		*d++ = *s++;
    754   1.9  christos 	}
    755   1.9  christos 	*d = '\0';
    756   1.9  christos 	return dst;
    757   1.9  christos }
    758   1.9  christos 
    759   1.9  christos /*
    760   1.1     joerg  * callback_pager --
    761   1.1     joerg  *  A callback similar to callback_html. It overstrikes the matching text in
    762   1.1     joerg  *  the snippet so that it appears emboldened when viewed using a pager like
    763   1.1     joerg  *  more or less.
    764   1.1     joerg  */
    765   1.1     joerg static int
    766  1.10  christos callback_pager(void *data, const char *section, const char *name,
    767   1.1     joerg 	const char *name_desc, const char *snippet, size_t snippet_length)
    768   1.1     joerg {
    769   1.1     joerg 	struct orig_callback_data *orig_data = (struct orig_callback_data *) data;
    770   1.1     joerg 	char *psnippet;
    771   1.1     joerg 	const char *temp = snippet;
    772   1.1     joerg 	int count = 0;
    773  1.14  christos 	int i = 0, did;
    774   1.1     joerg 	size_t sz = 0;
    775   1.1     joerg 	size_t psnippet_length;
    776   1.1     joerg 
    777   1.1     joerg 	/* Count the number of bytes of matching text. For each of these bytes we
    778   1.1     joerg 	 * will use 2 extra bytes to overstrike it so that it appears bold when
    779   1.1     joerg 	 * viewed using a pager.
    780   1.1     joerg 	 */
    781   1.1     joerg 	while (*temp) {
    782   1.1     joerg 		sz = strcspn(temp, "\002\003");
    783   1.1     joerg 		temp += sz;
    784   1.1     joerg 		if (*temp == '\003') {
    785   1.1     joerg 			count += 2 * (sz);
    786   1.1     joerg 		}
    787   1.1     joerg 		temp++;
    788   1.1     joerg 	}
    789   1.1     joerg 
    790   1.1     joerg 	psnippet_length = snippet_length + count;
    791   1.1     joerg 	psnippet = emalloc(psnippet_length + 1);
    792   1.1     joerg 
    793   1.1     joerg 	/* Copy the bytes from snippet to psnippet:
    794   1.1     joerg 	 * 1. Copy the bytes before \002 as it is.
    795   1.1     joerg 	 * 2. The bytes after \002 need to be overstriked till we encounter \003.
    796   1.1     joerg 	 * 3. To overstrike a byte 'A' we need to write 'A\bA'
    797   1.1     joerg 	 */
    798  1.14  christos 	did = 0;
    799   1.1     joerg 	while (*snippet) {
    800   1.1     joerg 		sz = strcspn(snippet, "\002");
    801   1.1     joerg 		memcpy(&psnippet[i], snippet, sz);
    802   1.1     joerg 		snippet += sz;
    803   1.1     joerg 		i += sz;
    804   1.1     joerg 
    805   1.1     joerg 		/* Don't change this. Advancing the pointer without reading the byte
    806   1.1     joerg 		 * is causing strange behavior.
    807   1.1     joerg 		 */
    808   1.1     joerg 		if (*snippet == '\002')
    809   1.1     joerg 			snippet++;
    810   1.1     joerg 		while (*snippet && *snippet != '\003') {
    811  1.14  christos 			did = 1;
    812   1.1     joerg 			psnippet[i++] = *snippet;
    813   1.1     joerg 			psnippet[i++] = '\b';
    814   1.1     joerg 			psnippet[i++] = *snippet++;
    815   1.1     joerg 		}
    816   1.1     joerg 		if (*snippet)
    817   1.1     joerg 			snippet++;
    818   1.1     joerg 	}
    819   1.1     joerg 
    820   1.1     joerg 	psnippet[i] = 0;
    821  1.14  christos 	char *ul_section = ul_pager(did, section);
    822  1.14  christos 	char *ul_name = ul_pager(did, name);
    823  1.14  christos 	char *ul_name_desc = ul_pager(did, name_desc);
    824   1.9  christos 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    825   1.9  christos 	    ul_name_desc, psnippet, psnippet_length);
    826   1.9  christos 	free(ul_section);
    827   1.9  christos 	free(ul_name);
    828   1.9  christos 	free(ul_name_desc);
    829   1.1     joerg 	free(psnippet);
    830   1.1     joerg 	return 0;
    831   1.1     joerg }
    832   1.1     joerg 
    833   1.9  christos struct term_args {
    834   1.9  christos 	struct orig_callback_data *orig_data;
    835   1.9  christos 	const char *smul;
    836   1.9  christos 	const char *rmul;
    837   1.9  christos };
    838   1.9  christos 
    839   1.9  christos /*
    840   1.9  christos  * underline a string, pager style.
    841   1.9  christos  */
    842   1.9  christos static char *
    843   1.9  christos ul_term(const char *s, const struct term_args *ta)
    844   1.9  christos {
    845   1.9  christos 	char *dst;
    846   1.9  christos 
    847   1.9  christos 	easprintf(&dst, "%s%s%s", ta->smul, s, ta->rmul);
    848   1.9  christos 	return dst;
    849   1.9  christos }
    850   1.9  christos 
    851   1.9  christos /*
    852   1.9  christos  * callback_term --
    853   1.9  christos  *  A callback similar to callback_html. It overstrikes the matching text in
    854   1.9  christos  *  the snippet so that it appears emboldened when viewed using a pager like
    855   1.9  christos  *  more or less.
    856   1.9  christos  */
    857   1.9  christos static int
    858  1.10  christos callback_term(void *data, const char *section, const char *name,
    859   1.9  christos 	const char *name_desc, const char *snippet, size_t snippet_length)
    860   1.9  christos {
    861   1.9  christos 	struct term_args *ta = data;
    862   1.9  christos 	struct orig_callback_data *orig_data = ta->orig_data;
    863   1.9  christos 
    864   1.9  christos 	char *ul_section = ul_term(section, ta);
    865   1.9  christos 	char *ul_name = ul_term(name, ta);
    866   1.9  christos 	char *ul_name_desc = ul_term(name_desc, ta);
    867   1.9  christos 	(orig_data->callback)(orig_data->data, ul_section, ul_name,
    868   1.9  christos 	    ul_name_desc, snippet, snippet_length);
    869   1.9  christos 	free(ul_section);
    870   1.9  christos 	free(ul_name);
    871   1.9  christos 	free(ul_name_desc);
    872   1.9  christos 	return 0;
    873   1.9  christos }
    874   1.9  christos 
    875   1.1     joerg /*
    876   1.1     joerg  * run_query_pager --
    877   1.1     joerg  *  Utility function similar to run_query_html. This function tries to
    878   1.1     joerg  *  pre-process the result assuming it will be piped to a pager.
    879   1.1     joerg  *  For this purpose it first calls it's own callback function callback_pager
    880   1.1     joerg  *  which then delegates the call to the user supplied callback.
    881   1.1     joerg  */
    882  1.15  christos static int
    883   1.6     joerg run_query_pager(sqlite3 *db, query_args *args)
    884   1.1     joerg {
    885   1.1     joerg 	struct orig_callback_data orig_data;
    886   1.1     joerg 	orig_data.callback = args->callback;
    887   1.1     joerg 	orig_data.data = args->callback_data;
    888  1.15  christos 	const char *snippet_args[3] = { "\002", "\003", "..." };
    889   1.1     joerg 	args->callback = &callback_pager;
    890   1.1     joerg 	args->callback_data = (void *) &orig_data;
    891  1.15  christos 	return run_query_internal(db, snippet_args, args);
    892   1.1     joerg }
    893   1.9  christos 
    894   1.9  christos static void
    895   1.9  christos term_init(int fd, const char *sa[5])
    896   1.9  christos {
    897   1.9  christos 	TERMINAL *ti;
    898   1.9  christos 	int error;
    899   1.9  christos 	const char *bold, *sgr0, *smso, *rmso, *smul, *rmul;
    900   1.9  christos 
    901   1.9  christos 	if (ti_setupterm(&ti, NULL, fd, &error) == -1) {
    902   1.9  christos 		bold = sgr0 = NULL;
    903   1.9  christos 		smso = rmso = smul = rmul = "";
    904   1.9  christos 		ti = NULL;
    905   1.9  christos 	} else {
    906   1.9  christos 		bold = ti_getstr(ti, "bold");
    907   1.9  christos 		sgr0 = ti_getstr(ti, "sgr0");
    908   1.9  christos 		if (bold == NULL || sgr0 == NULL) {
    909   1.9  christos 			smso = ti_getstr(ti, "smso");
    910   1.9  christos 
    911   1.9  christos 			if (smso == NULL ||
    912   1.9  christos 			    (rmso = ti_getstr(ti, "rmso")) == NULL)
    913   1.9  christos 				smso = rmso = "";
    914   1.9  christos 			bold = sgr0 = NULL;
    915   1.9  christos 		} else
    916   1.9  christos 			smso = rmso = "";
    917   1.9  christos 
    918   1.9  christos 		smul = ti_getstr(ti, "smul");
    919   1.9  christos 		if (smul == NULL || (rmul = ti_getstr(ti, "rmul")) == NULL)
    920   1.9  christos 			smul = rmul = "";
    921   1.9  christos 	}
    922   1.9  christos 
    923   1.9  christos 	sa[0] = estrdup(bold ? bold : smso);
    924   1.9  christos 	sa[1] = estrdup(sgr0 ? sgr0 : rmso);
    925   1.9  christos 	sa[2] = estrdup("...");
    926   1.9  christos 	sa[3] = estrdup(smul);
    927   1.9  christos 	sa[4] = estrdup(rmul);
    928   1.9  christos 	if (ti)
    929   1.9  christos 		del_curterm(ti);
    930   1.9  christos }
    931   1.9  christos 
    932   1.9  christos /*
    933   1.9  christos  * run_query_term --
    934   1.9  christos  *  Utility function similar to run_query_html. This function tries to
    935   1.9  christos  *  pre-process the result assuming it will be displayed on a terminal
    936   1.9  christos  *  For this purpose it first calls it's own callback function callback_pager
    937   1.9  christos  *  which then delegates the call to the user supplied callback.
    938   1.9  christos  */
    939  1.15  christos static int
    940   1.9  christos run_query_term(sqlite3 *db, query_args *args)
    941   1.9  christos {
    942   1.9  christos 	struct orig_callback_data orig_data;
    943   1.9  christos 	struct term_args ta;
    944   1.9  christos 	orig_data.callback = args->callback;
    945   1.9  christos 	orig_data.data = args->callback_data;
    946   1.9  christos 	const char *snippet_args[5];
    947  1.15  christos 
    948  1.15  christos 	term_init(STDOUT_FILENO, snippet_args);
    949   1.9  christos 	ta.smul = snippet_args[3];
    950   1.9  christos 	ta.rmul = snippet_args[4];
    951   1.9  christos 	ta.orig_data = (void *) &orig_data;
    952   1.9  christos 
    953   1.9  christos 	args->callback = &callback_term;
    954   1.9  christos 	args->callback_data = &ta;
    955  1.15  christos 	return run_query_internal(db, snippet_args, args);
    956  1.15  christos }
    957  1.15  christos 
    958  1.15  christos static int
    959  1.15  christos run_query_none(sqlite3 *db, query_args *args)
    960  1.15  christos {
    961  1.15  christos 	struct orig_callback_data orig_data;
    962  1.15  christos 	orig_data.callback = args->callback;
    963  1.15  christos 	orig_data.data = args->callback_data;
    964  1.15  christos 	const char *snippet_args[3] = { "", "", "..." };
    965  1.15  christos 	args->callback = &callback_pager;
    966  1.15  christos 	args->callback_data = (void *) &orig_data;
    967  1.15  christos 	return run_query_internal(db, snippet_args, args);
    968  1.15  christos }
    969  1.15  christos 
    970  1.15  christos int
    971  1.15  christos run_query(sqlite3 *db, query_format fmt, query_args *args)
    972  1.15  christos {
    973  1.15  christos 	switch (fmt) {
    974  1.15  christos 	case APROPOS_NONE:
    975  1.15  christos 		return run_query_none(db, args);
    976  1.15  christos 	case APROPOS_HTML:
    977  1.15  christos 		return run_query_html(db, args);
    978  1.15  christos 	case APROPOS_TERM:
    979  1.15  christos 		return run_query_term(db, args);
    980  1.15  christos 	case APROPOS_PAGER:
    981  1.15  christos 		return run_query_pager(db, args);
    982  1.15  christos 	default:
    983  1.15  christos 		warnx("Unknown query format %d", (int)fmt);
    984  1.15  christos 		return -1;
    985  1.15  christos 	}
    986   1.9  christos }
    987