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 buffer().updateBibfilesCache();
115 InsetCommand::doDispatch(cur, cmd);
121 docstring InsetBibtex::screenLabel() const
123 return _("BibTeX Generated Bibliography");
127 static string normalizeName(Buffer const & buffer,
128 OutputParams const & runparams, string const & name, string const & ext)
130 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
131 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
137 return to_utf8(makeRelPath(from_utf8(fname),
138 from_utf8(buffer.masterBuffer()->filePath())));
142 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
144 // the sequence of the commands:
145 // 1. \bibliographystyle{style}
146 // 2. \addcontentsline{...} - if option bibtotoc set
147 // 3. \bibliography{database}
148 // and with bibtopic:
149 // 1. \bibliographystyle{style}
150 // 2. \begin{btSect}{database}
151 // 3. \btPrint{Cited|NotCited|All}
155 // If we are processing the LaTeX file in a temp directory then
156 // copy the .bib databases to this temp directory, mangling their
157 // names in the process. Store this mangled name in the list of
159 // (We need to do all this because BibTeX *really*, *really*
160 // can't handle "files with spaces" and Windows users tend to
161 // use such filenames.)
162 // Otherwise, store the (maybe absolute) path to the original,
163 // unmangled database name.
164 EmbeddedFileList::const_iterator it = bibfiles_.begin();
165 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
166 odocstringstream dbs;
167 for (; it != it_end; ++it) {
168 string utf8input = removeExtension(it->availableFile().absFilename());
170 normalizeName(buffer(), runparams, utf8input, ".bib");
171 FileName const try_in_file =
172 makeAbsPath(database + ".bib", buffer().filePath());
173 bool const not_from_texmf = try_in_file.isReadableFile();
175 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
178 // mangledFilename() needs the extension
179 DocFileName const in_file = DocFileName(try_in_file);
180 database = removeExtension(in_file.mangledFilename());
181 FileName const out_file = makeAbsPath(database + ".bib",
182 buffer().masterBuffer()->temppath());
184 bool const success = in_file.copyTo(out_file);
186 lyxerr << "Failed to copy '" << in_file
187 << "' to '" << out_file << "'"
190 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
191 !isValidLaTeXFilename(database)) {
192 frontend::Alert::warning(_("Invalid filename"),
193 _("The following filename is likely to cause trouble "
194 "when running the exported file through LaTeX: ") +
195 from_utf8(database));
198 if (it != bibfiles_.begin())
201 dbs << from_utf8(latex_path(database));
203 docstring const db_out = dbs.str();
205 // Post this warning only once.
206 static bool warned_about_spaces = false;
207 if (!warned_about_spaces &&
208 runparams.nice && db_out.find(' ') != docstring::npos) {
209 warned_about_spaces = true;
211 Alert::warning(_("Export Warning!"),
212 _("There are spaces in the paths to your BibTeX databases.\n"
213 "BibTeX will be unable to find them."));
217 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
219 if (prefixIs(style, "bibtotoc")) {
220 bibtotoc = "bibtotoc";
221 if (contains(style, ','))
222 style = split(style, bibtotoc, ',');
228 if (!style.empty()) {
229 string base = normalizeName(buffer(), runparams, style, ".bst");
230 FileName const try_in_file =
231 makeAbsPath(base + ".bst", buffer().filePath());
232 bool const not_from_texmf = try_in_file.isReadableFile();
233 // If this style does not come from texmf and we are not
234 // exporting to .tex copy it to the tmp directory.
235 // This prevents problems with spaces and 8bit charcaters
237 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
239 // use new style name
240 DocFileName const in_file = DocFileName(try_in_file);
241 base = removeExtension(in_file.mangledFilename());
242 FileName const out_file = makeAbsPath(base + ".bst",
243 buffer().masterBuffer()->temppath());
244 bool const success = in_file.copyTo(out_file);
246 lyxerr << "Failed to copy '" << in_file
247 << "' to '" << out_file << "'"
252 os << "\\bibliographystyle{"
253 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
258 // Post this warning only once.
259 static bool warned_about_bst_spaces = false;
260 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
261 warned_about_bst_spaces = true;
262 Alert::warning(_("Export Warning!"),
263 _("There are spaces in the path to your BibTeX style file.\n"
264 "BibTeX will be unable to find it."));
267 if (!db_out.empty() && buffer().params().use_bibtopic) {
268 os << "\\begin{btSect}{" << db_out << "}\n";
269 docstring btprint = getParam("btprint");
272 btprint = from_ascii("btPrintCited");
273 os << "\\" << btprint << "\n"
274 << "\\end{btSect}\n";
279 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
280 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
281 if (buffer().params().sides == OneSide) {
286 os << "\\cleardoublepage";
288 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
289 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
290 os << "\\addcontentsline{toc}{section}{\\refname}";
293 if (!db_out.empty() && !buffer().params().use_bibtopic) {
294 docstring btprint = getParam("btprint");
295 if (btprint == "btPrintAll") {
296 os << "\\nocite{*}\n";
299 os << "\\bibliography{" << db_out << "}\n";
307 EmbeddedFileList InsetBibtex::embeddedFiles() const
314 // methods for parsing bibtex files
316 typedef map<docstring, docstring> VarMap;
318 /// remove whitespace characters, optionally a single comma,
319 /// and further whitespace characters from the stream.
320 /// @return true if a comma was found, false otherwise
322 bool removeWSAndComma(idocfstream & ifs) {
331 } while (ifs && isSpace(ch));
344 } while (ifs && isSpace(ch));
359 /// remove whitespace characters, read characer sequence
360 /// not containing whitespace characters or characters in
361 /// delimChars, and remove further whitespace characters.
363 /// @return true if a string of length > 0 could be read.
365 bool readTypeOrKey(docstring & val, idocfstream & ifs,
366 docstring const & delimChars, docstring const &illegalChars,
379 } while (ifs && isSpace(ch));
385 bool legalChar = true;
386 while (ifs && !isSpace(ch) &&
387 delimChars.find(ch) == docstring::npos &&
388 (legalChar = (illegalChars.find(ch) == docstring::npos))
391 if (chCase == makeLowerCase)
392 val += lowercase(ch);
404 while (ifs && isSpace(ch)) {
412 return val.length() > 0;
415 /// read subsequent bibtex values that are delimited with a #-character.
416 /// Concatenate all parts and replace names with the associated string in
417 /// the variable strings.
418 /// @return true if reading was successfull (all single parts were delimited
420 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
433 } while (ifs && isSpace(ch));
438 // check for field type
441 // read integer value
445 } while (ifs && isDigit(ch));
450 } else if (ch == '"' || ch == '{') {
452 char_type delim = ch == '"' ? '"': '}';
457 } while (ifs && isSpace(ch));
462 //We now have the first non-whitespace character
463 //We'll collapse adjacent whitespace.
464 bool lastWasWhiteSpace = false;
466 // inside this delimited text braces must match.
467 // Thus we can have a closing delimiter only
468 // when nestLevel == 0
471 while (ifs && (nestLevel > 0 || ch != delim)) {
473 lastWasWhiteSpace = true;
477 //We output the space only after we stop getting
478 //whitespace so as not to output any whitespace
479 //at the end of the value.
480 if (lastWasWhiteSpace) {
481 lastWasWhiteSpace = false;
487 // update nesting level
494 if (nestLevel < 0) return false;
511 // reading a string name
514 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
515 strName += lowercase(ch);
522 // replace the string with its assigned value or
523 // discard it if it's not assigned
524 if (strName.length()) {
525 VarMap::const_iterator pos = strings.find(strName);
526 if (pos != strings.end()) {
533 while (ifs && isSpace(ch)) {
540 // continue reading next value on concatenate with '#'
550 // This method returns a comma separated list of Bibtex entries
551 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
552 InsetIterator const & /*di*/) const
554 EmbeddedFileList const files = embeddedFiles();
555 for (vector<EmbeddedFile>::const_iterator it = files.begin();
556 it != files.end(); ++ it) {
557 // This bibtex parser is a first step to parse bibtex files
560 // - it reads the whole bibtex entry and does a syntax check
561 // (matching delimiters, missing commas,...
562 // - it recovers from errors starting with the next @-character
563 // - it reads @string definitions and replaces them in the
565 // - it accepts more characters in keys or value names than
568 // Officially bibtex does only support ASCII, but in practice
569 // you can use the encoding of the main document as long as
570 // some elements like keys and names are pure ASCII. Therefore
571 // we convert the file from the buffer encoding.
572 // We don't restrict keys to ASCII in LyX, since our own
573 // InsetBibitem can generate non-ASCII keys, and nonstandard
574 // 8bit clean bibtex forks exist.
576 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
577 ios_base::in, buffer().params().encoding().iconvName());
593 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
594 docstring(), makeLowerCase) || !ifs)
597 if (entryType == from_ascii("comment")) {
599 ifs.ignore(numeric_limits<int>::max(), '\n');
607 if ((ch != '(') && (ch != '{')) {
608 // invalid entry delimiter
614 if (entryType == from_ascii("string")) {
616 // read string and add it to the strings map
617 // (or replace it's old value)
621 if (!readTypeOrKey(name, ifs, from_ascii("="),
622 from_ascii("#{}(),"), makeLowerCase) || !ifs)
625 // next char must be an equal sign
627 if (!ifs || ch != '=')
630 if (!readValue(value, ifs, strings))
633 strings[name] = value;
635 } else if (entryType == from_ascii("preamble")) {
637 // preamble definitions are discarded.
638 // can they be of any use in lyx?
641 if (!readValue(value, ifs, strings))
646 // Citation entry. Try to read the key.
649 if (!readTypeOrKey(key, ifs, from_ascii(","),
650 from_ascii("}"), keepCase) || !ifs)
653 /////////////////////////////////////////////
654 // now we have a key, so we will add an entry
655 // (even if it's empty, as bibtex does)
657 // we now read the field = value pairs.
658 // all items must be separated by a comma. If
659 // it is missing the scanning of this entry is
660 // stopped and the next is searched.
664 docstring commaNewline;
666 BibTeXInfo keyvalmap(key, entryType);
668 bool readNext = removeWSAndComma(ifs);
670 while (ifs && readNext) {
673 if (!readTypeOrKey(name, ifs, from_ascii("="),
674 from_ascii("{}(),"), makeLowerCase) || !ifs)
677 // next char must be an equal sign
687 if (!readValue(value, ifs, strings))
690 keyvalmap[name] = value;
691 data += "\n\n" + value;
692 keylist.addFieldName(name);
693 readNext = removeWSAndComma(ifs);
697 keylist.addEntryType(entryType);
698 keyvalmap.setAllData(data);
699 keylist[key] = keyvalmap;
702 } //< for loop over files
707 bool InsetBibtex::addDatabase(string const & db)
709 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
711 // only compare filename
712 EmbeddedFileList::iterator it = bibfiles_.begin();
713 EmbeddedFileList::iterator it_end = bibfiles_.end();
714 for (; it != it_end; ++it)
715 if (it->absFilename() == file.absFilename())
718 bibfiles_.push_back(file);
724 bool InsetBibtex::delDatabase(string const & db)
726 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
728 // only compare filename
729 EmbeddedFileList::iterator it = bibfiles_.begin();
730 EmbeddedFileList::iterator it_end = bibfiles_.end();
731 for (; it != it_end; ++it)
732 if (it->absFilename() == file.absFilename()) {
741 void InsetBibtex::validate(LaTeXFeatures & features) const
743 if (features.bufferParams().use_bibtopic)
744 features.require("bibtopic");
748 void InsetBibtex::createBibFiles(docstring const & bibParam,
749 docstring const & embedParam) const
756 string bibfiles = to_utf8(bibParam);
757 string embedStatus = to_utf8(embedParam);
759 LYXERR(Debug::FILES, "Create bib files from parameters "
760 << bibfiles << " and " << embedStatus);
762 bibfiles = split(bibfiles, tmp, ',');
763 embedStatus = split(embedStatus, emb, ',');
765 while (!tmp.empty()) {
766 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
768 file.setInzipName(emb);
769 file.setEmbed(!emb.empty());
770 file.enable(buffer().embedded(), &buffer(), false);
771 bibfiles_.push_back(file);
772 // Get next file name
773 bibfiles = split(bibfiles, tmp, ',');
774 embedStatus = split(embedStatus, emb, ',');
779 void InsetBibtex::updateParam()
785 for (EmbeddedFileList::iterator it = bibfiles_.begin();
786 it != bibfiles_.end(); ++it) {
792 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
794 embed += from_utf8(it->inzipName());
796 setParam("bibfiles", bibfiles);
797 setParam("embed", embed);
801 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
803 if (bibfiles_.empty())
804 createBibFiles(params()["bibfiles"], params()["embed"]);
806 EmbeddedFileList::const_iterator it = bibfiles_.begin();
807 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
808 for (; it != it_end; ++it)
809 files.registerFile(*it, this, buffer());
813 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
815 // look for the item and update status
816 for (EmbeddedFileList::iterator it = bibfiles_.begin();
817 it != bibfiles_.end(); ++it)
818 if (it->absFilename() == file.absFilename())