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::isFileReadable;
51 using support::isValidLaTeXFilename;
52 using support::latex_path;
54 using support::makeAbsPath;
55 using support::makeRelPath;
56 using support::prefixIs;
57 using support::removeExtension;
61 using support::tokenPos;
63 using support::lowercase;
65 namespace Alert = frontend::Alert;
66 namespace os = support::os;
77 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
78 : InsetCommand(p, "bibtex")
82 Inset * InsetBibtex::clone() const
84 return new InsetBibtex(*this);
88 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
92 case LFUN_INSET_MODIFY: {
93 InsetCommandParams p("bibtex");
95 if (!InsetCommandMailer::string2params("bibtex",
96 to_utf8(cmd.argument()), p)) {
100 } catch (support::ExceptionMessage const & message) {
101 if (message.type_ == support::WarningException) {
102 Alert::warning(message.title_, message.details_);
109 cur.buffer().updateBibfilesCache();
114 InsetCommand::doDispatch(cur, cmd);
120 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
122 return _("BibTeX Generated Bibliography");
128 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
129 string const & name, string const & ext)
131 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
132 if (absolutePath(name) || !isFileReadable(FileName(fname + ext)))
134 else if (!runparams.nice)
138 return to_utf8(makeRelPath(from_utf8(fname),
139 from_utf8(buffer.getMasterBuffer()->filePath())));
145 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
146 OutputParams const & runparams) const
148 // the sequence of the commands:
149 // 1. \bibliographystyle{style}
150 // 2. \addcontentsline{...} - if option bibtotoc set
151 // 3. \bibliography{database}
152 // and with bibtopic:
153 // 1. \bibliographystyle{style}
154 // 2. \begin{btSect}{database}
155 // 3. \btPrint{Cited|NotCited|All}
159 // If we are processing the LaTeX file in a temp directory then
160 // copy the .bib databases to this temp directory, mangling their
161 // names in the process. Store this mangled name in the list of
163 // (We need to do all this because BibTeX *really*, *really*
164 // can't handle "files with spaces" and Windows users tend to
165 // use such filenames.)
166 // Otherwise, store the (maybe absolute) path to the original,
167 // unmangled database name.
168 typedef boost::char_separator<char_type> Separator;
169 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
171 Separator const separator(from_ascii(",").c_str());
172 // The tokenizer must not be called with temporary strings, since
173 // it does not make a copy and uses iterators of the string further
174 // down. getParam returns a reference, so this is OK.
175 Tokenizer const tokens(getParam("bibfiles"), separator);
176 Tokenizer::const_iterator const begin = tokens.begin();
177 Tokenizer::const_iterator const end = tokens.end();
179 odocstringstream dbs;
180 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
181 docstring const input = trim(*it);
183 string utf8input(to_utf8(input));
185 normalize_name(buffer, runparams, utf8input, ".bib");
186 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
187 bool const not_from_texmf = isFileReadable(try_in_file);
189 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
192 // mangledFilename() needs the extension
193 DocFileName const in_file = DocFileName(try_in_file);
194 database = removeExtension(in_file.mangledFilename());
195 FileName const out_file(makeAbsPath(database + ".bib",
196 buffer.getMasterBuffer()->temppath()));
198 bool const success = copy(in_file, out_file);
200 lyxerr << "Failed to copy '" << in_file
201 << "' to '" << out_file << "'"
204 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
205 !isValidLaTeXFilename(database)) {
206 frontend::Alert::warning(_("Invalid filename"),
207 _("The following filename is likely to cause trouble "
208 "when running the exported file through LaTeX: ") +
209 from_utf8(database));
215 dbs << from_utf8(latex_path(database));
217 docstring const db_out = dbs.str();
219 // Post this warning only once.
220 static bool warned_about_spaces = false;
221 if (!warned_about_spaces &&
222 runparams.nice && db_out.find(' ') != docstring::npos) {
223 warned_about_spaces = true;
225 Alert::warning(_("Export Warning!"),
226 _("There are spaces in the paths to your BibTeX databases.\n"
227 "BibTeX will be unable to find them."));
232 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
234 if (prefixIs(style, "bibtotoc")) {
235 bibtotoc = "bibtotoc";
236 if (contains(style, ',')) {
237 style = split(style, bibtotoc, ',');
244 if (!style.empty()) {
246 normalize_name(buffer, runparams, style, ".bst");
247 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
248 bool const not_from_texmf = isFileReadable(try_in_file);
249 // If this style does not come from texmf and we are not
250 // exporting to .tex copy it to the tmp directory.
251 // This prevents problems with spaces and 8bit charcaters
253 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
255 // use new style name
256 DocFileName const in_file = DocFileName(try_in_file);
257 base = removeExtension(in_file.mangledFilename());
258 FileName const out_file(makeAbsPath(base + ".bst",
259 buffer.getMasterBuffer()->temppath()));
260 bool const success = copy(in_file, out_file);
262 lyxerr << "Failed to copy '" << in_file
263 << "' to '" << out_file << "'"
268 os << "\\bibliographystyle{"
269 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
274 // Post this warning only once.
275 static bool warned_about_bst_spaces = false;
276 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
277 warned_about_bst_spaces = true;
278 Alert::warning(_("Export Warning!"),
279 _("There are spaces in the path to your BibTeX style file.\n"
280 "BibTeX will be unable to find it."));
283 if (!db_out.empty() && buffer.params().use_bibtopic){
284 os << "\\begin{btSect}{" << db_out << "}\n";
285 docstring btprint = getParam("btprint");
288 btprint = from_ascii("btPrintCited");
289 os << "\\" << btprint << "\n"
290 << "\\end{btSect}\n";
295 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
296 // maybe a problem when a textclass has no "art" as
297 // part of its name, because it's than book.
298 // For the "official" lyx-layouts it's no problem to support
300 if (!contains(buffer.params().getTextClass().name(),
302 if (buffer.params().sides == TextClass::OneSide) {
307 os << "\\cleardoublepage";
311 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
315 os << "\\addcontentsline{toc}{section}{\\refname}";
319 if (!db_out.empty() && !buffer.params().use_bibtopic){
320 os << "\\bibliography{" << db_out << "}\n";
328 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
330 FileName path(buffer.filePath());
331 support::Path p(path);
333 vector<FileName> vec;
337 string bibfiles = to_utf8(getParam("bibfiles"));
338 bibfiles = split(bibfiles, tmp, ',');
339 while (!tmp.empty()) {
340 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
341 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
343 // If we didn't find a matching file name just fail silently
347 // Get next file name
348 bibfiles = split(bibfiles, tmp, ',');
356 // methods for parsing bibtex files
358 typedef map<docstring, docstring> VarMap;
360 /// remove whitespace characters, optionally a single comma,
361 /// and further whitespace characters from the stream.
362 /// @return true if a comma was found, false otherwise
364 bool removeWSAndComma(idocfstream & ifs) {
373 } while (ifs && isSpace(ch));
386 } while (ifs && isSpace(ch));
401 /// remove whitespace characters, read characer sequence
402 /// not containing whitespace characters or characters in
403 /// delimChars, and remove further whitespace characters.
405 /// @return true if a string of length > 0 could be read.
407 bool readTypeOrKey(docstring & val, idocfstream & ifs,
408 docstring const & delimChars, docstring const &illegalChars,
421 } while (ifs && isSpace(ch));
427 bool legalChar = true;
428 while (ifs && !isSpace(ch) &&
429 delimChars.find(ch) == docstring::npos &&
430 (legalChar = (illegalChars.find(ch) == docstring::npos))
433 if (chCase == makeLowerCase)
434 val += lowercase(ch);
446 while (ifs && isSpace(ch)) {
454 return val.length() > 0;
457 /// read subsequent bibtex values that are delimited with a #-character.
458 /// Concatenate all parts and replace names with the associated string in
459 /// the variable strings.
460 /// @return true if reading was successfull (all single parts were delimited
462 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
475 } while (ifs && isSpace(ch));
480 // check for field type
483 // read integer value
487 } while (ifs && isDigit(ch));
492 } else if (ch == '"' || ch == '{') {
494 char_type delim = ch == '"' ? '"': '}';
499 } while (ifs && isSpace(ch));
504 //We now have the first non-whitespace character
505 //We'll collapse adjacent whitespace.
506 bool lastWasWhiteSpace = false;
508 // inside this delimited text braces must match.
509 // Thus we can have a closing delimiter only
510 // when nestLevel == 0
513 while (ifs && (nestLevel > 0 || ch != delim)) {
515 lastWasWhiteSpace = true;
519 //We output the space only after we stop getting
520 //whitespace so as not to output any whitespace
521 //at the end of the value.
522 if (lastWasWhiteSpace) {
523 lastWasWhiteSpace = false;
529 // update nesting level
536 if (nestLevel < 0) return false;
553 // reading a string name
556 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
557 strName += lowercase(ch);
564 // replace the string with its assigned value or
565 // discard it if it's not assigned
566 if (strName.length()) {
567 VarMap::const_iterator pos = strings.find(strName);
568 if (pos != strings.end()) {
575 while (ifs && isSpace(ch)) {
582 // continue reading next value on concatenate with '#'
592 // This method returns a comma separated list of Bibtex entries
593 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
594 BiblioInfo & keylist, InsetIterator const & /*di*/) const
596 vector<FileName> const files = getFiles(buffer);
597 for (vector<FileName>::const_iterator it = files.begin();
598 it != files.end(); ++ it) {
599 // This bibtex parser is a first step to parse bibtex files
602 // - it reads the whole bibtex entry and does a syntax check
603 // (matching delimiters, missing commas,...
604 // - it recovers from errors starting with the next @-character
605 // - it reads @string definitions and replaces them in the
607 // - it accepts more characters in keys or value names than
610 // Officially bibtex does only support ASCII, but in practice
611 // you can use the encoding of the main document as long as
612 // some elements like keys and names are pure ASCII. Therefore
613 // we convert the file from the buffer encoding.
614 // We don't restrict keys to ASCII in LyX, since our own
615 // InsetBibitem can generate non-ASCII keys, and nonstandard
616 // 8bit clean bibtex forks exist.
618 idocfstream ifs(it->toFilesystemEncoding().c_str(),
620 buffer.params().encoding().iconvName());
636 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
637 docstring(), makeLowerCase) || !ifs)
640 if (entryType == from_ascii("comment")) {
642 ifs.ignore(std::numeric_limits<int>::max(), '\n');
650 if ((ch != '(') && (ch != '{')) {
651 // invalid entry delimiter
657 if (entryType == from_ascii("string")) {
659 // read string and add it to the strings map
660 // (or replace it's old value)
664 if (!readTypeOrKey(name, ifs, from_ascii("="),
665 from_ascii("#{}(),"), makeLowerCase) || !ifs)
668 // next char must be an equal sign
670 if (!ifs || ch != '=')
673 if (!readValue(value, ifs, strings))
676 strings[name] = value;
678 } else if (entryType == from_ascii("preamble")) {
680 // preamble definitions are discarded.
681 // can they be of any use in lyx?
684 if (!readValue(value, ifs, strings))
689 // Citation entry. Try to read the key.
692 if (!readTypeOrKey(key, ifs, from_ascii(","),
693 from_ascii("}"), keepCase) || !ifs)
696 /////////////////////////////////////////////
697 // now we have a key, so we will add an entry
698 // (even if it's empty, as bibtex does)
700 // we now read the field = value pairs.
701 // all items must be separated by a comma. If
702 // it is missing the scanning of this entry is
703 // stopped and the next is searched.
707 docstring commaNewline;
709 BibTeXInfo keyvalmap;
710 keyvalmap.entryType = entryType;
712 bool readNext = removeWSAndComma(ifs);
714 while (ifs && readNext) {
717 if (!readTypeOrKey(name, ifs, from_ascii("="),
718 from_ascii("{}(),"), makeLowerCase) || !ifs)
721 // next char must be an equal sign
731 if (!readValue(value, ifs, strings))
734 keyvalmap[name] = value;
735 data += "\n\n" + value;
736 keylist.fieldNames.insert(name);
737 readNext = removeWSAndComma(ifs);
741 keylist.entryTypes.insert(entryType);
742 keyvalmap.allData = data;
743 keyvalmap.isBibTeX = true;
744 keyvalmap.bibKey = key;
745 keylist[key] = keyvalmap;
748 } //< for loop over files
753 bool InsetBibtex::addDatabase(string const & db)
756 string bibfiles(to_utf8(getParam("bibfiles")));
757 if (tokenPos(bibfiles, ',', db) == -1) {
758 if (!bibfiles.empty())
760 setParam("bibfiles", from_utf8(bibfiles + db));
767 bool InsetBibtex::delDatabase(string const & db)
770 string bibfiles(to_utf8(getParam("bibfiles")));
771 if (contains(bibfiles, db)) {
772 int const n = tokenPos(bibfiles, ',', db);
775 // this is not the first database
776 string tmp = ',' + bd;
777 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
779 // this is the first (or only) database
780 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
788 void InsetBibtex::validate(LaTeXFeatures & features) const
790 if (features.bufferParams().use_bibtopic)
791 features.require("bibtopic");