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 void InsetBibtex::setBuffer(Buffer & buffer)
58 EmbeddedFileList::iterator it = bibfiles_.begin();
59 EmbeddedFileList::iterator it_end = bibfiles_.end();
60 for (; it != it_end; ++it) {
62 *it = it->copyTo(&buffer);
63 } catch (ExceptionMessage const & message) {
64 Alert::error(message.title_, message.details_);
70 Inset::setBuffer(buffer);
74 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
76 static ParamInfo param_info_;
77 if (param_info_.empty()) {
78 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
79 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
80 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
81 param_info_.add("options", ParamInfo::LYX_INTERNAL);
87 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
91 case LFUN_INSET_MODIFY: {
92 InsetCommandParams p(BIBTEX_CODE);
94 if (!InsetCommandMailer::string2params("bibtex",
95 to_utf8(cmd.argument()), p)) {
99 } catch (ExceptionMessage const & message) {
100 if (message.type_ == WarningException) {
101 Alert::warning(message.title_, message.details_);
108 createBibFiles(p["bibfiles"], p["embed"]);
110 setParam("options", p["options"]);
111 buffer().updateBibfilesCache();
116 InsetCommand::doDispatch(cur, cmd);
122 docstring InsetBibtex::screenLabel() const
124 return _("BibTeX Generated Bibliography");
128 static string normalizeName(Buffer const & buffer,
129 OutputParams const & runparams, string const & name, string const & ext)
131 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
132 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
138 return to_utf8(makeRelPath(from_utf8(fname),
139 from_utf8(buffer.masterBuffer()->filePath())));
143 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
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}
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
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());
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();
176 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
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());
185 bool const success = in_file.copyTo(out_file);
187 lyxerr << "Failed to copy '" << in_file
188 << "' to '" << out_file << "'"
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));
199 if (it != bibfiles_.begin())
202 dbs << from_utf8(latex_path(database));
204 docstring const db_out = dbs.str();
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;
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."));
218 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
220 if (prefixIs(style, "bibtotoc")) {
221 bibtotoc = "bibtotoc";
222 if (contains(style, ','))
223 style = split(style, bibtotoc, ',');
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
238 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
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);
247 lyxerr << "Failed to copy '" << in_file
248 << "' to '" << out_file << "'"
253 os << "\\bibliographystyle{"
254 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
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."));
268 if (!db_out.empty() && buffer().params().use_bibtopic) {
269 os << "\\begin{btSect}{" << db_out << "}\n";
270 docstring btprint = getParam("btprint");
273 btprint = from_ascii("btPrintCited");
274 os << "\\" << btprint << "\n"
275 << "\\end{btSect}\n";
280 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
281 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
282 if (buffer().params().sides == OneSide) {
287 os << "\\cleardoublepage";
289 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
290 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
291 os << "\\addcontentsline{toc}{section}{\\refname}";
294 if (!db_out.empty() && !buffer().params().use_bibtopic) {
295 docstring btprint = getParam("btprint");
296 if (btprint == "btPrintAll") {
297 os << "\\nocite{*}\n";
300 os << "\\bibliography{" << db_out << "}\n";
308 EmbeddedFileList InsetBibtex::embeddedFiles() const
315 // methods for parsing bibtex files
317 typedef map<docstring, docstring> VarMap;
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
323 bool removeWSAndComma(idocfstream & ifs) {
332 } while (ifs && isSpace(ch));
345 } while (ifs && isSpace(ch));
360 /// remove whitespace characters, read characer sequence
361 /// not containing whitespace characters or characters in
362 /// delimChars, and remove further whitespace characters.
364 /// @return true if a string of length > 0 could be read.
366 bool readTypeOrKey(docstring & val, idocfstream & ifs,
367 docstring const & delimChars, docstring const &illegalChars,
380 } while (ifs && isSpace(ch));
386 bool legalChar = true;
387 while (ifs && !isSpace(ch) &&
388 delimChars.find(ch) == docstring::npos &&
389 (legalChar = (illegalChars.find(ch) == docstring::npos))
392 if (chCase == makeLowerCase)
393 val += lowercase(ch);
405 while (ifs && isSpace(ch)) {
413 return val.length() > 0;
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
421 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
434 } while (ifs && isSpace(ch));
439 // check for field type
442 // read integer value
446 } while (ifs && isDigit(ch));
451 } else if (ch == '"' || ch == '{') {
453 char_type delim = ch == '"' ? '"': '}';
458 } while (ifs && isSpace(ch));
463 //We now have the first non-whitespace character
464 //We'll collapse adjacent whitespace.
465 bool lastWasWhiteSpace = false;
467 // inside this delimited text braces must match.
468 // Thus we can have a closing delimiter only
469 // when nestLevel == 0
472 while (ifs && (nestLevel > 0 || ch != delim)) {
474 lastWasWhiteSpace = true;
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;
488 // update nesting level
495 if (nestLevel < 0) return false;
512 // reading a string name
515 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
516 strName += lowercase(ch);
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()) {
534 while (ifs && isSpace(ch)) {
541 // continue reading next value on concatenate with '#'
551 // This method returns a comma separated list of Bibtex entries
552 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
553 InsetIterator const & /*di*/) const
555 EmbeddedFileList const files = embeddedFiles();
556 for (vector<EmbeddedFile>::const_iterator it = files.begin();
557 it != files.end(); ++ it) {
558 // This bibtex parser is a first step to parse bibtex files
561 // - it reads the whole bibtex entry and does a syntax check
562 // (matching delimiters, missing commas,...
563 // - it recovers from errors starting with the next @-character
564 // - it reads @string definitions and replaces them in the
566 // - it accepts more characters in keys or value names than
569 // Officially bibtex does only support ASCII, but in practice
570 // you can use the encoding of the main document as long as
571 // some elements like keys and names are pure ASCII. Therefore
572 // we convert the file from the buffer encoding.
573 // We don't restrict keys to ASCII in LyX, since our own
574 // InsetBibitem can generate non-ASCII keys, and nonstandard
575 // 8bit clean bibtex forks exist.
577 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
578 ios_base::in, buffer().params().encoding().iconvName());
594 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
595 docstring(), makeLowerCase) || !ifs)
598 if (entryType == from_ascii("comment")) {
600 ifs.ignore(numeric_limits<int>::max(), '\n');
608 if ((ch != '(') && (ch != '{')) {
609 // invalid entry delimiter
615 if (entryType == from_ascii("string")) {
617 // read string and add it to the strings map
618 // (or replace it's old value)
622 if (!readTypeOrKey(name, ifs, from_ascii("="),
623 from_ascii("#{}(),"), makeLowerCase) || !ifs)
626 // next char must be an equal sign
628 if (!ifs || ch != '=')
631 if (!readValue(value, ifs, strings))
634 strings[name] = value;
636 } else if (entryType == from_ascii("preamble")) {
638 // preamble definitions are discarded.
639 // can they be of any use in lyx?
642 if (!readValue(value, ifs, strings))
647 // Citation entry. Try to read the key.
650 if (!readTypeOrKey(key, ifs, from_ascii(","),
651 from_ascii("}"), keepCase) || !ifs)
654 /////////////////////////////////////////////
655 // now we have a key, so we will add an entry
656 // (even if it's empty, as bibtex does)
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.
665 docstring commaNewline;
667 BibTeXInfo keyvalmap(key, entryType);
669 bool readNext = removeWSAndComma(ifs);
671 while (ifs && readNext) {
674 if (!readTypeOrKey(name, ifs, from_ascii("="),
675 from_ascii("{}(),"), makeLowerCase) || !ifs)
678 // next char must be an equal sign
688 if (!readValue(value, ifs, strings))
691 keyvalmap[name] = value;
692 data += "\n\n" + value;
693 keylist.addFieldName(name);
694 readNext = removeWSAndComma(ifs);
698 keylist.addEntryType(entryType);
699 keyvalmap.setAllData(data);
700 keylist[key] = keyvalmap;
703 } //< for loop over files
708 bool InsetBibtex::addDatabase(string const & db)
710 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
712 // only compare filename
713 EmbeddedFileList::iterator it = bibfiles_.begin();
714 EmbeddedFileList::iterator it_end = bibfiles_.end();
715 for (; it != it_end; ++it)
716 if (it->absFilename() == file.absFilename())
719 bibfiles_.push_back(file);
725 bool InsetBibtex::delDatabase(string const & db)
727 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
729 // only compare filename
730 EmbeddedFileList::iterator it = bibfiles_.begin();
731 EmbeddedFileList::iterator it_end = bibfiles_.end();
732 for (; it != it_end; ++it)
733 if (it->absFilename() == file.absFilename()) {
742 void InsetBibtex::validate(LaTeXFeatures & features) const
744 if (features.bufferParams().use_bibtopic)
745 features.require("bibtopic");
749 void InsetBibtex::createBibFiles(docstring const & bibParam,
750 docstring const & embedParam) const
757 string bibfiles = to_utf8(bibParam);
758 string embedStatus = to_utf8(embedParam);
760 LYXERR(Debug::FILES, "Create bib files from parameters "
761 << bibfiles << " and " << embedStatus);
763 bibfiles = split(bibfiles, tmp, ',');
764 embedStatus = split(embedStatus, emb, ',');
766 while (!tmp.empty()) {
767 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
769 file.setInzipName(emb);
770 file.setEmbed(!emb.empty());
771 file.enable(buffer().embedded(), &buffer(), false);
772 bibfiles_.push_back(file);
773 // Get next file name
774 bibfiles = split(bibfiles, tmp, ',');
775 embedStatus = split(embedStatus, emb, ',');
780 void InsetBibtex::updateParam()
787 EmbeddedFileList::iterator it = bibfiles_.begin();
788 EmbeddedFileList::iterator en = bibfiles_.end();
789 for (; it != en; ++it) {
795 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
797 embed += from_utf8(it->inzipName());
799 setParam("bibfiles", bibfiles);
800 setParam("embed", embed);
804 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
806 if (bibfiles_.empty())
807 createBibFiles(params()["bibfiles"], params()["embed"]);
809 EmbeddedFileList::const_iterator it = bibfiles_.begin();
810 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
811 for (; it != it_end; ++it)
812 files.registerFile(*it, this, buffer());
816 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
818 // look for the item and update status
819 for (EmbeddedFileList::iterator it = bibfiles_.begin();
820 it != bibfiles_.end(); ++it)
821 if (it->absFilename() == file.absFilename())