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