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