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