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