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