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