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 CommandInfo const * InsetBibtex::findInfo(std::string const & /* cmdName */)
83 static const char * const paramnames[] =
84 {"options", "btprint", "bibfiles", ""};
85 static const bool isoptional[] = {true, true, false};
86 static const CommandInfo info = {3, paramnames, isoptional};
91 Inset * InsetBibtex::clone() const
93 return new InsetBibtex(*this);
97 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
101 case LFUN_INSET_MODIFY: {
102 InsetCommandParams p(BIBTEX_CODE);
104 if (!InsetCommandMailer::string2params("bibtex",
105 to_utf8(cmd.argument()), p)) {
109 } catch (support::ExceptionMessage const & message) {
110 if (message.type_ == support::WarningException) {
111 Alert::warning(message.title_, message.details_);
118 cur.buffer().updateBibfilesCache();
123 InsetCommand::doDispatch(cur, cmd);
129 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
131 return _("BibTeX Generated Bibliography");
137 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
138 string const & name, string const & ext)
140 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
141 if (absolutePath(name) || !FileName(fname + ext).isFileReadable())
147 return to_utf8(makeRelPath(from_utf8(fname),
148 from_utf8(buffer.masterBuffer()->filePath())));
154 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
155 OutputParams const & runparams) const
157 // the sequence of the commands:
158 // 1. \bibliographystyle{style}
159 // 2. \addcontentsline{...} - if option bibtotoc set
160 // 3. \bibliography{database}
161 // and with bibtopic:
162 // 1. \bibliographystyle{style}
163 // 2. \begin{btSect}{database}
164 // 3. \btPrint{Cited|NotCited|All}
168 // If we are processing the LaTeX file in a temp directory then
169 // copy the .bib databases to this temp directory, mangling their
170 // names in the process. Store this mangled name in the list of
172 // (We need to do all this because BibTeX *really*, *really*
173 // can't handle "files with spaces" and Windows users tend to
174 // use such filenames.)
175 // Otherwise, store the (maybe absolute) path to the original,
176 // unmangled database name.
177 typedef boost::char_separator<char_type> Separator;
178 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
180 Separator const separator(from_ascii(",").c_str());
181 // The tokenizer must not be called with temporary strings, since
182 // it does not make a copy and uses iterators of the string further
183 // down. getParam returns a reference, so this is OK.
184 Tokenizer const tokens(getParam("bibfiles"), separator);
185 Tokenizer::const_iterator const begin = tokens.begin();
186 Tokenizer::const_iterator const end = tokens.end();
188 odocstringstream dbs;
189 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
190 docstring const input = trim(*it);
192 string utf8input = to_utf8(input);
194 normalizeName(buffer, runparams, utf8input, ".bib");
195 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
196 bool const not_from_texmf = try_in_file.isFileReadable();
198 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
201 // mangledFilename() needs the extension
202 DocFileName const in_file = DocFileName(try_in_file);
203 database = removeExtension(in_file.mangledFilename());
204 FileName const out_file = makeAbsPath(database + ".bib",
205 buffer.masterBuffer()->temppath());
207 bool const success = copy(in_file, out_file);
209 lyxerr << "Failed to copy '" << in_file
210 << "' to '" << out_file << "'"
213 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
214 !isValidLaTeXFilename(database)) {
215 frontend::Alert::warning(_("Invalid filename"),
216 _("The following filename is likely to cause trouble "
217 "when running the exported file through LaTeX: ") +
218 from_utf8(database));
224 dbs << from_utf8(latex_path(database));
226 docstring const db_out = dbs.str();
228 // Post this warning only once.
229 static bool warned_about_spaces = false;
230 if (!warned_about_spaces &&
231 runparams.nice && db_out.find(' ') != docstring::npos) {
232 warned_about_spaces = true;
234 Alert::warning(_("Export Warning!"),
235 _("There are spaces in the paths to your BibTeX databases.\n"
236 "BibTeX will be unable to find them."));
240 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
242 if (prefixIs(style, "bibtotoc")) {
243 bibtotoc = "bibtotoc";
244 if (contains(style, ','))
245 style = split(style, bibtotoc, ',');
251 if (!style.empty()) {
252 string base = normalizeName(buffer, runparams, style, ".bst");
253 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
254 bool const not_from_texmf = try_in_file.isFileReadable();
255 // If this style does not come from texmf and we are not
256 // exporting to .tex copy it to the tmp directory.
257 // This prevents problems with spaces and 8bit charcaters
259 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
261 // use new style name
262 DocFileName const in_file = DocFileName(try_in_file);
263 base = removeExtension(in_file.mangledFilename());
264 FileName const out_file(makeAbsPath(base + ".bst",
265 buffer.masterBuffer()->temppath()));
266 bool const success = copy(in_file, out_file);
268 lyxerr << "Failed to copy '" << in_file
269 << "' to '" << out_file << "'"
274 os << "\\bibliographystyle{"
275 << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
280 // Post this warning only once.
281 static bool warned_about_bst_spaces = false;
282 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
283 warned_about_bst_spaces = true;
284 Alert::warning(_("Export Warning!"),
285 _("There are spaces in the path to your BibTeX style file.\n"
286 "BibTeX will be unable to find it."));
289 if (!db_out.empty() && buffer.params().use_bibtopic){
290 os << "\\begin{btSect}{" << db_out << "}\n";
291 docstring btprint = getParam("btprint");
294 btprint = from_ascii("btPrintCited");
295 os << "\\" << btprint << "\n"
296 << "\\end{btSect}\n";
301 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
302 // maybe a problem when a textclass has no "art" as
303 // part of its name, because it's than book.
304 // For the "official" lyx-layouts it's no problem to support
306 if (!contains(buffer.params().getTextClass().name(),
308 if (buffer.params().sides == TextClass::OneSide) {
313 os << "\\cleardoublepage";
317 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
321 os << "\\addcontentsline{toc}{section}{\\refname}";
325 if (!db_out.empty() && !buffer.params().use_bibtopic){
326 os << "\\bibliography{" << db_out << "}\n";
334 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
336 FileName path(buffer.filePath());
337 support::Path p(path);
339 vector<FileName> vec;
343 string bibfiles = to_utf8(getParam("bibfiles"));
344 bibfiles = split(bibfiles, tmp, ',');
345 while (!tmp.empty()) {
346 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
347 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
349 // If we didn't find a matching file name just fail silently
353 // Get next file name
354 bibfiles = split(bibfiles, tmp, ',');
362 // methods for parsing bibtex files
364 typedef map<docstring, docstring> VarMap;
366 /// remove whitespace characters, optionally a single comma,
367 /// and further whitespace characters from the stream.
368 /// @return true if a comma was found, false otherwise
370 bool removeWSAndComma(idocfstream & ifs) {
379 } while (ifs && isSpace(ch));
392 } while (ifs && isSpace(ch));
407 /// remove whitespace characters, read characer sequence
408 /// not containing whitespace characters or characters in
409 /// delimChars, and remove further whitespace characters.
411 /// @return true if a string of length > 0 could be read.
413 bool readTypeOrKey(docstring & val, idocfstream & ifs,
414 docstring const & delimChars, docstring const &illegalChars,
427 } while (ifs && isSpace(ch));
433 bool legalChar = true;
434 while (ifs && !isSpace(ch) &&
435 delimChars.find(ch) == docstring::npos &&
436 (legalChar = (illegalChars.find(ch) == docstring::npos))
439 if (chCase == makeLowerCase)
440 val += lowercase(ch);
452 while (ifs && isSpace(ch)) {
460 return val.length() > 0;
463 /// read subsequent bibtex values that are delimited with a #-character.
464 /// Concatenate all parts and replace names with the associated string in
465 /// the variable strings.
466 /// @return true if reading was successfull (all single parts were delimited
468 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
481 } while (ifs && isSpace(ch));
486 // check for field type
489 // read integer value
493 } while (ifs && isDigit(ch));
498 } else if (ch == '"' || ch == '{') {
500 char_type delim = ch == '"' ? '"': '}';
505 } while (ifs && isSpace(ch));
510 //We now have the first non-whitespace character
511 //We'll collapse adjacent whitespace.
512 bool lastWasWhiteSpace = false;
514 // inside this delimited text braces must match.
515 // Thus we can have a closing delimiter only
516 // when nestLevel == 0
519 while (ifs && (nestLevel > 0 || ch != delim)) {
521 lastWasWhiteSpace = true;
525 //We output the space only after we stop getting
526 //whitespace so as not to output any whitespace
527 //at the end of the value.
528 if (lastWasWhiteSpace) {
529 lastWasWhiteSpace = false;
535 // update nesting level
542 if (nestLevel < 0) return false;
559 // reading a string name
562 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
563 strName += lowercase(ch);
570 // replace the string with its assigned value or
571 // discard it if it's not assigned
572 if (strName.length()) {
573 VarMap::const_iterator pos = strings.find(strName);
574 if (pos != strings.end()) {
581 while (ifs && isSpace(ch)) {
588 // continue reading next value on concatenate with '#'
598 // This method returns a comma separated list of Bibtex entries
599 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
600 BiblioInfo & keylist, InsetIterator const & /*di*/) const
602 vector<FileName> const files = getFiles(buffer);
603 for (vector<FileName>::const_iterator it = files.begin();
604 it != files.end(); ++ it) {
605 // This bibtex parser is a first step to parse bibtex files
608 // - it reads the whole bibtex entry and does a syntax check
609 // (matching delimiters, missing commas,...
610 // - it recovers from errors starting with the next @-character
611 // - it reads @string definitions and replaces them in the
613 // - it accepts more characters in keys or value names than
616 // Officially bibtex does only support ASCII, but in practice
617 // you can use the encoding of the main document as long as
618 // some elements like keys and names are pure ASCII. Therefore
619 // we convert the file from the buffer encoding.
620 // We don't restrict keys to ASCII in LyX, since our own
621 // InsetBibitem can generate non-ASCII keys, and nonstandard
622 // 8bit clean bibtex forks exist.
624 idocfstream ifs(it->toFilesystemEncoding().c_str(),
626 buffer.params().encoding().iconvName());
642 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
643 docstring(), makeLowerCase) || !ifs)
646 if (entryType == from_ascii("comment")) {
648 ifs.ignore(std::numeric_limits<int>::max(), '\n');
656 if ((ch != '(') && (ch != '{')) {
657 // invalid entry delimiter
663 if (entryType == from_ascii("string")) {
665 // read string and add it to the strings map
666 // (or replace it's old value)
670 if (!readTypeOrKey(name, ifs, from_ascii("="),
671 from_ascii("#{}(),"), makeLowerCase) || !ifs)
674 // next char must be an equal sign
676 if (!ifs || ch != '=')
679 if (!readValue(value, ifs, strings))
682 strings[name] = value;
684 } else if (entryType == from_ascii("preamble")) {
686 // preamble definitions are discarded.
687 // can they be of any use in lyx?
690 if (!readValue(value, ifs, strings))
695 // Citation entry. Try to read the key.
698 if (!readTypeOrKey(key, ifs, from_ascii(","),
699 from_ascii("}"), keepCase) || !ifs)
702 /////////////////////////////////////////////
703 // now we have a key, so we will add an entry
704 // (even if it's empty, as bibtex does)
706 // we now read the field = value pairs.
707 // all items must be separated by a comma. If
708 // it is missing the scanning of this entry is
709 // stopped and the next is searched.
713 docstring commaNewline;
715 BibTeXInfo keyvalmap;
716 keyvalmap.entryType = entryType;
718 bool readNext = removeWSAndComma(ifs);
720 while (ifs && readNext) {
723 if (!readTypeOrKey(name, ifs, from_ascii("="),
724 from_ascii("{}(),"), makeLowerCase) || !ifs)
727 // next char must be an equal sign
737 if (!readValue(value, ifs, strings))
740 keyvalmap[name] = value;
741 data += "\n\n" + value;
742 keylist.fieldNames.insert(name);
743 readNext = removeWSAndComma(ifs);
747 keylist.entryTypes.insert(entryType);
748 keyvalmap.allData = data;
749 keyvalmap.isBibTeX = true;
750 keyvalmap.bibKey = key;
751 keylist[key] = keyvalmap;
754 } //< for loop over files
759 bool InsetBibtex::addDatabase(string const & db)
762 string bibfiles(to_utf8(getParam("bibfiles")));
763 if (tokenPos(bibfiles, ',', db) == -1) {
764 if (!bibfiles.empty())
766 setParam("bibfiles", from_utf8(bibfiles + db));
773 bool InsetBibtex::delDatabase(string const & db)
776 string bibfiles(to_utf8(getParam("bibfiles")));
777 if (contains(bibfiles, db)) {
778 int const n = tokenPos(bibfiles, ',', db);
781 // this is not the first database
782 string tmp = ',' + bd;
783 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
785 // this is the first (or only) database
786 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
794 void InsetBibtex::validate(LaTeXFeatures & features) const
796 if (features.bufferParams().use_bibtopic)
797 features.require("bibtopic");