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