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"
21 #include "FuncRequest.h"
23 #include "LaTeXFeatures.h"
24 #include "MetricsInfo.h"
25 #include "OutputParams.h"
27 #include "frontends/alert.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxlib.h"
33 #include "support/os.h"
34 #include "support/Path.h"
35 #include "support/textutils.h"
37 #include <boost/tokenizer.hpp>
42 using support::absolutePath;
43 using support::ascii_lowercase;
44 using support::changeExtension;
45 using support::contains;
47 using support::DocFileName;
48 using support::FileName;
49 using support::findtexfile;
50 using support::isValidLaTeXFilename;
51 using support::latex_path;
53 using support::makeAbsPath;
54 using support::makeRelPath;
55 using support::prefixIs;
56 using support::removeExtension;
60 using support::tokenPos;
62 using support::lowercase;
64 namespace Alert = frontend::Alert;
65 namespace os = support::os;
76 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
77 : InsetCommand(p, "bibtex")
81 Inset * InsetBibtex::clone() const
83 return new InsetBibtex(*this);
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 (support::ExceptionMessage const & message) {
100 if (message.type_ == support::WarningException) {
101 Alert::warning(message.title_, message.details_);
108 cur.buffer().updateBibfilesCache();
113 InsetCommand::doDispatch(cur, cmd);
119 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
121 return _("BibTeX Generated Bibliography");
127 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
128 string const & name, string const & ext)
130 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
131 if (absolutePath(name) || !FileName(fname + ext).isFileReadable())
137 return to_utf8(makeRelPath(from_utf8(fname),
138 from_utf8(buffer.masterBuffer()->filePath())));
144 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
145 OutputParams const & runparams) const
147 // the sequence of the commands:
148 // 1. \bibliographystyle{style}
149 // 2. \addcontentsline{...} - if option bibtotoc set
150 // 3. \bibliography{database}
151 // and with bibtopic:
152 // 1. \bibliographystyle{style}
153 // 2. \begin{btSect}{database}
154 // 3. \btPrint{Cited|NotCited|All}
158 // If we are processing the LaTeX file in a temp directory then
159 // copy the .bib databases to this temp directory, mangling their
160 // names in the process. Store this mangled name in the list of
162 // (We need to do all this because BibTeX *really*, *really*
163 // can't handle "files with spaces" and Windows users tend to
164 // use such filenames.)
165 // Otherwise, store the (maybe absolute) path to the original,
166 // unmangled database name.
167 typedef boost::char_separator<char_type> Separator;
168 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
170 Separator const separator(from_ascii(",").c_str());
171 // The tokenizer must not be called with temporary strings, since
172 // it does not make a copy and uses iterators of the string further
173 // down. getParam returns a reference, so this is OK.
174 Tokenizer const tokens(getParam("bibfiles"), separator);
175 Tokenizer::const_iterator const begin = tokens.begin();
176 Tokenizer::const_iterator const end = tokens.end();
178 odocstringstream dbs;
179 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
180 docstring const input = trim(*it);
182 string utf8input = to_utf8(input);
184 normalizeName(buffer, runparams, utf8input, ".bib");
185 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
186 bool const not_from_texmf = try_in_file.isFileReadable();
188 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
191 // mangledFilename() needs the extension
192 DocFileName const in_file = DocFileName(try_in_file);
193 database = removeExtension(in_file.mangledFilename());
194 FileName const out_file = makeAbsPath(database + ".bib",
195 buffer.masterBuffer()->temppath());
197 bool const success = copy(in_file, out_file);
199 lyxerr << "Failed to copy '" << in_file
200 << "' to '" << out_file << "'"
203 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
204 !isValidLaTeXFilename(database)) {
205 frontend::Alert::warning(_("Invalid filename"),
206 _("The following filename is likely to cause trouble "
207 "when running the exported file through LaTeX: ") +
208 from_utf8(database));
214 dbs << from_utf8(latex_path(database));
216 docstring const db_out = dbs.str();
218 // Post this warning only once.
219 static bool warned_about_spaces = false;
220 if (!warned_about_spaces &&
221 runparams.nice && db_out.find(' ') != docstring::npos) {
222 warned_about_spaces = true;
224 Alert::warning(_("Export Warning!"),
225 _("There are spaces in the paths to your BibTeX databases.\n"
226 "BibTeX will be unable to find them."));
230 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
232 if (prefixIs(style, "bibtotoc")) {
233 bibtotoc = "bibtotoc";
234 if (contains(style, ','))
235 style = split(style, bibtotoc, ',');
241 if (!style.empty()) {
242 string base = normalizeName(buffer, runparams, style, ".bst");
243 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
244 bool const not_from_texmf = try_in_file.isFileReadable();
245 // If this style does not come from texmf and we are not
246 // exporting to .tex copy it to the tmp directory.
247 // This prevents problems with spaces and 8bit charcaters
249 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
251 // use new style name
252 DocFileName const in_file = DocFileName(try_in_file);
253 base = removeExtension(in_file.mangledFilename());
254 FileName const out_file(makeAbsPath(base + ".bst",
255 buffer.masterBuffer()->temppath()));
256 bool const success = copy(in_file, out_file);
258 lyxerr << "Failed to copy '" << in_file
259 << "' to '" << out_file << "'"
264 os << "\\bibliographystyle{"
265 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
270 // Post this warning only once.
271 static bool warned_about_bst_spaces = false;
272 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
273 warned_about_bst_spaces = true;
274 Alert::warning(_("Export Warning!"),
275 _("There are spaces in the path to your BibTeX style file.\n"
276 "BibTeX will be unable to find it."));
279 if (!db_out.empty() && buffer.params().use_bibtopic){
280 os << "\\begin{btSect}{" << db_out << "}\n";
281 docstring btprint = getParam("btprint");
284 btprint = from_ascii("btPrintCited");
285 os << "\\" << btprint << "\n"
286 << "\\end{btSect}\n";
291 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
292 // maybe a problem when a textclass has no "art" as
293 // part of its name, because it's than book.
294 // For the "official" lyx-layouts it's no problem to support
296 if (!contains(buffer.params().getTextClass().name(),
298 if (buffer.params().sides == TextClass::OneSide) {
303 os << "\\cleardoublepage";
307 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
311 os << "\\addcontentsline{toc}{section}{\\refname}";
315 if (!db_out.empty() && !buffer.params().use_bibtopic){
316 os << "\\bibliography{" << db_out << "}\n";
324 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
326 FileName path(buffer.filePath());
327 support::Path p(path);
329 vector<FileName> vec;
333 string bibfiles = to_utf8(getParam("bibfiles"));
334 bibfiles = split(bibfiles, tmp, ',');
335 while (!tmp.empty()) {
336 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
337 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
339 // If we didn't find a matching file name just fail silently
343 // Get next file name
344 bibfiles = split(bibfiles, tmp, ',');
352 // methods for parsing bibtex files
354 typedef map<docstring, docstring> VarMap;
356 /// remove whitespace characters, optionally a single comma,
357 /// and further whitespace characters from the stream.
358 /// @return true if a comma was found, false otherwise
360 bool removeWSAndComma(idocfstream & ifs) {
369 } while (ifs && isSpace(ch));
382 } while (ifs && isSpace(ch));
397 /// remove whitespace characters, read characer sequence
398 /// not containing whitespace characters or characters in
399 /// delimChars, and remove further whitespace characters.
401 /// @return true if a string of length > 0 could be read.
403 bool readTypeOrKey(docstring & val, idocfstream & ifs,
404 docstring const & delimChars, docstring const &illegalChars,
417 } while (ifs && isSpace(ch));
423 bool legalChar = true;
424 while (ifs && !isSpace(ch) &&
425 delimChars.find(ch) == docstring::npos &&
426 (legalChar = (illegalChars.find(ch) == docstring::npos))
429 if (chCase == makeLowerCase)
430 val += lowercase(ch);
442 while (ifs && isSpace(ch)) {
450 return val.length() > 0;
453 /// read subsequent bibtex values that are delimited with a #-character.
454 /// Concatenate all parts and replace names with the associated string in
455 /// the variable strings.
456 /// @return true if reading was successfull (all single parts were delimited
458 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
471 } while (ifs && isSpace(ch));
476 // check for field type
479 // read integer value
483 } while (ifs && isDigit(ch));
488 } else if (ch == '"' || ch == '{') {
490 char_type delim = ch == '"' ? '"': '}';
495 } while (ifs && isSpace(ch));
500 //We now have the first non-whitespace character
501 //We'll collapse adjacent whitespace.
502 bool lastWasWhiteSpace = false;
504 // inside this delimited text braces must match.
505 // Thus we can have a closing delimiter only
506 // when nestLevel == 0
509 while (ifs && (nestLevel > 0 || ch != delim)) {
511 lastWasWhiteSpace = true;
515 //We output the space only after we stop getting
516 //whitespace so as not to output any whitespace
517 //at the end of the value.
518 if (lastWasWhiteSpace) {
519 lastWasWhiteSpace = false;
525 // update nesting level
532 if (nestLevel < 0) return false;
549 // reading a string name
552 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
553 strName += lowercase(ch);
560 // replace the string with its assigned value or
561 // discard it if it's not assigned
562 if (strName.length()) {
563 VarMap::const_iterator pos = strings.find(strName);
564 if (pos != strings.end()) {
571 while (ifs && isSpace(ch)) {
578 // continue reading next value on concatenate with '#'
588 // This method returns a comma separated list of Bibtex entries
589 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
590 BiblioInfo & keylist, InsetIterator const & /*di*/) const
592 vector<FileName> const files = getFiles(buffer);
593 for (vector<FileName>::const_iterator it = files.begin();
594 it != files.end(); ++ it) {
595 // This bibtex parser is a first step to parse bibtex files
598 // - it reads the whole bibtex entry and does a syntax check
599 // (matching delimiters, missing commas,...
600 // - it recovers from errors starting with the next @-character
601 // - it reads @string definitions and replaces them in the
603 // - it accepts more characters in keys or value names than
606 // Officially bibtex does only support ASCII, but in practice
607 // you can use the encoding of the main document as long as
608 // some elements like keys and names are pure ASCII. Therefore
609 // we convert the file from the buffer encoding.
610 // We don't restrict keys to ASCII in LyX, since our own
611 // InsetBibitem can generate non-ASCII keys, and nonstandard
612 // 8bit clean bibtex forks exist.
614 idocfstream ifs(it->toFilesystemEncoding().c_str(),
616 buffer.params().encoding().iconvName());
632 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
633 docstring(), makeLowerCase) || !ifs)
636 if (entryType == from_ascii("comment")) {
638 ifs.ignore(std::numeric_limits<int>::max(), '\n');
646 if ((ch != '(') && (ch != '{')) {
647 // invalid entry delimiter
653 if (entryType == from_ascii("string")) {
655 // read string and add it to the strings map
656 // (or replace it's old value)
660 if (!readTypeOrKey(name, ifs, from_ascii("="),
661 from_ascii("#{}(),"), makeLowerCase) || !ifs)
664 // next char must be an equal sign
666 if (!ifs || ch != '=')
669 if (!readValue(value, ifs, strings))
672 strings[name] = value;
674 } else if (entryType == from_ascii("preamble")) {
676 // preamble definitions are discarded.
677 // can they be of any use in lyx?
680 if (!readValue(value, ifs, strings))
685 // Citation entry. Try to read the key.
688 if (!readTypeOrKey(key, ifs, from_ascii(","),
689 from_ascii("}"), keepCase) || !ifs)
692 /////////////////////////////////////////////
693 // now we have a key, so we will add an entry
694 // (even if it's empty, as bibtex does)
696 // we now read the field = value pairs.
697 // all items must be separated by a comma. If
698 // it is missing the scanning of this entry is
699 // stopped and the next is searched.
703 docstring commaNewline;
705 BibTeXInfo keyvalmap;
706 keyvalmap.entryType = entryType;
708 bool readNext = removeWSAndComma(ifs);
710 while (ifs && readNext) {
713 if (!readTypeOrKey(name, ifs, from_ascii("="),
714 from_ascii("{}(),"), makeLowerCase) || !ifs)
717 // next char must be an equal sign
727 if (!readValue(value, ifs, strings))
730 keyvalmap[name] = value;
731 data += "\n\n" + value;
732 keylist.fieldNames.insert(name);
733 readNext = removeWSAndComma(ifs);
737 keylist.entryTypes.insert(entryType);
738 keyvalmap.allData = data;
739 keyvalmap.isBibTeX = true;
740 keyvalmap.bibKey = key;
741 keylist[key] = keyvalmap;
744 } //< for loop over files
749 bool InsetBibtex::addDatabase(string const & db)
752 string bibfiles(to_utf8(getParam("bibfiles")));
753 if (tokenPos(bibfiles, ',', db) == -1) {
754 if (!bibfiles.empty())
756 setParam("bibfiles", from_utf8(bibfiles + db));
763 bool InsetBibtex::delDatabase(string const & db)
766 string bibfiles(to_utf8(getParam("bibfiles")));
767 if (contains(bibfiles, db)) {
768 int const n = tokenPos(bibfiles, ',', db);
771 // this is not the first database
772 string tmp = ',' + bd;
773 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
775 // this is the first (or only) database
776 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
784 void InsetBibtex::validate(LaTeXFeatures & features) const
786 if (features.bufferParams().use_bibtopic)
787 features.require("bibtopic");