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"
16 #include "BiblioInfo.h"
18 #include "BufferParams.h"
20 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
26 #include "LaTeXFeatures.h"
27 #include "output_xhtml.h"
28 #include "OutputParams.h"
29 #include "PDFOptions.h"
30 #include "TextClass.h"
32 #include "frontends/alert.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/ExceptionMessage.h"
38 #include "support/FileNameList.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/os.h"
43 #include "support/Path.h"
44 #include "support/textutils.h"
49 using namespace lyx::support;
53 namespace Alert = frontend::Alert;
54 namespace os = support::os;
57 InsetBibtex::InsetBibtex(Buffer * buf, InsetCommandParams const & p)
58 : InsetCommand(buf, p)
60 buffer().invalidateBibinfoCache();
64 InsetBibtex::~InsetBibtex()
67 buffer().invalidateBibfileCache();
71 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
73 static ParamInfo param_info_;
74 if (param_info_.empty()) {
75 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
76 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
77 param_info_.add("options", ParamInfo::LYX_INTERNAL);
83 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
85 switch (cmd.action()) {
91 case LFUN_INSET_MODIFY: {
92 InsetCommandParams p(BIBTEX_CODE);
94 if (!InsetCommand::string2params(to_utf8(cmd.argument()), p)) {
98 } catch (ExceptionMessage const & message) {
99 if (message.type_ == WarningException) {
100 Alert::warning(message.title_, message.details_);
101 cur.noScreenUpdate();
109 buffer().invalidateBibfileCache();
110 cur.forceBufferUpdate();
115 InsetCommand::doDispatch(cur, cmd);
121 bool InsetBibtex::getStatus(Cursor & cur, FuncRequest const & cmd,
122 FuncStatus & flag) const
124 switch (cmd.action()) {
125 case LFUN_INSET_EDIT:
126 flag.setEnabled(true);
130 return InsetCommand::getStatus(cur, cmd, flag);
135 void InsetBibtex::editDatabases() const
137 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
139 if (bibfilelist.empty())
142 int nr_databases = bibfilelist.size();
143 if (nr_databases > 1) {
144 docstring message = bformat(_("The BibTeX inset includes %1$s databases.\n"
145 "If you proceed, all of them will be opened."),
146 convert<docstring>(nr_databases));
147 int const ret = Alert::prompt(_("Open Databases?"),
148 message, 0, 1, _("&Cancel"), _("&Proceed"));
154 vector<docstring>::const_iterator it = bibfilelist.begin();
155 vector<docstring>::const_iterator en = bibfilelist.end();
156 for (; it != en; ++it) {
157 FileName const bibfile = getBibTeXPath(*it, buffer());
158 formats.edit(buffer(), bibfile,
159 formats.getFormatFromFile(bibfile));
164 docstring InsetBibtex::screenLabel() const
166 return _("BibTeX Generated Bibliography");
170 docstring InsetBibtex::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
172 docstring item = from_ascii("* ");
173 docstring tip = _("Databases:") + "\n";
174 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
176 if (bibfilelist.empty()) {
180 vector<docstring>::const_iterator it = bibfilelist.begin();
181 vector<docstring>::const_iterator en = bibfilelist.end();
182 for (; it != en; ++it) {
190 docstring style = getParam("options"); // maybe empty! and with bibtotoc
191 docstring bibtotoc = from_ascii("bibtotoc");
192 if (prefixIs(style, bibtotoc)) {
194 if (contains(style, char_type(',')))
195 style = split(style, bibtotoc, char_type(','));
198 tip += _("Style File:") +"\n";
205 tip += "\n" + _("Lists:") + " ";
206 docstring btprint = getParam("btprint");
207 if (btprint == "btPrintAll")
208 tip += _("all references");
209 else if (btprint == "btPrintNotCited")
210 tip += _("all uncited references");
212 tip += _("all cited references");
216 tip += _("included in TOC");
223 static string normalizeName(Buffer const & buffer,
224 OutputParams const & runparams, string const & name, string const & ext)
226 string const fname = makeAbsPath(name, buffer.filePath()).absFileName();
227 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
233 return to_utf8(makeRelPath(from_utf8(fname),
234 from_utf8(buffer.masterBuffer()->filePath())));
238 int InsetBibtex::latex(otexstream & os, OutputParams const & runparams) const
240 // the sequence of the commands:
241 // 1. \bibliographystyle{style}
242 // 2. \addcontentsline{...} - if option bibtotoc set
243 // 3. \bibliography{database}
244 // and with bibtopic:
245 // 1. \bibliographystyle{style}
246 // 2. \begin{btSect}{database}
247 // 3. \btPrint{Cited|NotCited|All}
251 // If we are processing the LaTeX file in a temp directory then
252 // copy the .bib databases to this temp directory, mangling their
253 // names in the process. Store this mangled name in the list of
255 // (We need to do all this because BibTeX *really*, *really*
256 // can't handle "files with spaces" and Windows users tend to
257 // use such filenames.)
258 // Otherwise, store the (maybe absolute) path to the original,
259 // unmangled database name.
260 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
261 vector<docstring>::const_iterator it = bibfilelist.begin();
262 vector<docstring>::const_iterator en = bibfilelist.end();
263 odocstringstream dbs;
266 for (; it != en; ++it) {
267 string utf8input = to_utf8(*it);
269 normalizeName(buffer(), runparams, utf8input, ".bib");
270 FileName const try_in_file =
271 makeAbsPath(database + ".bib", buffer().filePath());
272 bool const not_from_texmf = try_in_file.isReadableFile();
274 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
276 // mangledFileName() needs the extension
277 DocFileName const in_file = DocFileName(try_in_file);
278 database = removeExtension(in_file.mangledFileName());
279 FileName const out_file = makeAbsPath(database + ".bib",
280 buffer().masterBuffer()->temppath());
282 bool const success = in_file.copyTo(out_file);
284 lyxerr << "Failed to copy '" << in_file
285 << "' to '" << out_file << "'"
288 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
289 if (!isValidLaTeXFileName(database)) {
290 frontend::Alert::warning(_("Invalid filename"),
291 _("The following filename will cause troubles "
292 "when running the exported file through LaTeX: ") +
293 from_utf8(database));
295 if (!isValidDVIFileName(database)) {
296 frontend::Alert::warning(_("Problematic filename for DVI"),
297 _("The following filename can cause troubles "
298 "when running the exported file through LaTeX "
299 "and opening the resulting DVI: ") +
300 from_utf8(database), true);
309 dbs << from_utf8(latex_path(database));
311 docstring const db_out = dbs.str();
313 // Post this warning only once.
314 static bool warned_about_spaces = false;
315 if (!warned_about_spaces &&
316 runparams.nice && db_out.find(' ') != docstring::npos) {
317 warned_about_spaces = true;
318 Alert::warning(_("Export Warning!"),
319 _("There are spaces in the paths to your BibTeX databases.\n"
320 "BibTeX will be unable to find them."));
323 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
325 if (prefixIs(style, "bibtotoc")) {
326 bibtotoc = "bibtotoc";
327 if (contains(style, ','))
328 style = split(style, bibtotoc, ',');
334 if (!style.empty()) {
335 string base = normalizeName(buffer(), runparams, style, ".bst");
336 FileName const try_in_file =
337 makeAbsPath(base + ".bst", buffer().filePath());
338 bool const not_from_texmf = try_in_file.isReadableFile();
339 // If this style does not come from texmf and we are not
340 // exporting to .tex copy it to the tmp directory.
341 // This prevents problems with spaces and 8bit charcaters
343 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
345 // use new style name
346 DocFileName const in_file = DocFileName(try_in_file);
347 base = removeExtension(in_file.mangledFileName());
348 FileName const out_file = makeAbsPath(base + ".bst",
349 buffer().masterBuffer()->temppath());
350 bool const success = in_file.copyTo(out_file);
352 lyxerr << "Failed to copy '" << in_file
353 << "' to '" << out_file << "'"
358 os << "\\bibliographystyle{"
359 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
364 // Post this warning only once.
365 static bool warned_about_bst_spaces = false;
366 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
367 warned_about_bst_spaces = true;
368 Alert::warning(_("Export Warning!"),
369 _("There are spaces in the path to your BibTeX style file.\n"
370 "BibTeX will be unable to find it."));
373 if (!db_out.empty() && buffer().params().use_bibtopic) {
374 os << "\\begin{btSect}{" << db_out << "}\n";
375 docstring btprint = getParam("btprint");
378 btprint = from_ascii("btPrintCited");
379 os << "\\" << btprint << "\n"
380 << "\\end{btSect}\n";
385 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
386 // set label for hyperref, see http://www.lyx.org/trac/ticket/6470
387 if (buffer().params().pdfoptions().use_hyperref)
388 os << "\\phantomsection";
389 if (buffer().params().documentClass().hasLaTeXLayout("chapter"))
390 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
391 else if (buffer().params().documentClass().hasLaTeXLayout("section"))
392 os << "\\addcontentsline{toc}{section}{\\refname}";
395 if (!db_out.empty() && !buffer().params().use_bibtopic) {
396 docstring btprint = getParam("btprint");
397 if (btprint == "btPrintAll") {
398 os << "\\nocite{*}\n";
401 os << "\\bibliography{" << db_out << "}\n";
409 support::FileNameList InsetBibtex::getBibFiles() const
411 FileName path(buffer().filePath());
412 support::PathChanger p(path);
414 support::FileNameList vec;
416 vector<docstring> bibfilelist = getVectorFromString(getParam("bibfiles"));
417 vector<docstring>::const_iterator it = bibfilelist.begin();
418 vector<docstring>::const_iterator en = bibfilelist.end();
419 for (; it != en; ++it) {
420 FileName const file = getBibTeXPath(*it, buffer());
425 LYXERR0("Couldn't find " + to_utf8(*it) + " in InsetBibtex::getBibFiles()!");
434 // methods for parsing bibtex files
436 typedef map<docstring, docstring> VarMap;
438 /// remove whitespace characters, optionally a single comma,
439 /// and further whitespace characters from the stream.
440 /// @return true if a comma was found, false otherwise
442 bool removeWSAndComma(ifdocstream & ifs) {
451 } while (ifs && isSpace(ch));
464 } while (ifs && isSpace(ch));
479 /// remove whitespace characters, read characer sequence
480 /// not containing whitespace characters or characters in
481 /// delimChars, and remove further whitespace characters.
483 /// @return true if a string of length > 0 could be read.
485 bool readTypeOrKey(docstring & val, ifdocstream & ifs,
486 docstring const & delimChars, docstring const & illegalChars,
499 } while (ifs && isSpace(ch));
505 bool legalChar = true;
506 while (ifs && !isSpace(ch) &&
507 delimChars.find(ch) == docstring::npos &&
508 (legalChar = (illegalChars.find(ch) == docstring::npos))
511 if (chCase == makeLowerCase)
512 val += lowercase(ch);
524 while (ifs && isSpace(ch)) {
532 return val.length() > 0;
535 /// read subsequent bibtex values that are delimited with a #-character.
536 /// Concatenate all parts and replace names with the associated string in
537 /// the variable strings.
538 /// @return true if reading was successfull (all single parts were delimited
540 bool readValue(docstring & val, ifdocstream & ifs, const VarMap & strings) {
553 } while (ifs && isSpace(ch));
558 // check for field type
559 if (isDigitASCII(ch)) {
561 // read integer value
565 } while (ifs && isDigitASCII(ch));
570 } else if (ch == '"' || ch == '{') {
572 char_type delim = ch == '"' ? '"': '}';
577 } while (ifs && isSpace(ch));
582 // We now have the first non-whitespace character
583 // We'll collapse adjacent whitespace.
584 bool lastWasWhiteSpace = false;
586 // inside this delimited text braces must match.
587 // Thus we can have a closing delimiter only
588 // when nestLevel == 0
591 while (ifs && (nestLevel > 0 || ch != delim)) {
593 lastWasWhiteSpace = true;
597 // We output the space only after we stop getting
598 // whitespace so as not to output any whitespace
599 // at the end of the value.
600 if (lastWasWhiteSpace) {
601 lastWasWhiteSpace = false;
607 // update nesting level
626 // FIXME Why is this here?
634 // reading a string name
637 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
638 strName += lowercase(ch);
645 // replace the string with its assigned value or
646 // discard it if it's not assigned
647 if (strName.length()) {
648 VarMap::const_iterator pos = strings.find(strName);
649 if (pos != strings.end()) {
656 while (ifs && isSpace(ch)) {
663 // continue reading next value on concatenate with '#'
673 void InsetBibtex::collectBibKeys(InsetIterator const & /*di*/) const
679 void InsetBibtex::parseBibTeXFiles() const
681 // This bibtex parser is a first step to parse bibtex files
684 // - it reads the whole bibtex entry and does a syntax check
685 // (matching delimiters, missing commas,...
686 // - it recovers from errors starting with the next @-character
687 // - it reads @string definitions and replaces them in the
689 // - it accepts more characters in keys or value names than
692 // Officially bibtex does only support ASCII, but in practice
693 // you can use the encoding of the main document as long as
694 // some elements like keys and names are pure ASCII. Therefore
695 // we convert the file from the buffer encoding.
696 // We don't restrict keys to ASCII in LyX, since our own
697 // InsetBibitem can generate non-ASCII keys, and nonstandard
698 // 8bit clean bibtex forks exist.
702 support::FileNameList const files = getBibFiles();
703 support::FileNameList::const_iterator it = files.begin();
704 support::FileNameList::const_iterator en = files.end();
705 for (; it != en; ++ it) {
706 ifdocstream ifs(it->toFilesystemEncoding().c_str(),
707 ios_base::in, buffer().params().encoding().iconvName());
723 if (!readTypeOrKey(entryType, ifs, from_ascii("{("), docstring(), makeLowerCase)) {
724 lyxerr << "BibTeX Parser: Error reading entry type." << std::endl;
729 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
733 if (entryType == from_ascii("comment")) {
734 ifs.ignore(numeric_limits<int>::max(), '\n');
740 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
744 if ((ch != '(') && (ch != '{')) {
745 lyxerr << "BibTeX Parser: Invalid entry delimiter." << std::endl;
751 if (entryType == from_ascii("string")) {
753 // read string and add it to the strings map
754 // (or replace it's old value)
758 if (!readTypeOrKey(name, ifs, from_ascii("="), from_ascii("#{}(),"), makeLowerCase)) {
759 lyxerr << "BibTeX Parser: Error reading string name." << std::endl;
764 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
768 // next char must be an equal sign
770 if (!ifs || ch != '=') {
771 lyxerr << "BibTeX Parser: No `=' after string name: " <<
772 name << "." << std::endl;
776 if (!readValue(value, ifs, strings)) {
777 lyxerr << "BibTeX Parser: Unable to read value for string: " <<
778 name << "." << std::endl;
782 strings[name] = value;
784 } else if (entryType == from_ascii("preamble")) {
786 // preamble definitions are discarded.
787 // can they be of any use in lyx?
790 if (!readValue(value, ifs, strings)) {
791 lyxerr << "BibTeX Parser: Unable to read preamble value." << std::endl;
797 // Citation entry. Try to read the key.
800 if (!readTypeOrKey(key, ifs, from_ascii(","), from_ascii("}"), keepCase)) {
801 lyxerr << "BibTeX Parser: Unable to read key for entry type:" <<
802 entryType << "." << std::endl;
807 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
811 /////////////////////////////////////////////
812 // now we have a key, so we will add an entry
813 // (even if it's empty, as bibtex does)
815 // we now read the field = value pairs.
816 // all items must be separated by a comma. If
817 // it is missing the scanning of this entry is
818 // stopped and the next is searched.
822 BibTeXInfo keyvalmap(key, entryType);
824 bool readNext = removeWSAndComma(ifs);
826 while (ifs && readNext) {
829 if (!readTypeOrKey(name, ifs, from_ascii("="),
830 from_ascii("{}(),"), makeLowerCase) || !ifs)
833 // next char must be an equal sign
834 // FIXME Whitespace??
837 lyxerr << "BibTeX Parser: Unexpected end of file." << std::endl;
841 lyxerr << "BibTeX Parser: Missing `=' after field name: " <<
842 name << ", for key: " << key << "." << std::endl;
848 if (!readValue(value, ifs, strings)) {
849 lyxerr << "BibTeX Parser: Unable to read value for field: " <<
850 name << ", for key: " << key << "." << std::endl;
854 keyvalmap[name] = value;
855 data += "\n\n" + value;
856 keylist.addFieldName(name);
857 readNext = removeWSAndComma(ifs);
861 keylist.addEntryType(entryType);
862 keyvalmap.setAllData(data);
863 keylist[key] = keyvalmap;
864 } //< else (citation entry)
866 } //< for loop over files
868 buffer().addBiblioInfo(keylist);
872 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
874 string texfile = changeExtension(to_utf8(filename), "bib");
875 // note that, if the filename can be found directly from the path,
876 // findtexfile will just return a FileName object for that path.
877 FileName file(findtexfile(texfile, "bib"));
879 file = FileName(makeAbsPath(texfile, buf.filePath()));
884 bool InsetBibtex::addDatabase(docstring const & db)
886 docstring bibfiles = getParam("bibfiles");
887 if (tokenPos(bibfiles, ',', db) != -1)
889 if (!bibfiles.empty())
891 setParam("bibfiles", bibfiles + db);
896 bool InsetBibtex::delDatabase(docstring const & db)
898 docstring bibfiles = getParam("bibfiles");
899 if (contains(bibfiles, db)) {
900 int const n = tokenPos(bibfiles, ',', db);
903 // this is not the first database
904 docstring tmp = ',' + bd;
905 setParam("bibfiles", subst(bibfiles, tmp, docstring()));
907 // this is the first (or only) database
908 setParam("bibfiles", split(bibfiles, bd, ','));
916 void InsetBibtex::validate(LaTeXFeatures & features) const
918 if (features.bufferParams().use_bibtopic)
919 features.require("bibtopic");
921 // It'd be better to be able to get this from an InsetLayout, but at present
922 // InsetLayouts do not seem really to work for things that aren't InsetTexts.
923 if (features.runparams().flavor == OutputParams::HTML)
924 features.addPreambleSnippet("<style type=\"text/css\">\n"
925 "div.bibtexentry { margin-left: 2em; text-indent: -2em; }\n"
926 "span.bibtexlabel:before{ content: \"[\"; }\n"
927 "span.bibtexlabel:after{ content: \"] \"; }\n"
933 // docstring InsetBibtex::entriesAsXHTML(vector<docstring> const & entries)
934 // And then here just: entriesAsXHTML(buffer().masterBibInfo().citedEntries())
935 docstring InsetBibtex::xhtml(XHTMLStream & xs, OutputParams const &) const
937 BiblioInfo const & bibinfo = buffer().masterBibInfo();
938 vector<docstring> const & cites = bibinfo.citedEntries();
939 CiteEngine const engine = buffer().params().citeEngine();
941 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
943 docstring reflabel = from_ascii("References");
944 Language const * l = buffer().params().language;
946 reflabel = translateIfPossible(reflabel, l->code());
948 xs << html::StartTag("h2", "class='bibtex'")
950 << html::EndTag("h2")
951 << html::StartTag("div", "class='bibtex'");
953 // Now we loop over the entries
954 vector<docstring>::const_iterator vit = cites.begin();
955 vector<docstring>::const_iterator const ven = cites.end();
956 for (; vit != ven; ++vit) {
957 BiblioInfo::const_iterator const biit = bibinfo.find(*vit);
958 if (biit == bibinfo.end())
960 BibTeXInfo const & entry = biit->second;
961 xs << html::StartTag("div", "class='bibtexentry'");
963 // The same name/id problem we have elsewhere.
964 string const attr = "id='" + to_utf8(entry.key()) + "'";
965 xs << html::CompTag("a", attr);
968 citekey = entry.citeNumber();
970 docstring const auth = entry.getAbbreviatedAuthor();
971 // we do it this way so as to access the xref, if necessary
972 // note that this also gives us the modifier
973 docstring const year = bibinfo.getYear(*vit, true);
974 if (!auth.empty() && !year.empty())
975 citekey = auth + ' ' + year;
977 if (citekey.empty()) {
978 citekey = entry.label();
980 citekey = entry.key();
982 xs << html::StartTag("span", "class='bibtexlabel'")
984 << html::EndTag("span");
985 // FIXME Right now, we are calling BibInfo::getInfo on the key,
986 // which will give us all the cross-referenced info. But for every
987 // entry, so there's a lot of repitition. This should be fixed.
988 xs << html::StartTag("span", "class='bibtexinfo'")
989 << XHTMLStream::ESCAPE_AND
990 << bibinfo.getInfo(entry.key(), buffer(), true)
991 << html::EndTag("span")
992 << html::EndTag("div");
995 xs << html::EndTag("div");
1000 docstring InsetBibtex::contextMenuName() const
1002 return from_ascii("context-bibtex");