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/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"
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 createBibFiles(p["bibfiles"], p["embed"]);
91 buffer().updateBibfilesCache();
96 InsetCommand::doDispatch(cur, cmd);
102 docstring InsetBibtex::screenLabel() const
104 return _("BibTeX Generated Bibliography");
108 static string normalizeName(Buffer const & buffer,
109 OutputParams const & runparams, string const & name, string const & ext)
111 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
112 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
118 return to_utf8(makeRelPath(from_utf8(fname),
119 from_utf8(buffer.masterBuffer()->filePath())));
123 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
125 // the sequence of the commands:
126 // 1. \bibliographystyle{style}
127 // 2. \addcontentsline{...} - if option bibtotoc set
128 // 3. \bibliography{database}
129 // and with bibtopic:
130 // 1. \bibliographystyle{style}
131 // 2. \begin{btSect}{database}
132 // 3. \btPrint{Cited|NotCited|All}
136 // If we are processing the LaTeX file in a temp directory then
137 // copy the .bib databases to this temp directory, mangling their
138 // names in the process. Store this mangled name in the list of
140 // (We need to do all this because BibTeX *really*, *really*
141 // can't handle "files with spaces" and Windows users tend to
142 // use such filenames.)
143 // Otherwise, store the (maybe absolute) path to the original,
144 // unmangled database name.
145 EmbeddedFileList::const_iterator it = bibfiles_.begin();
146 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
147 odocstringstream dbs;
148 for (; it != it_end; ++it) {
149 string utf8input = removeExtension(it->availableFile().absFilename());
151 normalizeName(buffer(), runparams, utf8input, ".bib");
152 FileName const try_in_file =
153 makeAbsPath(database + ".bib", buffer().filePath());
154 bool const not_from_texmf = try_in_file.isReadableFile();
156 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
159 // mangledFilename() needs the extension
160 DocFileName const in_file = DocFileName(try_in_file);
161 database = removeExtension(in_file.mangledFilename());
162 FileName const out_file = makeAbsPath(database + ".bib",
163 buffer().masterBuffer()->temppath());
165 bool const success = in_file.copyTo(out_file);
167 lyxerr << "Failed to copy '" << in_file
168 << "' to '" << out_file << "'"
171 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
172 !isValidLaTeXFilename(database)) {
173 frontend::Alert::warning(_("Invalid filename"),
174 _("The following filename is likely to cause trouble "
175 "when running the exported file through LaTeX: ") +
176 from_utf8(database));
179 if (it != bibfiles_.begin())
182 dbs << from_utf8(latex_path(database));
184 docstring const db_out = dbs.str();
186 // Post this warning only once.
187 static bool warned_about_spaces = false;
188 if (!warned_about_spaces &&
189 runparams.nice && db_out.find(' ') != docstring::npos) {
190 warned_about_spaces = true;
192 Alert::warning(_("Export Warning!"),
193 _("There are spaces in the paths to your BibTeX databases.\n"
194 "BibTeX will be unable to find them."));
198 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
200 if (prefixIs(style, "bibtotoc")) {
201 bibtotoc = "bibtotoc";
202 if (contains(style, ','))
203 style = split(style, bibtotoc, ',');
209 if (!style.empty()) {
210 string base = normalizeName(buffer(), runparams, style, ".bst");
211 FileName const try_in_file =
212 makeAbsPath(base + ".bst", buffer().filePath());
213 bool const not_from_texmf = try_in_file.isReadableFile();
214 // If this style does not come from texmf and we are not
215 // exporting to .tex copy it to the tmp directory.
216 // This prevents problems with spaces and 8bit charcaters
218 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
220 // use new style name
221 DocFileName const in_file = DocFileName(try_in_file);
222 base = removeExtension(in_file.mangledFilename());
223 FileName const out_file = makeAbsPath(base + ".bst",
224 buffer().masterBuffer()->temppath());
225 bool const success = in_file.copyTo(out_file);
227 lyxerr << "Failed to copy '" << in_file
228 << "' to '" << out_file << "'"
233 os << "\\bibliographystyle{"
234 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
239 // Post this warning only once.
240 static bool warned_about_bst_spaces = false;
241 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
242 warned_about_bst_spaces = true;
243 Alert::warning(_("Export Warning!"),
244 _("There are spaces in the path to your BibTeX style file.\n"
245 "BibTeX will be unable to find it."));
248 if (!db_out.empty() && buffer().params().use_bibtopic) {
249 os << "\\begin{btSect}{" << db_out << "}\n";
250 docstring btprint = getParam("btprint");
253 btprint = from_ascii("btPrintCited");
254 os << "\\" << btprint << "\n"
255 << "\\end{btSect}\n";
260 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
261 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
262 if (buffer().params().sides == OneSide) {
267 os << "\\cleardoublepage";
269 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
270 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
271 os << "\\addcontentsline{toc}{section}{\\refname}";
274 if (!db_out.empty() && !buffer().params().use_bibtopic) {
275 docstring btprint = getParam("btprint");
276 if (btprint == "btPrintAll") {
277 os << "\\nocite{*}\n";
280 os << "\\bibliography{" << db_out << "}\n";
288 EmbeddedFileList InsetBibtex::embeddedFiles() const
295 // methods for parsing bibtex files
297 typedef map<docstring, docstring> VarMap;
299 /// remove whitespace characters, optionally a single comma,
300 /// and further whitespace characters from the stream.
301 /// @return true if a comma was found, false otherwise
303 bool removeWSAndComma(idocfstream & ifs) {
312 } while (ifs && isSpace(ch));
325 } while (ifs && isSpace(ch));
340 /// remove whitespace characters, read characer sequence
341 /// not containing whitespace characters or characters in
342 /// delimChars, and remove further whitespace characters.
344 /// @return true if a string of length > 0 could be read.
346 bool readTypeOrKey(docstring & val, idocfstream & ifs,
347 docstring const & delimChars, docstring const &illegalChars,
360 } while (ifs && isSpace(ch));
366 bool legalChar = true;
367 while (ifs && !isSpace(ch) &&
368 delimChars.find(ch) == docstring::npos &&
369 (legalChar = (illegalChars.find(ch) == docstring::npos))
372 if (chCase == makeLowerCase)
373 val += lowercase(ch);
385 while (ifs && isSpace(ch)) {
393 return val.length() > 0;
396 /// read subsequent bibtex values that are delimited with a #-character.
397 /// Concatenate all parts and replace names with the associated string in
398 /// the variable strings.
399 /// @return true if reading was successfull (all single parts were delimited
401 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
414 } while (ifs && isSpace(ch));
419 // check for field type
422 // read integer value
426 } while (ifs && isDigit(ch));
431 } else if (ch == '"' || ch == '{') {
433 char_type delim = ch == '"' ? '"': '}';
438 } while (ifs && isSpace(ch));
443 //We now have the first non-whitespace character
444 //We'll collapse adjacent whitespace.
445 bool lastWasWhiteSpace = false;
447 // inside this delimited text braces must match.
448 // Thus we can have a closing delimiter only
449 // when nestLevel == 0
452 while (ifs && (nestLevel > 0 || ch != delim)) {
454 lastWasWhiteSpace = true;
458 //We output the space only after we stop getting
459 //whitespace so as not to output any whitespace
460 //at the end of the value.
461 if (lastWasWhiteSpace) {
462 lastWasWhiteSpace = false;
468 // update nesting level
475 if (nestLevel < 0) return false;
492 // reading a string name
495 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
496 strName += lowercase(ch);
503 // replace the string with its assigned value or
504 // discard it if it's not assigned
505 if (strName.length()) {
506 VarMap::const_iterator pos = strings.find(strName);
507 if (pos != strings.end()) {
514 while (ifs && isSpace(ch)) {
521 // continue reading next value on concatenate with '#'
531 // This method returns a comma separated list of Bibtex entries
532 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
533 InsetIterator const & /*di*/) const
535 EmbeddedFileList const files = embeddedFiles();
536 for (vector<EmbeddedFile>::const_iterator it = files.begin();
537 it != files.end(); ++ it) {
538 // This bibtex parser is a first step to parse bibtex files
541 // - it reads the whole bibtex entry and does a syntax check
542 // (matching delimiters, missing commas,...
543 // - it recovers from errors starting with the next @-character
544 // - it reads @string definitions and replaces them in the
546 // - it accepts more characters in keys or value names than
549 // Officially bibtex does only support ASCII, but in practice
550 // you can use the encoding of the main document as long as
551 // some elements like keys and names are pure ASCII. Therefore
552 // we convert the file from the buffer encoding.
553 // We don't restrict keys to ASCII in LyX, since our own
554 // InsetBibitem can generate non-ASCII keys, and nonstandard
555 // 8bit clean bibtex forks exist.
557 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
558 ios_base::in, buffer().params().encoding().iconvName());
574 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
575 docstring(), makeLowerCase) || !ifs)
578 if (entryType == from_ascii("comment")) {
580 ifs.ignore(numeric_limits<int>::max(), '\n');
588 if ((ch != '(') && (ch != '{')) {
589 // invalid entry delimiter
595 if (entryType == from_ascii("string")) {
597 // read string and add it to the strings map
598 // (or replace it's old value)
602 if (!readTypeOrKey(name, ifs, from_ascii("="),
603 from_ascii("#{}(),"), makeLowerCase) || !ifs)
606 // next char must be an equal sign
608 if (!ifs || ch != '=')
611 if (!readValue(value, ifs, strings))
614 strings[name] = value;
616 } else if (entryType == from_ascii("preamble")) {
618 // preamble definitions are discarded.
619 // can they be of any use in lyx?
622 if (!readValue(value, ifs, strings))
627 // Citation entry. Try to read the key.
630 if (!readTypeOrKey(key, ifs, from_ascii(","),
631 from_ascii("}"), keepCase) || !ifs)
634 /////////////////////////////////////////////
635 // now we have a key, so we will add an entry
636 // (even if it's empty, as bibtex does)
638 // we now read the field = value pairs.
639 // all items must be separated by a comma. If
640 // it is missing the scanning of this entry is
641 // stopped and the next is searched.
645 docstring commaNewline;
647 BibTeXInfo keyvalmap(key, entryType);
649 bool readNext = removeWSAndComma(ifs);
651 while (ifs && readNext) {
654 if (!readTypeOrKey(name, ifs, from_ascii("="),
655 from_ascii("{}(),"), makeLowerCase) || !ifs)
658 // next char must be an equal sign
668 if (!readValue(value, ifs, strings))
671 keyvalmap[name] = value;
672 data += "\n\n" + value;
673 keylist.addFieldName(name);
674 readNext = removeWSAndComma(ifs);
678 keylist.addEntryType(entryType);
679 keyvalmap.setAllData(data);
680 keylist[key] = keyvalmap;
683 } //< for loop over files
688 bool InsetBibtex::addDatabase(string const & db)
690 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
692 // only compare filename
693 EmbeddedFileList::iterator it = bibfiles_.begin();
694 EmbeddedFileList::iterator it_end = bibfiles_.end();
695 for (; it != it_end; ++it)
696 if (it->absFilename() == file.absFilename())
699 bibfiles_.push_back(file);
705 bool InsetBibtex::delDatabase(string const & db)
707 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
709 // only compare filename
710 EmbeddedFileList::iterator it = bibfiles_.begin();
711 EmbeddedFileList::iterator it_end = bibfiles_.end();
712 for (; it != it_end; ++it)
713 if (it->absFilename() == file.absFilename()) {
722 void InsetBibtex::validate(LaTeXFeatures & features) const
724 if (features.bufferParams().use_bibtopic)
725 features.require("bibtopic");
729 void InsetBibtex::createBibFiles(docstring const & bibParam,
730 docstring const & embedParam) const
737 string bibfiles = to_utf8(bibParam);
738 string embedStatus = to_utf8(embedParam);
740 LYXERR(Debug::FILES, "Create bib files from parameters "
741 << bibfiles << " and " << embedStatus);
743 bibfiles = split(bibfiles, tmp, ',');
744 embedStatus = split(embedStatus, emb, ',');
746 while (!tmp.empty()) {
747 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
749 file.setInzipName(emb);
750 file.setEmbed(!emb.empty());
751 file.enable(buffer().embedded(), &buffer(), false);
752 bibfiles_.push_back(file);
753 // Get next file name
754 bibfiles = split(bibfiles, tmp, ',');
755 embedStatus = split(embedStatus, emb, ',');
760 void InsetBibtex::updateParam()
766 for (EmbeddedFileList::iterator it = bibfiles_.begin();
767 it != bibfiles_.end(); ++it) {
773 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
775 embed += from_utf8(it->inzipName());
777 setParam("bibfiles", bibfiles);
778 setParam("embed", embed);
782 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
784 if (bibfiles_.empty())
785 createBibFiles(params()["bibfiles"], params()["embed"]);
787 EmbeddedFileList::const_iterator it = bibfiles_.begin();
788 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
789 for (; it != it_end; ++it)
790 files.registerFile(*it, this, buffer());
794 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
796 // look for the item and update status
797 for (EmbeddedFileList::iterator it = bibfiles_.begin();
798 it != bibfiles_.end(); ++it)
799 if (it->absFilename() == file.absFilename())