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");
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 normalize_name(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.getMasterBuffer()->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 normalize_name(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.getMasterBuffer()->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."));
231 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
233 if (prefixIs(style, "bibtotoc")) {
234 bibtotoc = "bibtotoc";
235 if (contains(style, ',')) {
236 style = split(style, bibtotoc, ',');
243 if (!style.empty()) {
245 normalize_name(buffer, runparams, style, ".bst");
246 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
247 bool const not_from_texmf = try_in_file.isFileReadable();
248 // If this style does not come from texmf and we are not
249 // exporting to .tex copy it to the tmp directory.
250 // This prevents problems with spaces and 8bit charcaters
252 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
254 // use new style name
255 DocFileName const in_file = DocFileName(try_in_file);
256 base = removeExtension(in_file.mangledFilename());
257 FileName const out_file(makeAbsPath(base + ".bst",
258 buffer.getMasterBuffer()->temppath()));
259 bool const success = copy(in_file, out_file);
261 lyxerr << "Failed to copy '" << in_file
262 << "' to '" << out_file << "'"
267 os << "\\bibliographystyle{"
268 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
273 // Post this warning only once.
274 static bool warned_about_bst_spaces = false;
275 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
276 warned_about_bst_spaces = true;
277 Alert::warning(_("Export Warning!"),
278 _("There are spaces in the path to your BibTeX style file.\n"
279 "BibTeX will be unable to find it."));
282 if (!db_out.empty() && buffer.params().use_bibtopic){
283 os << "\\begin{btSect}{" << db_out << "}\n";
284 docstring btprint = getParam("btprint");
287 btprint = from_ascii("btPrintCited");
288 os << "\\" << btprint << "\n"
289 << "\\end{btSect}\n";
294 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
295 // maybe a problem when a textclass has no "art" as
296 // part of its name, because it's than book.
297 // For the "official" lyx-layouts it's no problem to support
299 if (!contains(buffer.params().getTextClass().name(),
301 if (buffer.params().sides == TextClass::OneSide) {
306 os << "\\cleardoublepage";
310 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
314 os << "\\addcontentsline{toc}{section}{\\refname}";
318 if (!db_out.empty() && !buffer.params().use_bibtopic){
319 os << "\\bibliography{" << db_out << "}\n";
327 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
329 FileName path(buffer.filePath());
330 support::Path p(path);
332 vector<FileName> vec;
336 string bibfiles = to_utf8(getParam("bibfiles"));
337 bibfiles = split(bibfiles, tmp, ',');
338 while (!tmp.empty()) {
339 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
340 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
342 // If we didn't find a matching file name just fail silently
346 // Get next file name
347 bibfiles = split(bibfiles, tmp, ',');
355 // methods for parsing bibtex files
357 typedef map<docstring, docstring> VarMap;
359 /// remove whitespace characters, optionally a single comma,
360 /// and further whitespace characters from the stream.
361 /// @return true if a comma was found, false otherwise
363 bool removeWSAndComma(idocfstream & ifs) {
372 } while (ifs && isSpace(ch));
385 } while (ifs && isSpace(ch));
400 /// remove whitespace characters, read characer sequence
401 /// not containing whitespace characters or characters in
402 /// delimChars, and remove further whitespace characters.
404 /// @return true if a string of length > 0 could be read.
406 bool readTypeOrKey(docstring & val, idocfstream & ifs,
407 docstring const & delimChars, docstring const &illegalChars,
420 } while (ifs && isSpace(ch));
426 bool legalChar = true;
427 while (ifs && !isSpace(ch) &&
428 delimChars.find(ch) == docstring::npos &&
429 (legalChar = (illegalChars.find(ch) == docstring::npos))
432 if (chCase == makeLowerCase)
433 val += lowercase(ch);
445 while (ifs && isSpace(ch)) {
453 return val.length() > 0;
456 /// read subsequent bibtex values that are delimited with a #-character.
457 /// Concatenate all parts and replace names with the associated string in
458 /// the variable strings.
459 /// @return true if reading was successfull (all single parts were delimited
461 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
474 } while (ifs && isSpace(ch));
479 // check for field type
482 // read integer value
486 } while (ifs && isDigit(ch));
491 } else if (ch == '"' || ch == '{') {
493 char_type delim = ch == '"' ? '"': '}';
498 } while (ifs && isSpace(ch));
503 //We now have the first non-whitespace character
504 //We'll collapse adjacent whitespace.
505 bool lastWasWhiteSpace = false;
507 // inside this delimited text braces must match.
508 // Thus we can have a closing delimiter only
509 // when nestLevel == 0
512 while (ifs && (nestLevel > 0 || ch != delim)) {
514 lastWasWhiteSpace = true;
518 //We output the space only after we stop getting
519 //whitespace so as not to output any whitespace
520 //at the end of the value.
521 if (lastWasWhiteSpace) {
522 lastWasWhiteSpace = false;
528 // update nesting level
535 if (nestLevel < 0) return false;
552 // reading a string name
555 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
556 strName += lowercase(ch);
563 // replace the string with its assigned value or
564 // discard it if it's not assigned
565 if (strName.length()) {
566 VarMap::const_iterator pos = strings.find(strName);
567 if (pos != strings.end()) {
574 while (ifs && isSpace(ch)) {
581 // continue reading next value on concatenate with '#'
591 // This method returns a comma separated list of Bibtex entries
592 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
593 BiblioInfo & keylist, InsetIterator const & /*di*/) const
595 vector<FileName> const files = getFiles(buffer);
596 for (vector<FileName>::const_iterator it = files.begin();
597 it != files.end(); ++ it) {
598 // This bibtex parser is a first step to parse bibtex files
601 // - it reads the whole bibtex entry and does a syntax check
602 // (matching delimiters, missing commas,...
603 // - it recovers from errors starting with the next @-character
604 // - it reads @string definitions and replaces them in the
606 // - it accepts more characters in keys or value names than
609 // Officially bibtex does only support ASCII, but in practice
610 // you can use the encoding of the main document as long as
611 // some elements like keys and names are pure ASCII. Therefore
612 // we convert the file from the buffer encoding.
613 // We don't restrict keys to ASCII in LyX, since our own
614 // InsetBibitem can generate non-ASCII keys, and nonstandard
615 // 8bit clean bibtex forks exist.
617 idocfstream ifs(it->toFilesystemEncoding().c_str(),
619 buffer.params().encoding().iconvName());
635 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
636 docstring(), makeLowerCase) || !ifs)
639 if (entryType == from_ascii("comment")) {
641 ifs.ignore(std::numeric_limits<int>::max(), '\n');
649 if ((ch != '(') && (ch != '{')) {
650 // invalid entry delimiter
656 if (entryType == from_ascii("string")) {
658 // read string and add it to the strings map
659 // (or replace it's old value)
663 if (!readTypeOrKey(name, ifs, from_ascii("="),
664 from_ascii("#{}(),"), makeLowerCase) || !ifs)
667 // next char must be an equal sign
669 if (!ifs || ch != '=')
672 if (!readValue(value, ifs, strings))
675 strings[name] = value;
677 } else if (entryType == from_ascii("preamble")) {
679 // preamble definitions are discarded.
680 // can they be of any use in lyx?
683 if (!readValue(value, ifs, strings))
688 // Citation entry. Try to read the key.
691 if (!readTypeOrKey(key, ifs, from_ascii(","),
692 from_ascii("}"), keepCase) || !ifs)
695 /////////////////////////////////////////////
696 // now we have a key, so we will add an entry
697 // (even if it's empty, as bibtex does)
699 // we now read the field = value pairs.
700 // all items must be separated by a comma. If
701 // it is missing the scanning of this entry is
702 // stopped and the next is searched.
706 docstring commaNewline;
708 BibTeXInfo keyvalmap;
709 keyvalmap.entryType = entryType;
711 bool readNext = removeWSAndComma(ifs);
713 while (ifs && readNext) {
716 if (!readTypeOrKey(name, ifs, from_ascii("="),
717 from_ascii("{}(),"), makeLowerCase) || !ifs)
720 // next char must be an equal sign
730 if (!readValue(value, ifs, strings))
733 keyvalmap[name] = value;
734 data += "\n\n" + value;
735 keylist.fieldNames.insert(name);
736 readNext = removeWSAndComma(ifs);
740 keylist.entryTypes.insert(entryType);
741 keyvalmap.allData = data;
742 keyvalmap.isBibTeX = true;
743 keyvalmap.bibKey = key;
744 keylist[key] = keyvalmap;
747 } //< for loop over files
752 bool InsetBibtex::addDatabase(string const & db)
755 string bibfiles(to_utf8(getParam("bibfiles")));
756 if (tokenPos(bibfiles, ',', db) == -1) {
757 if (!bibfiles.empty())
759 setParam("bibfiles", from_utf8(bibfiles + db));
766 bool InsetBibtex::delDatabase(string const & db)
769 string bibfiles(to_utf8(getParam("bibfiles")));
770 if (contains(bibfiles, db)) {
771 int const n = tokenPos(bibfiles, ',', db);
774 // this is not the first database
775 string tmp = ',' + bd;
776 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
778 // this is the first (or only) database
779 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
787 void InsetBibtex::validate(LaTeXFeatures & features) const
789 if (features.bufferParams().use_bibtopic)
790 features.require("bibtopic");