]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
Make bibtex works with embedded bib file
[lyx.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetBibtex.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "DispatchResult.h"
19 #include "support/debug.h"
20 #include "EmbeddedFiles.h"
21 #include "Encoding.h"
22 #include "FuncRequest.h"
23 #include "support/gettext.h"
24 #include "LaTeXFeatures.h"
25 #include "MetricsInfo.h"
26 #include "OutputParams.h"
27 #include "TextClass.h"
28
29 #include "frontends/alert.h"
30
31 #include "support/ExceptionMessage.h"
32 #include "support/docstream.h"
33 #include "support/filetools.h"
34 #include "support/lstrings.h"
35 #include "support/os.h"
36 #include "support/Path.h"
37 #include "support/textutils.h"
38
39 #include <boost/tokenizer.hpp>
40
41 using namespace std;
42 using namespace lyx::support;
43
44 namespace lyx {
45
46 namespace Alert = frontend::Alert;
47 namespace os = support::os;
48
49
50 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
51         : InsetCommand(p, "bibtex")
52 {}
53
54
55 CommandInfo const * InsetBibtex::findInfo(string const & /* cmdName */)
56 {
57         static const char * const paramnames[] = 
58                 {"options", "btprint", "bibfiles", "embed", ""};
59         static const bool isoptional[] = {true, true, false, false};
60         static const CommandInfo info = {4, paramnames, isoptional};
61         return &info;
62 }
63
64
65 Inset * InsetBibtex::clone() const
66 {
67         return new InsetBibtex(*this);
68 }
69
70
71 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
72 {
73         switch (cmd.action) {
74
75         case LFUN_INSET_MODIFY: {
76                 InsetCommandParams p(BIBTEX_CODE);
77                 try {
78                         if (!InsetCommandMailer::string2params("bibtex", 
79                                         to_utf8(cmd.argument()), p)) {
80                                 cur.noUpdate();
81                                 break;
82                         }
83                 } catch (ExceptionMessage const & message) {
84                         if (message.type_ == WarningException) {
85                                 Alert::warning(message.title_, message.details_);
86                                 cur.noUpdate();
87                         } else 
88                                 throw message;
89                         break;
90                 }
91                 //
92                 InsetCommandParams orig = params();
93                 // returned "embed" is composed of "true" or "false", which needs to be adjusted
94                 string tmp;
95                 string emb;
96                 
97                 string newBibfiles;
98                 string newEmbedStatus;
99                 
100                 string bibfiles = to_utf8(p["bibfiles"]);
101                 string embedStatus = to_utf8(p["embed"]);
102                 
103                 bibfiles = split(bibfiles, tmp, ',');
104                 embedStatus = split(embedStatus, emb, ',');
105                 while (!tmp.empty()) {
106                         EmbeddedFile file(changeExtension(tmp, "bib"), cur.buffer().filePath());
107                         if (!file.exists())
108                                 continue;
109                         if (!newBibfiles.empty())
110                                 newBibfiles += ",";
111                         newBibfiles += tmp;
112                         if (!newEmbedStatus.empty())
113                                 newEmbedStatus += ",";
114                         if (emb == "true")
115                                 newEmbedStatus += file.inzipName();
116                         // Get next file name
117                         bibfiles = split(bibfiles, tmp, ',');
118                         embedStatus = split(embedStatus, emb, ',');
119                 }
120                 LYXERR(Debug::FILES, "Update parameters from " << p["bibfiles"]
121                         << " " << p["embed"] << " to " << newBibfiles << " "
122                         << newEmbedStatus);
123                 p["bibfiles"] = from_utf8(newBibfiles);
124                 p["embed"] = from_utf8(newEmbedStatus);
125                 
126                 setParams(p);
127                 try {
128                         // test parameter and copy files
129                         getFiles(cur.buffer());
130                 } catch (ExceptionMessage const & message) {
131                         Alert::error(message.title_, message.details_);
132                         // do not set parameter if an error happens
133                         setParams(orig);
134                         break;
135                 }
136                 cur.buffer().updateBibfilesCache();
137                 break;
138         }
139
140         default:
141                 InsetCommand::doDispatch(cur, cmd);
142                 break;
143         }
144 }
145
146
147 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
148 {
149         return _("BibTeX Generated Bibliography");
150 }
151
152
153 namespace {
154
155 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
156                       string const & name, string const & ext)
157 {
158         string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
159         if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
160                 return name;
161         if (!runparams.nice)
162                 return fname;
163
164         // FIXME UNICODE
165         return to_utf8(makeRelPath(from_utf8(fname),
166                                          from_utf8(buffer.masterBuffer()->filePath())));
167 }
168
169 }
170
171
172 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
173                        OutputParams const & runparams) const
174 {
175         // the sequence of the commands:
176         // 1. \bibliographystyle{style}
177         // 2. \addcontentsline{...} - if option bibtotoc set
178         // 3. \bibliography{database}
179         // and with bibtopic:
180         // 1. \bibliographystyle{style}
181         // 2. \begin{btSect}{database}
182         // 3. \btPrint{Cited|NotCited|All}
183         // 4. \end{btSect}
184
185         // Database(s)
186         // If we are processing the LaTeX file in a temp directory then
187         // copy the .bib databases to this temp directory, mangling their
188         // names in the process. Store this mangled name in the list of
189         // all databases.
190         // (We need to do all this because BibTeX *really*, *really*
191         // can't handle "files with spaces" and Windows users tend to
192         // use such filenames.)
193         // Otherwise, store the (maybe absolute) path to the original,
194         // unmangled database name.
195         EmbeddedFileList const bibs = getFiles(buffer);
196         EmbeddedFileList::const_iterator it = bibs.begin();
197         EmbeddedFileList::const_iterator it_end = bibs.end();
198         odocstringstream dbs;
199         for (; it != it_end; ++it) {
200                 string utf8input = removeExtension(it->availableFile().absFilename());
201                 string database =
202                         normalizeName(buffer, runparams, utf8input, ".bib");
203                 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
204                 bool const not_from_texmf = try_in_file.isReadableFile();
205
206                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
207                     not_from_texmf) {
208
209                         // mangledFilename() needs the extension
210                         DocFileName const in_file = DocFileName(try_in_file);
211                         database = removeExtension(in_file.mangledFilename());
212                         FileName const out_file = makeAbsPath(database + ".bib",
213                                         buffer.masterBuffer()->temppath());
214
215                         bool const success = in_file.copyTo(out_file);
216                         if (!success) {
217                                 lyxerr << "Failed to copy '" << in_file
218                                        << "' to '" << out_file << "'"
219                                        << endl;
220                         }
221                 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
222                            !isValidLaTeXFilename(database)) {
223                                 frontend::Alert::warning(_("Invalid filename"),
224                                                          _("The following filename is likely to cause trouble "
225                                                            "when running the exported file through LaTeX: ") +
226                                                             from_utf8(database));
227                 }
228
229                 if (it != bibs.begin())
230                         dbs << ',';
231                 // FIXME UNICODE
232                 dbs << from_utf8(latex_path(database));
233         }
234         docstring const db_out = dbs.str();
235
236         // Post this warning only once.
237         static bool warned_about_spaces = false;
238         if (!warned_about_spaces &&
239             runparams.nice && db_out.find(' ') != docstring::npos) {
240                 warned_about_spaces = true;
241
242                 Alert::warning(_("Export Warning!"),
243                                _("There are spaces in the paths to your BibTeX databases.\n"
244                                               "BibTeX will be unable to find them."));
245         }
246
247         // Style-Options
248         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
249         string bibtotoc;
250         if (prefixIs(style, "bibtotoc")) {
251                 bibtotoc = "bibtotoc";
252                 if (contains(style, ','))
253                         style = split(style, bibtotoc, ',');
254         }
255
256         // line count
257         int nlines = 0;
258
259         if (!style.empty()) {
260                 string base = normalizeName(buffer, runparams, style, ".bst");
261                 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
262                 bool const not_from_texmf = try_in_file.isReadableFile();
263                 // If this style does not come from texmf and we are not
264                 // exporting to .tex copy it to the tmp directory.
265                 // This prevents problems with spaces and 8bit charcaters
266                 // in the file name.
267                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
268                     not_from_texmf) {
269                         // use new style name
270                         DocFileName const in_file = DocFileName(try_in_file);
271                         base = removeExtension(in_file.mangledFilename());
272                         FileName const out_file(makeAbsPath(base + ".bst",
273                                         buffer.masterBuffer()->temppath()));
274                         bool const success = in_file.copyTo(out_file);
275                         if (!success) {
276                                 lyxerr << "Failed to copy '" << in_file
277                                        << "' to '" << out_file << "'"
278                                        << endl;
279                         }
280                 }
281                 // FIXME UNICODE
282                 os << "\\bibliographystyle{"
283                    << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
284                    << "}\n";
285                 nlines += 1;
286         }
287
288         // Post this warning only once.
289         static bool warned_about_bst_spaces = false;
290         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
291                 warned_about_bst_spaces = true;
292                 Alert::warning(_("Export Warning!"),
293                                _("There are spaces in the path to your BibTeX style file.\n"
294                                               "BibTeX will be unable to find it."));
295         }
296
297         if (!db_out.empty() && buffer.params().use_bibtopic){
298                 os << "\\begin{btSect}{" << db_out << "}\n";
299                 docstring btprint = getParam("btprint");
300                 if (btprint.empty())
301                         // default
302                         btprint = from_ascii("btPrintCited");
303                 os << "\\" << btprint << "\n"
304                    << "\\end{btSect}\n";
305                 nlines += 3;
306         }
307
308         // bibtotoc-Option
309         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
310                 // maybe a problem when a textclass has no "art" as
311                 // part of its name, because it's than book.
312                 // For the "official" lyx-layouts it's no problem to support
313                 // all well
314                 if (!contains(buffer.params().getTextClass().name(),
315                               "art")) {
316                         if (buffer.params().sides == OneSide) {
317                                 // oneside
318                                 os << "\\clearpage";
319                         } else {
320                                 // twoside
321                                 os << "\\cleardoublepage";
322                         }
323
324                         // bookclass
325                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
326
327                 } else {
328                         // article class
329                         os << "\\addcontentsline{toc}{section}{\\refname}";
330                 }
331         }
332
333         if (!db_out.empty() && !buffer.params().use_bibtopic){
334                 docstring btprint = getParam("btprint");
335                 if (btprint == "btPrintAll") {
336                         os << "\\nocite{*}\n";
337                         nlines += 1;
338                 }
339                 os << "\\bibliography{" << db_out << "}\n";
340                 nlines += 1;
341         }
342
343         return nlines;
344 }
345
346
347 EmbeddedFileList const InsetBibtex::getFiles(Buffer const & buffer) const
348 {
349         FileName path(buffer.filePath());
350         PathChanger p(path);
351
352         EmbeddedFileList vec;
353
354         string tmp;
355         string emb;
356         // FIXME UNICODE
357         string bibfiles = to_utf8(getParam("bibfiles"));
358         string embedStatus = to_utf8(getParam("embed"));
359         bibfiles = split(bibfiles, tmp, ',');
360         embedStatus = split(embedStatus, emb, ',');
361         while (!tmp.empty()) {
362                 if (!emb.empty()) {
363                         EmbeddedFile file(changeExtension(tmp, "bib"), buffer.filePath());
364                         // If the file structure is correct, this should not fail.
365                         file.setEmbed(true);
366                         file.enable(buffer.embedded(), &buffer);
367                         vec.push_back(file);
368                 } else {
369                         // this includes the cases when the embed parameter is empty
370                         FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
371
372                         // If we didn't find a matching file name just fail silently
373                         if (!file.empty()) {
374                                 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer.filePath());
375                                 efile.setEmbed(false);
376                                 efile.enable(buffer.embedded(), &buffer);
377                                 vec.push_back(efile);
378                         }
379                 }
380
381                 // Get next file name
382                 bibfiles = split(bibfiles, tmp, ',');
383                 embedStatus = split(embedStatus, emb, ',');
384         }
385
386         return vec;
387 }
388
389 namespace {
390
391         // methods for parsing bibtex files
392
393         typedef map<docstring, docstring> VarMap;
394
395         /// remove whitespace characters, optionally a single comma,
396         /// and further whitespace characters from the stream.
397         /// @return true if a comma was found, false otherwise
398         ///
399         bool removeWSAndComma(idocfstream & ifs) {
400                 char_type ch;
401
402                 if (!ifs)
403                         return false;
404
405                 // skip whitespace
406                 do {
407                         ifs.get(ch);
408                 } while (ifs && isSpace(ch));
409
410                 if (!ifs)
411                         return false;
412
413                 if (ch != ',') {
414                         ifs.putback(ch);
415                         return false;
416                 }
417
418                 // skip whitespace
419                 do {
420                         ifs.get(ch);
421                 } while (ifs && isSpace(ch));
422
423                 if (ifs) {
424                         ifs.putback(ch);
425                 }
426
427                 return true;
428         }
429
430
431         enum charCase {
432                 makeLowerCase,
433                 keepCase
434         };
435
436         /// remove whitespace characters, read characer sequence
437         /// not containing whitespace characters or characters in
438         /// delimChars, and remove further whitespace characters.
439         ///
440         /// @return true if a string of length > 0 could be read.
441         ///
442         bool readTypeOrKey(docstring & val, idocfstream & ifs,
443                 docstring const & delimChars, docstring const &illegalChars, 
444                 charCase chCase) {
445
446                 char_type ch;
447
448                 val.clear();
449
450                 if (!ifs)
451                         return false;
452
453                 // skip whitespace
454                 do {
455                         ifs.get(ch);
456                 } while (ifs && isSpace(ch));
457
458                 if (!ifs)
459                         return false;
460
461                 // read value
462                 bool legalChar = true;
463                 while (ifs && !isSpace(ch) && 
464                                                  delimChars.find(ch) == docstring::npos &&
465                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
466                                         ) 
467                 {
468                         if (chCase == makeLowerCase)
469                                 val += lowercase(ch);
470                         else
471                                 val += ch;
472                         ifs.get(ch);
473                 }
474                 
475                 if (!legalChar) {
476                         ifs.putback(ch);
477                         return false;
478                 }
479
480                 // skip whitespace
481                 while (ifs && isSpace(ch)) {
482                         ifs.get(ch);
483                 }
484
485                 if (ifs) {
486                         ifs.putback(ch);
487                 }
488
489                 return val.length() > 0;
490         }
491
492         /// read subsequent bibtex values that are delimited with a #-character.
493         /// Concatenate all parts and replace names with the associated string in
494         /// the variable strings.
495         /// @return true if reading was successfull (all single parts were delimited
496         /// correctly)
497         bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
498
499                 char_type ch;
500
501                 val.clear();
502
503                 if (!ifs)
504                         return false;
505
506                 do {
507                         // skip whitespace
508                         do {
509                                 ifs.get(ch);
510                         } while (ifs && isSpace(ch));
511
512                         if (!ifs)
513                                 return false;
514
515                         // check for field type
516                         if (isDigit(ch)) {
517
518                                 // read integer value
519                                 do {
520                                         val += ch;
521                                         ifs.get(ch);
522                                 } while (ifs && isDigit(ch));
523
524                                 if (!ifs)
525                                         return false;
526
527                         } else if (ch == '"' || ch == '{') {
528                                 // set end delimiter
529                                 char_type delim = ch == '"' ? '"': '}';
530
531                                 //Skip whitespace
532                                 do {
533                                         ifs.get(ch);
534                                 } while (ifs && isSpace(ch));
535                                 
536                                 if (!ifs)
537                                         return false;
538                                 
539                                 //We now have the first non-whitespace character
540                                 //We'll collapse adjacent whitespace.
541                                 bool lastWasWhiteSpace = false;
542                                 
543                                 // inside this delimited text braces must match.
544                                 // Thus we can have a closing delimiter only
545                                 // when nestLevel == 0
546                                 int nestLevel = 0;
547  
548                                 while (ifs && (nestLevel > 0 || ch != delim)) {
549                                         if (isSpace(ch)) {
550                                                 lastWasWhiteSpace = true;
551                                                 ifs.get(ch);
552                                                 continue;
553                                         }
554                                         //We output the space only after we stop getting 
555                                         //whitespace so as not to output any whitespace
556                                         //at the end of the value.
557                                         if (lastWasWhiteSpace) {
558                                                 lastWasWhiteSpace = false;
559                                                 val += ' ';
560                                         }
561                                         
562                                         val += ch;
563
564                                         // update nesting level
565                                         switch (ch) {
566                                                 case '{':
567                                                         ++nestLevel;
568                                                         break;
569                                                 case '}':
570                                                         --nestLevel;
571                                                         if (nestLevel < 0) return false;
572                                                         break;
573                                         }
574
575                                         ifs.get(ch);
576                                 }
577
578                                 if (!ifs)
579                                         return false;
580
581                                 ifs.get(ch);
582
583                                 if (!ifs)
584                                         return false;
585
586                         } else {
587
588                                 // reading a string name
589                                 docstring strName;
590
591                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
592                                         strName += lowercase(ch);
593                                         ifs.get(ch);
594                                 }
595
596                                 if (!ifs)
597                                         return false;
598
599                                 // replace the string with its assigned value or
600                                 // discard it if it's not assigned
601                                 if (strName.length()) {
602                                         VarMap::const_iterator pos = strings.find(strName);
603                                         if (pos != strings.end()) {
604                                                 val += pos->second;
605                                         }
606                                 }
607                         }
608
609                         // skip WS
610                         while (ifs && isSpace(ch)) {
611                                 ifs.get(ch);
612                         }
613
614                         if (!ifs)
615                                 return false;
616
617                         // continue reading next value on concatenate with '#'
618                 } while (ch == '#');
619
620                 ifs.putback(ch);
621
622                 return true;
623         }
624 }
625
626
627 // This method returns a comma separated list of Bibtex entries
628 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
629                 BiblioInfo & keylist, InsetIterator const & /*di*/) const
630 {
631         EmbeddedFileList const files = getFiles(buffer);
632         for (vector<EmbeddedFile>::const_iterator it = files.begin();
633              it != files.end(); ++ it) {
634                 // This bibtex parser is a first step to parse bibtex files
635                 // more precisely.
636                 //
637                 // - it reads the whole bibtex entry and does a syntax check
638                 //   (matching delimiters, missing commas,...
639                 // - it recovers from errors starting with the next @-character
640                 // - it reads @string definitions and replaces them in the
641                 //   field values.
642                 // - it accepts more characters in keys or value names than
643                 //   bibtex does.
644                 //
645                 // Officially bibtex does only support ASCII, but in practice
646                 // you can use the encoding of the main document as long as
647                 // some elements like keys and names are pure ASCII. Therefore
648                 // we convert the file from the buffer encoding.
649                 // We don't restrict keys to ASCII in LyX, since our own
650                 // InsetBibitem can generate non-ASCII keys, and nonstandard
651                 // 8bit clean bibtex forks exist.
652                 
653                 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
654                         ios_base::in,
655                         buffer.params().encoding().iconvName());
656
657                 char_type ch;
658                 VarMap strings;
659
660                 while (ifs) {
661
662                         ifs.get(ch);
663                         if (!ifs)
664                                 break;
665
666                         if (ch != '@')
667                                 continue;
668
669                         docstring entryType;
670
671                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), 
672                                            docstring(), makeLowerCase) || !ifs)
673                                 continue;
674
675                         if (entryType == from_ascii("comment")) {
676
677                                 ifs.ignore(numeric_limits<int>::max(), '\n');
678                                 continue;
679                         }
680
681                         ifs.get(ch);
682                         if (!ifs)
683                                 break;
684
685                         if ((ch != '(') && (ch != '{')) {
686                                 // invalid entry delimiter
687                                 ifs.putback(ch);
688                                 continue;
689                         }
690
691                         // process the entry
692                         if (entryType == from_ascii("string")) {
693
694                                 // read string and add it to the strings map
695                                 // (or replace it's old value)
696                                 docstring name;
697                                 docstring value;
698
699                                 if (!readTypeOrKey(name, ifs, from_ascii("="), 
700                                                    from_ascii("#{}(),"), makeLowerCase) || !ifs)
701                                         continue;
702
703                                 // next char must be an equal sign
704                                 ifs.get(ch);
705                                 if (!ifs || ch != '=')
706                                         continue;
707
708                                 if (!readValue(value, ifs, strings))
709                                         continue;
710
711                                 strings[name] = value;
712
713                         } else if (entryType == from_ascii("preamble")) {
714
715                                 // preamble definitions are discarded.
716                                 // can they be of any use in lyx?
717                                 docstring value;
718
719                                 if (!readValue(value, ifs, strings))
720                                         continue;
721
722                         } else {
723
724                                 // Citation entry. Try to read the key.
725                                 docstring key;
726
727                                 if (!readTypeOrKey(key, ifs, from_ascii(","), 
728                                                    from_ascii("}"), keepCase) || !ifs)
729                                         continue;
730
731                                 /////////////////////////////////////////////
732                                 // now we have a key, so we will add an entry 
733                                 // (even if it's empty, as bibtex does)
734                                 //
735                                 // we now read the field = value pairs.
736                                 // all items must be separated by a comma. If
737                                 // it is missing the scanning of this entry is
738                                 // stopped and the next is searched.
739                                 docstring fields;
740                                 docstring name;
741                                 docstring value;
742                                 docstring commaNewline;
743                                 docstring data;
744                                 BibTeXInfo keyvalmap;
745                                 keyvalmap.entryType = entryType;
746                                 
747                                 bool readNext = removeWSAndComma(ifs);
748  
749                                 while (ifs && readNext) {
750
751                                         // read field name
752                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
753                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
754                                                 break;
755
756                                         // next char must be an equal sign
757                                         ifs.get(ch);
758                                         if (!ifs)
759                                                 break;
760                                         if (ch != '=') {
761                                                 ifs.putback(ch);
762                                                 break;
763                                         }
764
765                                         // read field value
766                                         if (!readValue(value, ifs, strings))
767                                                 break;
768
769                                         keyvalmap[name] = value;
770                                         data += "\n\n" + value;
771                                         keylist.fieldNames.insert(name);
772                                         readNext = removeWSAndComma(ifs);
773                                 }
774
775                                 // add the new entry
776                                 keylist.entryTypes.insert(entryType);
777                                 keyvalmap.allData = data;
778                                 keyvalmap.isBibTeX = true;
779                                 keyvalmap.bibKey = key;
780                                 keylist[key] = keyvalmap;
781                         }
782                 } //< searching '@'
783         } //< for loop over files
784 }
785
786
787
788 bool InsetBibtex::addDatabase(string const & db)
789 {
790         // FIXME UNICODE
791         string bibfiles(to_utf8(getParam("bibfiles")));
792         if (tokenPos(bibfiles, ',', db) == -1) {
793                 if (!bibfiles.empty())
794                         bibfiles += ',';
795                 setParam("bibfiles", from_utf8(bibfiles + db));
796                 return true;
797         }
798         return false;
799 }
800
801
802 bool InsetBibtex::delDatabase(string const & db)
803 {
804         // FIXME UNICODE
805         string bibfiles(to_utf8(getParam("bibfiles")));
806         if (contains(bibfiles, db)) {
807                 int const n = tokenPos(bibfiles, ',', db);
808                 string bd = db;
809                 if (n > 0) {
810                         // this is not the first database
811                         string tmp = ',' + bd;
812                         setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
813                 } else if (n == 0)
814                         // this is the first (or only) database
815                         setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
816                 else
817                         return false;
818         }
819         return true;
820 }
821
822
823 void InsetBibtex::validate(LaTeXFeatures & features) const
824 {
825         if (features.bufferParams().use_bibtopic)
826                 features.require("bibtopic");
827 }
828
829
830 void InsetBibtex::registerEmbeddedFiles(Buffer const & buffer, EmbeddedFileList & files) const
831 {
832         EmbeddedFileList const dbs = getFiles(buffer);
833         for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
834                 it != dbs.end(); ++ it)
835                 files.registerFile(*it, this, buffer);          
836 }
837
838
839 void InsetBibtex::updateEmbeddedFile(Buffer const & buf, EmbeddedFile const & file)
840 {
841         // look for the item and update status
842         docstring bibfiles;
843         docstring embed;
844
845         bool first = true;
846         EmbeddedFileList dbs = getFiles(buf);
847         for (EmbeddedFileList::iterator it = dbs.begin();
848                 it != dbs.end(); ++ it) {
849                 // update from file
850                 if (it->absFilename() == file.absFilename())
851                         it->setEmbed(file.embedded());
852                 // write parameter string
853                 if (!first) {
854                         bibfiles += ',';
855                         embed += ',';
856                 } else
857                         first = false;
858                 bibfiles += from_utf8(it->outputFilename(buf.filePath()));
859                 if (it->embedded())
860                         embed += from_utf8(it->inzipName());
861         }
862         setParam("bibfiles", bibfiles);
863         setParam("embed", embed);
864 }
865
866
867 } // namespace lyx