2 * \file InsetBibtex.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Richard Heck (BibTeX parser improvements)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetBibtex.h"
17 #include "BufferParams.h"
18 #include "DispatchResult.h"
19 #include "EmbeddedFiles.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "MetricsInfo.h"
24 #include "OutputParams.h"
25 #include "TextClass.h"
27 #include "frontends/alert.h"
29 #include "support/debug.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/docstream.h"
32 #include "support/filetools.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35 #include "support/os.h"
36 #include "support/Path.h"
37 #include "support/textutils.h"
42 using namespace lyx::support;
46 namespace Alert = frontend::Alert;
47 namespace os = support::os;
50 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
51 : InsetCommand(p, "bibtex"), bibfiles_()
55 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
57 static ParamInfo param_info_;
58 if (param_info_.empty()) {
59 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
60 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
61 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
62 param_info_.add("options", ParamInfo::LYX_INTERNAL);
68 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
72 case LFUN_INSET_MODIFY: {
73 InsetCommandParams p(BIBTEX_CODE);
75 if (!InsetCommandMailer::string2params("bibtex",
76 to_utf8(cmd.argument()), p)) {
80 } catch (ExceptionMessage const & message) {
81 if (message.type_ == WarningException) {
82 Alert::warning(message.title_, message.details_);
89 InsetCommandParams orig = params();
91 // returned "embed" is composed of "true" or "false", which needs to be adjusted
92 createBibFiles(p["bibfiles"], p["embed"], true, true);
94 } catch (ExceptionMessage const & message) {
95 Alert::error(message.title_, message.details_);
96 // do not set parameter if an error happens
100 buffer().updateBibfilesCache();
105 InsetCommand::doDispatch(cur, cmd);
111 docstring InsetBibtex::screenLabel() const
113 return _("BibTeX Generated Bibliography");
117 static string normalizeName(Buffer const & buffer,
118 OutputParams const & runparams, string const & name, string const & ext)
120 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
121 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
127 return to_utf8(makeRelPath(from_utf8(fname),
128 from_utf8(buffer.masterBuffer()->filePath())));
132 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
134 // the sequence of the commands:
135 // 1. \bibliographystyle{style}
136 // 2. \addcontentsline{...} - if option bibtotoc set
137 // 3. \bibliography{database}
138 // and with bibtopic:
139 // 1. \bibliographystyle{style}
140 // 2. \begin{btSect}{database}
141 // 3. \btPrint{Cited|NotCited|All}
145 // If we are processing the LaTeX file in a temp directory then
146 // copy the .bib databases to this temp directory, mangling their
147 // names in the process. Store this mangled name in the list of
149 // (We need to do all this because BibTeX *really*, *really*
150 // can't handle "files with spaces" and Windows users tend to
151 // use such filenames.)
152 // Otherwise, store the (maybe absolute) path to the original,
153 // unmangled database name.
154 EmbeddedFileList::const_iterator it = bibfiles_.begin();
155 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
156 odocstringstream dbs;
157 for (; it != it_end; ++it) {
158 string utf8input = removeExtension(it->availableFile().absFilename());
160 normalizeName(buffer(), runparams, utf8input, ".bib");
161 FileName const try_in_file =
162 makeAbsPath(database + ".bib", buffer().filePath());
163 bool const not_from_texmf = try_in_file.isReadableFile();
165 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
168 // mangledFilename() needs the extension
169 DocFileName const in_file = DocFileName(try_in_file);
170 database = removeExtension(in_file.mangledFilename());
171 FileName const out_file = makeAbsPath(database + ".bib",
172 buffer().masterBuffer()->temppath());
174 bool const success = in_file.copyTo(out_file);
176 lyxerr << "Failed to copy '" << in_file
177 << "' to '" << out_file << "'"
180 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
181 !isValidLaTeXFilename(database)) {
182 frontend::Alert::warning(_("Invalid filename"),
183 _("The following filename is likely to cause trouble "
184 "when running the exported file through LaTeX: ") +
185 from_utf8(database));
188 if (it != bibfiles_.begin())
191 dbs << from_utf8(latex_path(database));
193 docstring const db_out = dbs.str();
195 // Post this warning only once.
196 static bool warned_about_spaces = false;
197 if (!warned_about_spaces &&
198 runparams.nice && db_out.find(' ') != docstring::npos) {
199 warned_about_spaces = true;
201 Alert::warning(_("Export Warning!"),
202 _("There are spaces in the paths to your BibTeX databases.\n"
203 "BibTeX will be unable to find them."));
207 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
209 if (prefixIs(style, "bibtotoc")) {
210 bibtotoc = "bibtotoc";
211 if (contains(style, ','))
212 style = split(style, bibtotoc, ',');
218 if (!style.empty()) {
219 string base = normalizeName(buffer(), runparams, style, ".bst");
220 FileName const try_in_file =
221 makeAbsPath(base + ".bst", buffer().filePath());
222 bool const not_from_texmf = try_in_file.isReadableFile();
223 // If this style does not come from texmf and we are not
224 // exporting to .tex copy it to the tmp directory.
225 // This prevents problems with spaces and 8bit charcaters
227 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
229 // use new style name
230 DocFileName const in_file = DocFileName(try_in_file);
231 base = removeExtension(in_file.mangledFilename());
232 FileName const out_file = makeAbsPath(base + ".bst",
233 buffer().masterBuffer()->temppath());
234 bool const success = in_file.copyTo(out_file);
236 lyxerr << "Failed to copy '" << in_file
237 << "' to '" << out_file << "'"
242 os << "\\bibliographystyle{"
243 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
248 // Post this warning only once.
249 static bool warned_about_bst_spaces = false;
250 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
251 warned_about_bst_spaces = true;
252 Alert::warning(_("Export Warning!"),
253 _("There are spaces in the path to your BibTeX style file.\n"
254 "BibTeX will be unable to find it."));
257 if (!db_out.empty() && buffer().params().use_bibtopic) {
258 os << "\\begin{btSect}{" << db_out << "}\n";
259 docstring btprint = getParam("btprint");
262 btprint = from_ascii("btPrintCited");
263 os << "\\" << btprint << "\n"
264 << "\\end{btSect}\n";
269 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
270 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
271 if (buffer().params().sides == OneSide) {
276 os << "\\cleardoublepage";
278 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
279 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
280 os << "\\addcontentsline{toc}{section}{\\refname}";
283 if (!db_out.empty() && !buffer().params().use_bibtopic) {
284 docstring btprint = getParam("btprint");
285 if (btprint == "btPrintAll") {
286 os << "\\nocite{*}\n";
289 os << "\\bibliography{" << db_out << "}\n";
297 EmbeddedFileList InsetBibtex::embeddedFiles() const
304 // methods for parsing bibtex files
306 typedef map<docstring, docstring> VarMap;
308 /// remove whitespace characters, optionally a single comma,
309 /// and further whitespace characters from the stream.
310 /// @return true if a comma was found, false otherwise
312 bool removeWSAndComma(idocfstream & ifs) {
321 } while (ifs && isSpace(ch));
334 } while (ifs && isSpace(ch));
349 /// remove whitespace characters, read characer sequence
350 /// not containing whitespace characters or characters in
351 /// delimChars, and remove further whitespace characters.
353 /// @return true if a string of length > 0 could be read.
355 bool readTypeOrKey(docstring & val, idocfstream & ifs,
356 docstring const & delimChars, docstring const &illegalChars,
369 } while (ifs && isSpace(ch));
375 bool legalChar = true;
376 while (ifs && !isSpace(ch) &&
377 delimChars.find(ch) == docstring::npos &&
378 (legalChar = (illegalChars.find(ch) == docstring::npos))
381 if (chCase == makeLowerCase)
382 val += lowercase(ch);
394 while (ifs && isSpace(ch)) {
402 return val.length() > 0;
405 /// read subsequent bibtex values that are delimited with a #-character.
406 /// Concatenate all parts and replace names with the associated string in
407 /// the variable strings.
408 /// @return true if reading was successfull (all single parts were delimited
410 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
423 } while (ifs && isSpace(ch));
428 // check for field type
431 // read integer value
435 } while (ifs && isDigit(ch));
440 } else if (ch == '"' || ch == '{') {
442 char_type delim = ch == '"' ? '"': '}';
447 } while (ifs && isSpace(ch));
452 //We now have the first non-whitespace character
453 //We'll collapse adjacent whitespace.
454 bool lastWasWhiteSpace = false;
456 // inside this delimited text braces must match.
457 // Thus we can have a closing delimiter only
458 // when nestLevel == 0
461 while (ifs && (nestLevel > 0 || ch != delim)) {
463 lastWasWhiteSpace = true;
467 //We output the space only after we stop getting
468 //whitespace so as not to output any whitespace
469 //at the end of the value.
470 if (lastWasWhiteSpace) {
471 lastWasWhiteSpace = false;
477 // update nesting level
484 if (nestLevel < 0) return false;
501 // reading a string name
504 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
505 strName += lowercase(ch);
512 // replace the string with its assigned value or
513 // discard it if it's not assigned
514 if (strName.length()) {
515 VarMap::const_iterator pos = strings.find(strName);
516 if (pos != strings.end()) {
523 while (ifs && isSpace(ch)) {
530 // continue reading next value on concatenate with '#'
540 // This method returns a comma separated list of Bibtex entries
541 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
542 InsetIterator const & /*di*/) const
544 EmbeddedFileList const files = embeddedFiles();
545 for (vector<EmbeddedFile>::const_iterator it = files.begin();
546 it != files.end(); ++ it) {
547 // This bibtex parser is a first step to parse bibtex files
550 // - it reads the whole bibtex entry and does a syntax check
551 // (matching delimiters, missing commas,...
552 // - it recovers from errors starting with the next @-character
553 // - it reads @string definitions and replaces them in the
555 // - it accepts more characters in keys or value names than
558 // Officially bibtex does only support ASCII, but in practice
559 // you can use the encoding of the main document as long as
560 // some elements like keys and names are pure ASCII. Therefore
561 // we convert the file from the buffer encoding.
562 // We don't restrict keys to ASCII in LyX, since our own
563 // InsetBibitem can generate non-ASCII keys, and nonstandard
564 // 8bit clean bibtex forks exist.
566 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
567 ios_base::in, buffer().params().encoding().iconvName());
583 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
584 docstring(), makeLowerCase) || !ifs)
587 if (entryType == from_ascii("comment")) {
589 ifs.ignore(numeric_limits<int>::max(), '\n');
597 if ((ch != '(') && (ch != '{')) {
598 // invalid entry delimiter
604 if (entryType == from_ascii("string")) {
606 // read string and add it to the strings map
607 // (or replace it's old value)
611 if (!readTypeOrKey(name, ifs, from_ascii("="),
612 from_ascii("#{}(),"), makeLowerCase) || !ifs)
615 // next char must be an equal sign
617 if (!ifs || ch != '=')
620 if (!readValue(value, ifs, strings))
623 strings[name] = value;
625 } else if (entryType == from_ascii("preamble")) {
627 // preamble definitions are discarded.
628 // can they be of any use in lyx?
631 if (!readValue(value, ifs, strings))
636 // Citation entry. Try to read the key.
639 if (!readTypeOrKey(key, ifs, from_ascii(","),
640 from_ascii("}"), keepCase) || !ifs)
643 /////////////////////////////////////////////
644 // now we have a key, so we will add an entry
645 // (even if it's empty, as bibtex does)
647 // we now read the field = value pairs.
648 // all items must be separated by a comma. If
649 // it is missing the scanning of this entry is
650 // stopped and the next is searched.
654 docstring commaNewline;
656 BibTeXInfo keyvalmap(key, entryType);
658 bool readNext = removeWSAndComma(ifs);
660 while (ifs && readNext) {
663 if (!readTypeOrKey(name, ifs, from_ascii("="),
664 from_ascii("{}(),"), makeLowerCase) || !ifs)
667 // next char must be an equal sign
677 if (!readValue(value, ifs, strings))
680 keyvalmap[name] = value;
681 data += "\n\n" + value;
682 keylist.addFieldName(name);
683 readNext = removeWSAndComma(ifs);
687 keylist.addEntryType(entryType);
688 keyvalmap.setAllData(data);
689 keylist[key] = keyvalmap;
692 } //< for loop over files
697 bool InsetBibtex::addDatabase(string const & db)
699 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
701 // only compare filename
702 EmbeddedFileList::iterator it = bibfiles_.begin();
703 EmbeddedFileList::iterator it_end = bibfiles_.end();
704 for (; it != it_end; ++it)
705 if (it->absFilename() == file.absFilename())
708 bibfiles_.push_back(file);
714 bool InsetBibtex::delDatabase(string const & db)
716 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
718 // only compare filename
719 EmbeddedFileList::iterator it = bibfiles_.begin();
720 EmbeddedFileList::iterator it_end = bibfiles_.end();
721 for (; it != it_end; ++it)
722 if (it->absFilename() == file.absFilename()) {
731 void InsetBibtex::validate(LaTeXFeatures & features) const
733 if (features.bufferParams().use_bibtopic)
734 features.require("bibtopic");
738 void InsetBibtex::createBibFiles(docstring const & bibParam,
739 docstring const & embedParam, bool boolStatus, bool updateFile) const
746 string bibfiles = to_utf8(bibParam);
747 string embedStatus = to_utf8(embedParam);
749 LYXERR(Debug::FILES, "Create bib files from parameters "
750 << bibfiles << " and " << embedStatus);
752 bibfiles = split(bibfiles, tmp, ',');
753 embedStatus = split(embedStatus, emb, ',');
755 while (!tmp.empty()) {
756 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
759 BOOST_ASSERT(emb == "true" || emb == "false");
760 file.setEmbed(emb == "true");
762 file.setInzipName(emb);
763 file.setEmbed(emb != "");
765 file.enable(buffer().embedded(), &buffer(), updateFile);
766 bibfiles_.push_back(file);
767 // Get next file name
768 bibfiles = split(bibfiles, tmp, ',');
769 embedStatus = split(embedStatus, emb, ',');
774 void InsetBibtex::updateParam()
780 for (EmbeddedFileList::iterator it = bibfiles_.begin();
781 it != bibfiles_.end(); ++it) {
787 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
789 embed += from_utf8(it->inzipName());
791 setParam("bibfiles", bibfiles);
792 setParam("embed", embed);
796 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
798 if (bibfiles_.empty())
799 createBibFiles(params()["bibfiles"], params()["embed"], false, false);
801 EmbeddedFileList::const_iterator it = bibfiles_.begin();
802 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
803 for (; it != it_end; ++it)
804 files.registerFile(*it, this, buffer());
808 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
810 // look for the item and update status
811 for (EmbeddedFileList::iterator it = bibfiles_.begin();
812 it != bibfiles_.end(); ++it)
813 if (it->absFilename() == file.absFilename())