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")
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();
90 // returned "embed" is composed of "true" or "false", which needs to be adjusted
95 string newEmbedStatus;
97 string bibfiles = to_utf8(p["bibfiles"]);
98 string embedStatus = to_utf8(p["embed"]);
100 bibfiles = split(bibfiles, tmp, ',');
101 embedStatus = split(embedStatus, emb, ',');
102 while (!tmp.empty()) {
103 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
104 if (!newBibfiles.empty())
107 if (!newEmbedStatus.empty())
108 newEmbedStatus += ",";
110 newEmbedStatus += file.inzipName();
111 // Get next file name
112 bibfiles = split(bibfiles, tmp, ',');
113 embedStatus = split(embedStatus, emb, ',');
115 LYXERR(Debug::FILES, "Update parameters from " << p["bibfiles"]
116 << " " << p["embed"] << " to " << newBibfiles << " "
118 p["bibfiles"] = from_utf8(newBibfiles);
119 p["embed"] = from_utf8(newEmbedStatus);
123 // test parameter and copy files
125 } catch (ExceptionMessage const & message) {
126 Alert::error(message.title_, message.details_);
127 // do not set parameter if an error happens
131 buffer().updateBibfilesCache();
136 InsetCommand::doDispatch(cur, cmd);
142 docstring InsetBibtex::screenLabel() const
144 return _("BibTeX Generated Bibliography");
148 static string normalizeName(Buffer const & buffer,
149 OutputParams const & runparams, string const & name, string const & ext)
151 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
152 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
158 return to_utf8(makeRelPath(from_utf8(fname),
159 from_utf8(buffer.masterBuffer()->filePath())));
163 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
165 // the sequence of the commands:
166 // 1. \bibliographystyle{style}
167 // 2. \addcontentsline{...} - if option bibtotoc set
168 // 3. \bibliography{database}
169 // and with bibtopic:
170 // 1. \bibliographystyle{style}
171 // 2. \begin{btSect}{database}
172 // 3. \btPrint{Cited|NotCited|All}
176 // If we are processing the LaTeX file in a temp directory then
177 // copy the .bib databases to this temp directory, mangling their
178 // names in the process. Store this mangled name in the list of
180 // (We need to do all this because BibTeX *really*, *really*
181 // can't handle "files with spaces" and Windows users tend to
182 // use such filenames.)
183 // Otherwise, store the (maybe absolute) path to the original,
184 // unmangled database name.
185 EmbeddedFileList const bibs = embeddedFiles();
186 EmbeddedFileList::const_iterator it = bibs.begin();
187 EmbeddedFileList::const_iterator it_end = bibs.end();
188 odocstringstream dbs;
189 for (; it != it_end; ++it) {
190 string utf8input = removeExtension(it->availableFile().absFilename());
192 normalizeName(buffer(), runparams, utf8input, ".bib");
193 FileName const try_in_file =
194 makeAbsPath(database + ".bib", buffer().filePath());
195 bool const not_from_texmf = try_in_file.isReadableFile();
197 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
200 // mangledFilename() needs the extension
201 DocFileName const in_file = DocFileName(try_in_file);
202 database = removeExtension(in_file.mangledFilename());
203 FileName const out_file = makeAbsPath(database + ".bib",
204 buffer().masterBuffer()->temppath());
206 bool const success = in_file.copyTo(out_file);
208 lyxerr << "Failed to copy '" << in_file
209 << "' to '" << out_file << "'"
212 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
213 !isValidLaTeXFilename(database)) {
214 frontend::Alert::warning(_("Invalid filename"),
215 _("The following filename is likely to cause trouble "
216 "when running the exported file through LaTeX: ") +
217 from_utf8(database));
220 if (it != bibs.begin())
223 dbs << from_utf8(latex_path(database));
225 docstring const db_out = dbs.str();
227 // Post this warning only once.
228 static bool warned_about_spaces = false;
229 if (!warned_about_spaces &&
230 runparams.nice && db_out.find(' ') != docstring::npos) {
231 warned_about_spaces = true;
233 Alert::warning(_("Export Warning!"),
234 _("There are spaces in the paths to your BibTeX databases.\n"
235 "BibTeX will be unable to find them."));
239 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
241 if (prefixIs(style, "bibtotoc")) {
242 bibtotoc = "bibtotoc";
243 if (contains(style, ','))
244 style = split(style, bibtotoc, ',');
250 if (!style.empty()) {
251 string base = normalizeName(buffer(), runparams, style, ".bst");
252 FileName const try_in_file =
253 makeAbsPath(base + ".bst", buffer().filePath());
254 bool const not_from_texmf = try_in_file.isReadableFile();
255 // If this style does not come from texmf and we are not
256 // exporting to .tex copy it to the tmp directory.
257 // This prevents problems with spaces and 8bit charcaters
259 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
261 // use new style name
262 DocFileName const in_file = DocFileName(try_in_file);
263 base = removeExtension(in_file.mangledFilename());
264 FileName const out_file = makeAbsPath(base + ".bst",
265 buffer().masterBuffer()->temppath());
266 bool const success = in_file.copyTo(out_file);
268 lyxerr << "Failed to copy '" << in_file
269 << "' to '" << out_file << "'"
274 os << "\\bibliographystyle{"
275 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
280 // Post this warning only once.
281 static bool warned_about_bst_spaces = false;
282 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
283 warned_about_bst_spaces = true;
284 Alert::warning(_("Export Warning!"),
285 _("There are spaces in the path to your BibTeX style file.\n"
286 "BibTeX will be unable to find it."));
289 if (!db_out.empty() && buffer().params().use_bibtopic) {
290 os << "\\begin{btSect}{" << db_out << "}\n";
291 docstring btprint = getParam("btprint");
294 btprint = from_ascii("btPrintCited");
295 os << "\\" << btprint << "\n"
296 << "\\end{btSect}\n";
301 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
302 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
303 if (buffer().params().sides == OneSide) {
308 os << "\\cleardoublepage";
310 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
311 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
312 os << "\\addcontentsline{toc}{section}{\\refname}";
315 if (!db_out.empty() && !buffer().params().use_bibtopic) {
316 docstring btprint = getParam("btprint");
317 if (btprint == "btPrintAll") {
318 os << "\\nocite{*}\n";
321 os << "\\bibliography{" << db_out << "}\n";
329 EmbeddedFileList InsetBibtex::embeddedFiles() const
331 FileName path(buffer().filePath());
334 EmbeddedFileList vec;
339 string bibfiles = to_utf8(getParam("bibfiles"));
340 string embedStatus = to_utf8(getParam("embed"));
341 bibfiles = split(bibfiles, tmp, ',');
342 embedStatus = split(embedStatus, emb, ',');
343 while (!tmp.empty()) {
345 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
346 // If the file structure is correct, this should not fail.
348 file.enable(buffer().embedded(), &buffer());
351 // this includes the cases when the embed parameter is empty
352 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
354 // If we didn't find a matching file name just fail silently
356 EmbeddedFile efile = EmbeddedFile(file.absFilename(), buffer().filePath());
357 efile.setEmbed(false);
358 efile.enable(buffer().embedded(), &buffer());
359 vec.push_back(efile);
363 // Get next file name
364 bibfiles = split(bibfiles, tmp, ',');
365 embedStatus = split(embedStatus, emb, ',');
373 // methods for parsing bibtex files
375 typedef map<docstring, docstring> VarMap;
377 /// remove whitespace characters, optionally a single comma,
378 /// and further whitespace characters from the stream.
379 /// @return true if a comma was found, false otherwise
381 bool removeWSAndComma(idocfstream & ifs) {
390 } while (ifs && isSpace(ch));
403 } while (ifs && isSpace(ch));
418 /// remove whitespace characters, read characer sequence
419 /// not containing whitespace characters or characters in
420 /// delimChars, and remove further whitespace characters.
422 /// @return true if a string of length > 0 could be read.
424 bool readTypeOrKey(docstring & val, idocfstream & ifs,
425 docstring const & delimChars, docstring const &illegalChars,
438 } while (ifs && isSpace(ch));
444 bool legalChar = true;
445 while (ifs && !isSpace(ch) &&
446 delimChars.find(ch) == docstring::npos &&
447 (legalChar = (illegalChars.find(ch) == docstring::npos))
450 if (chCase == makeLowerCase)
451 val += lowercase(ch);
463 while (ifs && isSpace(ch)) {
471 return val.length() > 0;
474 /// read subsequent bibtex values that are delimited with a #-character.
475 /// Concatenate all parts and replace names with the associated string in
476 /// the variable strings.
477 /// @return true if reading was successfull (all single parts were delimited
479 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
492 } while (ifs && isSpace(ch));
497 // check for field type
500 // read integer value
504 } while (ifs && isDigit(ch));
509 } else if (ch == '"' || ch == '{') {
511 char_type delim = ch == '"' ? '"': '}';
516 } while (ifs && isSpace(ch));
521 //We now have the first non-whitespace character
522 //We'll collapse adjacent whitespace.
523 bool lastWasWhiteSpace = false;
525 // inside this delimited text braces must match.
526 // Thus we can have a closing delimiter only
527 // when nestLevel == 0
530 while (ifs && (nestLevel > 0 || ch != delim)) {
532 lastWasWhiteSpace = true;
536 //We output the space only after we stop getting
537 //whitespace so as not to output any whitespace
538 //at the end of the value.
539 if (lastWasWhiteSpace) {
540 lastWasWhiteSpace = false;
546 // update nesting level
553 if (nestLevel < 0) return false;
570 // reading a string name
573 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
574 strName += lowercase(ch);
581 // replace the string with its assigned value or
582 // discard it if it's not assigned
583 if (strName.length()) {
584 VarMap::const_iterator pos = strings.find(strName);
585 if (pos != strings.end()) {
592 while (ifs && isSpace(ch)) {
599 // continue reading next value on concatenate with '#'
609 // This method returns a comma separated list of Bibtex entries
610 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
611 InsetIterator const & /*di*/) const
613 EmbeddedFileList const files = embeddedFiles();
614 for (vector<EmbeddedFile>::const_iterator it = files.begin();
615 it != files.end(); ++ it) {
616 // This bibtex parser is a first step to parse bibtex files
619 // - it reads the whole bibtex entry and does a syntax check
620 // (matching delimiters, missing commas,...
621 // - it recovers from errors starting with the next @-character
622 // - it reads @string definitions and replaces them in the
624 // - it accepts more characters in keys or value names than
627 // Officially bibtex does only support ASCII, but in practice
628 // you can use the encoding of the main document as long as
629 // some elements like keys and names are pure ASCII. Therefore
630 // we convert the file from the buffer encoding.
631 // We don't restrict keys to ASCII in LyX, since our own
632 // InsetBibitem can generate non-ASCII keys, and nonstandard
633 // 8bit clean bibtex forks exist.
635 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
636 ios_base::in, buffer().params().encoding().iconvName());
652 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
653 docstring(), makeLowerCase) || !ifs)
656 if (entryType == from_ascii("comment")) {
658 ifs.ignore(numeric_limits<int>::max(), '\n');
666 if ((ch != '(') && (ch != '{')) {
667 // invalid entry delimiter
673 if (entryType == from_ascii("string")) {
675 // read string and add it to the strings map
676 // (or replace it's old value)
680 if (!readTypeOrKey(name, ifs, from_ascii("="),
681 from_ascii("#{}(),"), makeLowerCase) || !ifs)
684 // next char must be an equal sign
686 if (!ifs || ch != '=')
689 if (!readValue(value, ifs, strings))
692 strings[name] = value;
694 } else if (entryType == from_ascii("preamble")) {
696 // preamble definitions are discarded.
697 // can they be of any use in lyx?
700 if (!readValue(value, ifs, strings))
705 // Citation entry. Try to read the key.
708 if (!readTypeOrKey(key, ifs, from_ascii(","),
709 from_ascii("}"), keepCase) || !ifs)
712 /////////////////////////////////////////////
713 // now we have a key, so we will add an entry
714 // (even if it's empty, as bibtex does)
716 // we now read the field = value pairs.
717 // all items must be separated by a comma. If
718 // it is missing the scanning of this entry is
719 // stopped and the next is searched.
723 docstring commaNewline;
725 BibTeXInfo keyvalmap(key, entryType);
727 bool readNext = removeWSAndComma(ifs);
729 while (ifs && readNext) {
732 if (!readTypeOrKey(name, ifs, from_ascii("="),
733 from_ascii("{}(),"), makeLowerCase) || !ifs)
736 // next char must be an equal sign
746 if (!readValue(value, ifs, strings))
749 keyvalmap[name] = value;
750 data += "\n\n" + value;
751 keylist.addFieldName(name);
752 readNext = removeWSAndComma(ifs);
756 keylist.addEntryType(entryType);
757 keyvalmap.setAllData(data);
758 keylist[key] = keyvalmap;
761 } //< for loop over files
766 bool InsetBibtex::addDatabase(string const & db)
769 string bibfiles(to_utf8(getParam("bibfiles")));
770 if (tokenPos(bibfiles, ',', db) == -1) {
771 if (!bibfiles.empty())
773 setParam("bibfiles", from_utf8(bibfiles + db));
780 bool InsetBibtex::delDatabase(string const & db)
783 string bibfiles(to_utf8(getParam("bibfiles")));
784 if (contains(bibfiles, db)) {
785 int const n = tokenPos(bibfiles, ',', db);
788 // this is not the first database
789 string tmp = ',' + bd;
790 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
792 // this is the first (or only) database
793 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
801 void InsetBibtex::validate(LaTeXFeatures & features) const
803 if (features.bufferParams().use_bibtopic)
804 features.require("bibtopic");
808 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
810 EmbeddedFileList const dbs = embeddedFiles();
811 for (vector<EmbeddedFile>::const_iterator it = dbs.begin();
812 it != dbs.end(); ++it)
813 files.registerFile(*it, this, buffer());
817 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
819 // look for the item and update status
824 EmbeddedFileList dbs = embeddedFiles();
825 for (EmbeddedFileList::iterator it = dbs.begin();
826 it != dbs.end(); ++it) {
828 if (it->absFilename() == file.absFilename())
829 it->setEmbed(file.embedded());
830 // write parameter string
837 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
839 embed += from_utf8(it->inzipName());
841 setParam("bibfiles", bibfiles);
842 setParam("embed", embed);