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)
57 // FIXME We ought to have a buffer.
59 EmbeddedFileList::iterator it = bibfiles_.begin();
60 EmbeddedFileList::iterator it_end = bibfiles_.end();
61 for (; it != it_end; ++it) {
63 *it = it->copyTo(&buffer);
64 } catch (ExceptionMessage const & message) {
65 Alert::error(message.title_, message.details_);
71 InsetCommand::setBuffer(buffer);
75 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
77 static ParamInfo param_info_;
78 if (param_info_.empty()) {
79 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
80 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
81 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
82 param_info_.add("options", ParamInfo::LYX_INTERNAL);
88 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
92 case LFUN_INSET_MODIFY: {
93 InsetCommandParams p(BIBTEX_CODE);
95 if (!InsetCommand::string2params("bibtex",
96 to_utf8(cmd.argument()), p)) {
100 } catch (ExceptionMessage const & message) {
101 if (message.type_ == WarningException) {
102 Alert::warning(message.title_, message.details_);
111 setParam("options", p["options"]);
112 buffer().updateBibfilesCache();
117 InsetCommand::doDispatch(cur, cmd);
123 docstring InsetBibtex::screenLabel() const
125 return _("BibTeX Generated Bibliography");
129 static string normalizeName(Buffer const & buffer,
130 OutputParams const & runparams, string const & name, string const & ext)
132 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
133 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
139 return to_utf8(makeRelPath(from_utf8(fname),
140 from_utf8(buffer.masterBuffer()->filePath())));
144 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
146 // the sequence of the commands:
147 // 1. \bibliographystyle{style}
148 // 2. \addcontentsline{...} - if option bibtotoc set
149 // 3. \bibliography{database}
150 // and with bibtopic:
151 // 1. \bibliographystyle{style}
152 // 2. \begin{btSect}{database}
153 // 3. \btPrint{Cited|NotCited|All}
157 // If we are processing the LaTeX file in a temp directory then
158 // copy the .bib databases to this temp directory, mangling their
159 // names in the process. Store this mangled name in the list of
161 // (We need to do all this because BibTeX *really*, *really*
162 // can't handle "files with spaces" and Windows users tend to
163 // use such filenames.)
164 // Otherwise, store the (maybe absolute) path to the original,
165 // unmangled database name.
166 EmbeddedFileList::const_iterator it = bibfiles_.begin();
167 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
168 odocstringstream dbs;
169 for (; it != it_end; ++it) {
170 string utf8input = removeExtension(it->availableFile().absFilename());
172 normalizeName(buffer(), runparams, utf8input, ".bib");
173 FileName const try_in_file =
174 makeAbsPath(database + ".bib", buffer().filePath());
175 bool const not_from_texmf = try_in_file.isReadableFile();
177 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
180 // mangledFilename() needs the extension
181 DocFileName const in_file = DocFileName(try_in_file);
182 database = removeExtension(in_file.mangledFilename());
183 FileName const out_file = makeAbsPath(database + ".bib",
184 buffer().masterBuffer()->temppath());
186 bool const success = in_file.copyTo(out_file);
188 lyxerr << "Failed to copy '" << in_file
189 << "' to '" << out_file << "'"
192 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
193 !isValidLaTeXFilename(database)) {
194 frontend::Alert::warning(_("Invalid filename"),
195 _("The following filename is likely to cause trouble "
196 "when running the exported file through LaTeX: ") +
197 from_utf8(database));
200 if (it != bibfiles_.begin())
203 dbs << from_utf8(latex_path(database));
205 docstring const db_out = dbs.str();
207 // Post this warning only once.
208 static bool warned_about_spaces = false;
209 if (!warned_about_spaces &&
210 runparams.nice && db_out.find(' ') != docstring::npos) {
211 warned_about_spaces = true;
213 Alert::warning(_("Export Warning!"),
214 _("There are spaces in the paths to your BibTeX databases.\n"
215 "BibTeX will be unable to find them."));
219 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
221 if (prefixIs(style, "bibtotoc")) {
222 bibtotoc = "bibtotoc";
223 if (contains(style, ','))
224 style = split(style, bibtotoc, ',');
230 if (!style.empty()) {
231 string base = normalizeName(buffer(), runparams, style, ".bst");
232 FileName const try_in_file =
233 makeAbsPath(base + ".bst", buffer().filePath());
234 bool const not_from_texmf = try_in_file.isReadableFile();
235 // If this style does not come from texmf and we are not
236 // exporting to .tex copy it to the tmp directory.
237 // This prevents problems with spaces and 8bit charcaters
239 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
241 // use new style name
242 DocFileName const in_file = DocFileName(try_in_file);
243 base = removeExtension(in_file.mangledFilename());
244 FileName const out_file = makeAbsPath(base + ".bst",
245 buffer().masterBuffer()->temppath());
246 bool const success = in_file.copyTo(out_file);
248 lyxerr << "Failed to copy '" << in_file
249 << "' to '" << out_file << "'"
254 os << "\\bibliographystyle{"
255 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
260 // Post this warning only once.
261 static bool warned_about_bst_spaces = false;
262 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
263 warned_about_bst_spaces = true;
264 Alert::warning(_("Export Warning!"),
265 _("There are spaces in the path to your BibTeX style file.\n"
266 "BibTeX will be unable to find it."));
269 if (!db_out.empty() && buffer().params().use_bibtopic) {
270 os << "\\begin{btSect}{" << db_out << "}\n";
271 docstring btprint = getParam("btprint");
274 btprint = from_ascii("btPrintCited");
275 os << "\\" << btprint << "\n"
276 << "\\end{btSect}\n";
281 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
282 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
283 if (buffer().params().sides == OneSide) {
288 os << "\\cleardoublepage";
290 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
291 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
292 os << "\\addcontentsline{toc}{section}{\\refname}";
295 if (!db_out.empty() && !buffer().params().use_bibtopic) {
296 docstring btprint = getParam("btprint");
297 if (btprint == "btPrintAll") {
298 os << "\\nocite{*}\n";
301 os << "\\bibliography{" << db_out << "}\n";
309 EmbeddedFileList const & InsetBibtex::getBibFiles() const
316 // methods for parsing bibtex files
318 typedef map<docstring, docstring> VarMap;
320 /// remove whitespace characters, optionally a single comma,
321 /// and further whitespace characters from the stream.
322 /// @return true if a comma was found, false otherwise
324 bool removeWSAndComma(idocfstream & ifs) {
333 } while (ifs && isSpace(ch));
346 } while (ifs && isSpace(ch));
361 /// remove whitespace characters, read characer sequence
362 /// not containing whitespace characters or characters in
363 /// delimChars, and remove further whitespace characters.
365 /// @return true if a string of length > 0 could be read.
367 bool readTypeOrKey(docstring & val, idocfstream & ifs,
368 docstring const & delimChars, docstring const &illegalChars,
381 } while (ifs && isSpace(ch));
387 bool legalChar = true;
388 while (ifs && !isSpace(ch) &&
389 delimChars.find(ch) == docstring::npos &&
390 (legalChar = (illegalChars.find(ch) == docstring::npos))
393 if (chCase == makeLowerCase)
394 val += lowercase(ch);
406 while (ifs && isSpace(ch)) {
414 return val.length() > 0;
417 /// read subsequent bibtex values that are delimited with a #-character.
418 /// Concatenate all parts and replace names with the associated string in
419 /// the variable strings.
420 /// @return true if reading was successfull (all single parts were delimited
422 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
435 } while (ifs && isSpace(ch));
440 // check for field type
443 // read integer value
447 } while (ifs && isDigit(ch));
452 } else if (ch == '"' || ch == '{') {
454 char_type delim = ch == '"' ? '"': '}';
459 } while (ifs && isSpace(ch));
464 //We now have the first non-whitespace character
465 //We'll collapse adjacent whitespace.
466 bool lastWasWhiteSpace = false;
468 // inside this delimited text braces must match.
469 // Thus we can have a closing delimiter only
470 // when nestLevel == 0
473 while (ifs && (nestLevel > 0 || ch != delim)) {
475 lastWasWhiteSpace = true;
479 //We output the space only after we stop getting
480 //whitespace so as not to output any whitespace
481 //at the end of the value.
482 if (lastWasWhiteSpace) {
483 lastWasWhiteSpace = false;
489 // update nesting level
496 if (nestLevel < 0) return false;
513 // reading a string name
516 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
517 strName += lowercase(ch);
524 // replace the string with its assigned value or
525 // discard it if it's not assigned
526 if (strName.length()) {
527 VarMap::const_iterator pos = strings.find(strName);
528 if (pos != strings.end()) {
535 while (ifs && isSpace(ch)) {
542 // continue reading next value on concatenate with '#'
552 // This method returns a comma separated list of Bibtex entries
553 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
554 InsetIterator const & /*di*/) const
556 // This bibtex parser is a first step to parse bibtex files
559 // - it reads the whole bibtex entry and does a syntax check
560 // (matching delimiters, missing commas,...
561 // - it recovers from errors starting with the next @-character
562 // - it reads @string definitions and replaces them in the
564 // - it accepts more characters in keys or value names than
567 // Officially bibtex does only support ASCII, but in practice
568 // you can use the encoding of the main document as long as
569 // some elements like keys and names are pure ASCII. Therefore
570 // we convert the file from the buffer encoding.
571 // We don't restrict keys to ASCII in LyX, since our own
572 // InsetBibitem can generate non-ASCII keys, and nonstandard
573 // 8bit clean bibtex forks exist.
574 EmbeddedFileList const & files = getBibFiles();
575 EmbeddedFileList::const_iterator it = files.begin();
576 EmbeddedFileList::const_iterator en = files.end();
577 for (; it != en; ++ it) {
578 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
579 ios_base::in, buffer().params().encoding().iconvName());
595 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
596 docstring(), makeLowerCase) || !ifs)
599 if (entryType == from_ascii("comment")) {
601 ifs.ignore(numeric_limits<int>::max(), '\n');
609 if ((ch != '(') && (ch != '{')) {
610 // invalid entry delimiter
616 if (entryType == from_ascii("string")) {
618 // read string and add it to the strings map
619 // (or replace it's old value)
623 if (!readTypeOrKey(name, ifs, from_ascii("="),
624 from_ascii("#{}(),"), makeLowerCase) || !ifs)
627 // next char must be an equal sign
629 if (!ifs || ch != '=')
632 if (!readValue(value, ifs, strings))
635 strings[name] = value;
637 } else if (entryType == from_ascii("preamble")) {
639 // preamble definitions are discarded.
640 // can they be of any use in lyx?
643 if (!readValue(value, ifs, strings))
648 // Citation entry. Try to read the key.
651 if (!readTypeOrKey(key, ifs, from_ascii(","),
652 from_ascii("}"), keepCase) || !ifs)
655 /////////////////////////////////////////////
656 // now we have a key, so we will add an entry
657 // (even if it's empty, as bibtex does)
659 // we now read the field = value pairs.
660 // all items must be separated by a comma. If
661 // it is missing the scanning of this entry is
662 // stopped and the next is searched.
666 docstring commaNewline;
668 BibTeXInfo keyvalmap(key, entryType);
670 bool readNext = removeWSAndComma(ifs);
672 while (ifs && readNext) {
675 if (!readTypeOrKey(name, ifs, from_ascii("="),
676 from_ascii("{}(),"), makeLowerCase) || !ifs)
679 // next char must be an equal sign
689 if (!readValue(value, ifs, strings))
692 keyvalmap[name] = value;
693 data += "\n\n" + value;
694 keylist.addFieldName(name);
695 readNext = removeWSAndComma(ifs);
699 keylist.addEntryType(entryType);
700 keyvalmap.setAllData(data);
701 keylist[key] = keyvalmap;
704 } //< for loop over files
708 FileName InsetBibtex::getBibTeXPath(docstring const & filename, Buffer const & buf)
710 string texfile = changeExtension(to_utf8(filename), "bib");
711 // note that, if the filename can be found directly from the path,
712 // findtexfile will just return a FileName object for that path.
713 FileName file(findtexfile(texfile, "bib"));
715 file = FileName(makeAbsPath(texfile, buf.filePath()));
720 bool InsetBibtex::addDatabase(docstring const & db)
722 FileName const texPath = getBibTeXPath(db, buffer());
723 EmbeddedFileList::const_iterator efp =
724 bibfiles_.findFile(texPath.absFilename());
725 if (efp != bibfiles_.end())
729 EmbeddedFile file(texPath.absFilename(), buffer().filePath());
730 bibfiles_.push_back(file);
736 bool InsetBibtex::delDatabase(docstring const & db)
738 FileName const texPath = getBibTeXPath(db, buffer());
739 EmbeddedFileList::iterator efp =
740 bibfiles_.findFile(texPath.absFilename());
741 if (efp == bibfiles_.end())
745 bibfiles_.erase(efp);
751 void InsetBibtex::validate(LaTeXFeatures & features) const
753 if (features.bufferParams().use_bibtopic)
754 features.require("bibtopic");
758 void InsetBibtex::createBibFiles() const
760 // need to do this to keep old info while also not
761 // copying over any files that have been deleted.
762 EmbeddedFileList oldlist = bibfiles_;
768 docstring bibfiles = getParam("bibfiles");
769 docstring embfiles = getParam("embed");
771 bibfiles = split(bibfiles, bibfile, ',');
772 embfiles = split(embfiles, embfile, ',');
774 while (!bibfile.empty()) {
775 FileName bib = getBibTeXPath(bibfile, buffer());
776 EmbeddedFileList::iterator efp = oldlist.findFile(bib.absFilename());
777 if (efp != oldlist.end()) {
778 // already have this one
779 efp->setInzipName(to_utf8(embfile));
780 efp->setEmbed(!embfile.empty());
782 efp->enable(buffer().embedded(), &buffer(), false);
783 } catch (ExceptionMessage const & message) {
784 Alert::error(message.title_, message.details_);
786 efp->setEmbed(false);
788 bibfiles_.push_back(*efp);
790 EmbeddedFile file(bib.absFilename(), buffer().filePath());
791 file.setInzipName(to_utf8(embfile));
792 file.setEmbed(!embfile.empty());
794 file.enable(buffer().embedded(), &buffer(), true);
795 } catch (ExceptionMessage const & message) {
796 Alert::error(message.title_, message.details_);
798 file.setEmbed(false);
800 bibfiles_.push_back(file);
802 // Get next file name
803 bibfiles = split(bibfiles, bibfile, ',');
804 embfiles = split(embfiles, embfile, ',');
809 void InsetBibtex::updateParam()
816 EmbeddedFileList::iterator it = bibfiles_.begin();
817 EmbeddedFileList::iterator en = bibfiles_.end();
818 for (; it != en; ++it) {
824 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
826 embed += from_utf8(it->inzipName());
828 setParam("bibfiles", bibfiles);
829 setParam("embed", embed);
833 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
835 if (bibfiles_.empty())
838 EmbeddedFileList::const_iterator it = bibfiles_.begin();
839 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
840 for (; it != it_end; ++it)
841 files.registerFile(*it, this, buffer());
845 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
847 // look for the item and update status
848 for (EmbeddedFileList::iterator it = bibfiles_.begin();
849 it != bibfiles_.end(); ++it)
850 if (it->absFilename() == file.absFilename())