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