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
8 * Full author contact details are available in file CREDITS.
13 #include "InsetBibtex.h"
16 #include "BufferParams.h"
17 #include "DispatchResult.h"
20 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "MetricsInfo.h"
24 #include "OutputParams.h"
26 #include "frontends/alert.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/Path.h"
33 #include "support/textutils.h"
35 #include <boost/tokenizer.hpp>
40 using support::absolutePath;
41 using support::ascii_lowercase;
42 using support::changeExtension;
43 using support::contains;
45 using support::DocFileName;
46 using support::FileName;
47 using support::findtexfile;
48 using support::isFileReadable;
49 using support::isValidLaTeXFilename;
50 using support::latex_path;
52 using support::makeAbsPath;
53 using support::makeRelPath;
54 using support::prefixIs;
55 using support::removeExtension;
59 using support::tokenPos;
61 using support::lowercase;
63 namespace Alert = frontend::Alert;
64 namespace os = support::os;
75 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
76 : InsetCommand(p, "bibtex")
80 std::auto_ptr<Inset> InsetBibtex::doClone() const
82 return std::auto_ptr<Inset>(new InsetBibtex(*this));
86 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
90 case LFUN_INSET_MODIFY: {
91 InsetCommandParams p("bibtex");
92 InsetCommandMailer::string2params("bibtex", to_utf8(cmd.argument()), p);
93 if (!p.getCmdName().empty()) {
95 cur.buffer().updateBibfilesCache();
102 InsetCommand::doDispatch(cur, cmd);
108 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
110 return _("BibTeX Generated Bibliography");
116 string normalize_name(Buffer const & buffer, OutputParams const & runparams,
117 string const & name, string const & ext)
119 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
120 if (absolutePath(name) || !isFileReadable(FileName(fname + ext)))
122 else if (!runparams.nice)
126 return to_utf8(makeRelPath(from_utf8(fname),
127 from_utf8(buffer.getMasterBuffer()->filePath())));
133 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
134 OutputParams const & runparams) const
136 // the sequence of the commands:
137 // 1. \bibliographystyle{style}
138 // 2. \addcontentsline{...} - if option bibtotoc set
139 // 3. \bibliography{database}
140 // and with bibtopic:
141 // 1. \bibliographystyle{style}
142 // 2. \begin{btSect}{database}
143 // 3. \btPrint{Cited|NotCited|All}
147 // If we are processing the LaTeX file in a temp directory then
148 // copy the .bib databases to this temp directory, mangling their
149 // names in the process. Store this mangled name in the list of
151 // (We need to do all this because BibTeX *really*, *really*
152 // can't handle "files with spaces" and Windows users tend to
153 // use such filenames.)
154 // Otherwise, store the (maybe absolute) path to the original,
155 // unmangled database name.
156 typedef boost::char_separator<char_type> Separator;
157 typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
159 Separator const separator(from_ascii(",").c_str());
160 // The tokenizer must not be called with temporary strings, since
161 // it does not make a copy and uses iterators of the string further
162 // down. getParam returns a reference, so this is OK.
163 Tokenizer const tokens(getParam("bibfiles"), separator);
164 Tokenizer::const_iterator const begin = tokens.begin();
165 Tokenizer::const_iterator const end = tokens.end();
167 odocstringstream dbs;
168 for (Tokenizer::const_iterator it = begin; it != end; ++it) {
169 docstring const input = trim(*it);
171 string utf8input(to_utf8(input));
173 normalize_name(buffer, runparams, utf8input, ".bib");
174 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
175 bool const not_from_texmf = isFileReadable(try_in_file);
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.getMasterBuffer()->temppath()));
186 bool const success = copy(in_file, 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));
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."));
220 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
222 if (prefixIs(style, "bibtotoc")) {
223 bibtotoc = "bibtotoc";
224 if (contains(style, ',')) {
225 style = split(style, bibtotoc, ',');
232 if (!style.empty()) {
234 normalize_name(buffer, runparams, style, ".bst");
235 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
236 bool const not_from_texmf = isFileReadable(try_in_file);
237 // If this style does not come from texmf and we are not
238 // exporting to .tex copy it to the tmp directory.
239 // This prevents problems with spaces and 8bit charcaters
241 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
243 // use new style name
244 DocFileName const in_file = DocFileName(try_in_file);
245 base = removeExtension(in_file.mangledFilename());
246 FileName const out_file(makeAbsPath(base + ".bst",
247 buffer.getMasterBuffer()->temppath()));
248 bool const success = copy(in_file, out_file);
250 lyxerr << "Failed to copy '" << in_file
251 << "' to '" << out_file << "'"
256 os << "\\bibliographystyle{"
257 << from_utf8(latex_path(normalize_name(buffer, runparams, base, ".bst")))
262 // Post this warning only once.
263 static bool warned_about_bst_spaces = false;
264 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
265 warned_about_bst_spaces = true;
266 Alert::warning(_("Export Warning!"),
267 _("There are spaces in the path to your BibTeX style file.\n"
268 "BibTeX will be unable to find it."));
271 if (!db_out.empty() && buffer.params().use_bibtopic){
272 os << "\\begin{btSect}{" << db_out << "}\n";
273 docstring btprint = getParam("btprint");
276 btprint = from_ascii("btPrintCited");
277 os << "\\" << btprint << "\n"
278 << "\\end{btSect}\n";
283 if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
284 // maybe a problem when a textclass has no "art" as
285 // part of its name, because it's than book.
286 // For the "official" lyx-layouts it's no problem to support
288 if (!contains(buffer.params().getTextClass().name(),
290 if (buffer.params().sides == TextClass::OneSide) {
295 os << "\\cleardoublepage";
299 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
303 os << "\\addcontentsline{toc}{section}{\\refname}";
307 if (!db_out.empty() && !buffer.params().use_bibtopic){
308 os << "\\bibliography{" << db_out << "}\n";
316 vector<FileName> const InsetBibtex::getFiles(Buffer const & buffer) const
318 FileName path(buffer.filePath());
319 support::Path p(path);
321 vector<FileName> vec;
325 string bibfiles = to_utf8(getParam("bibfiles"));
326 bibfiles = split(bibfiles, tmp, ',');
327 while (!tmp.empty()) {
328 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
329 LYXERR(Debug::LATEX) << "Bibfile: " << file << endl;
331 // If we didn't find a matching file name just fail silently
335 // Get next file name
336 bibfiles = split(bibfiles, tmp, ',');
344 // methods for parsing bibtex files
346 typedef map<docstring, docstring> VarMap;
348 /// remove whitespace characters, optionally a single comma,
349 /// and further whitespace characters from the stream.
350 /// @return true if a comma was found, false otherwise
352 bool removeWSAndComma(idocfstream & ifs) {
361 } while (ifs && isSpace(ch));
374 } while (ifs && isSpace(ch));
389 /// remove whitespace characters, read characer sequence
390 /// not containing whitespace characters or characters in
391 /// delimChars, and remove further whitespace characters.
393 /// @return true if a string of length > 0 could be read.
395 bool readTypeOrKey(docstring & val, idocfstream & ifs,
396 docstring const & delimChars, docstring const &illegalChars,
409 } while (ifs && isSpace(ch));
416 while (ifs && !isSpace(ch) &&
417 delimChars.find(ch) == docstring::npos &&
418 (legalChar = illegalChars.find(ch) == docstring::npos)
420 if (chCase == makeLowerCase) {
421 val += lowercase(ch);
434 while (ifs && isSpace(ch)) {
442 return val.length() > 0;
445 /// read subsequent bibtex values that are delimited with a #-character.
446 /// Concatenate all parts and replace names with the associated string in
447 /// the variable strings.
448 /// @return true if reading was successfull (all single parts were delimited
450 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
463 } while (ifs && isSpace(ch));
468 // check for field type
471 // read integer value
475 } while (ifs && isDigit(ch));
480 } else if (ch == '"' || ch == '{') {
482 // read delimited text - set end delimiter
483 char_type delim = ch == '"'? '"': '}';
485 // inside this delimited text braces must match.
486 // Thus we can have a closing delimiter only
487 // when nestLevel == 0
491 while (ifs && (nestLevel > 0 || ch != delim)) {
494 // update nesting level
501 if (nestLevel < 0) return false;
518 // reading a string name
521 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
522 strName += lowercase(ch);
529 // replace the string with its assigned value or
530 // discard it if it's not assigned
531 if (strName.length()) {
532 VarMap::const_iterator pos = strings.find(strName);
533 if (pos != strings.end()) {
540 while (ifs && isSpace(ch)) {
547 // continue reading next value on concatenate with '#'
557 // This method returns a comma separated list of Bibtex entries
558 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
559 std::vector<std::pair<string, docstring> > & keys) const
561 vector<FileName> const files = getFiles(buffer);
562 for (vector<FileName>::const_iterator it = files.begin();
563 it != files.end(); ++ it) {
564 // This bibtex parser is a first step to parse bibtex files
567 // - it reads the whole bibtex entry and does a syntax check
568 // (matching delimiters, missing commas,...
569 // - it recovers from errors starting with the next @-character
570 // - it reads @string definitions and replaces them in the
572 // - it accepts more characters in keys or value names than
576 // - the entries are split into name = value pairs by the
577 // parser. These have to be merged again because of the
578 // way lyx treats the entries ( pair<...>(...) ). The citation
579 // mechanism in lyx should be changed such that it can use
580 // the split entries.
581 // - messages on parsing errors can be generated.
584 // Officially bibtex does only support ASCII, but in practice
585 // you can use the encoding of the main document as long as
586 // some elements like keys and names are pure ASCII. Therefore
587 // we convert the file from the buffer encoding.
588 // We don't restrict keys to ASCII in LyX, since our own
589 // InsetBibitem can generate non-ASCII keys, and nonstandard
590 // 8bit clean bibtex forks exist.
591 idocfstream ifs(it->toFilesystemEncoding().c_str(),
593 buffer.params().encoding().iconvName());
609 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
610 docstring(), makeLowerCase) || !ifs)
613 if (entryType == from_ascii("comment")) {
615 ifs.ignore(std::numeric_limits<int>::max(), '\n');
623 if ((ch != '(') && (ch != '{')) {
624 // invalid entry delimiter
630 if (entryType == from_ascii("string")) {
632 // read string and add it to the strings map
633 // (or replace it's old value)
637 if (!readTypeOrKey(name, ifs, from_ascii("="),
638 from_ascii("#{}(),"), makeLowerCase) || !ifs)
641 // next char must be an equal sign
643 if (!ifs || ch != '=')
646 if (!readValue(value, ifs, strings))
649 strings[name] = value;
651 } else if (entryType == from_ascii("preamble")) {
653 // preamble definitions are discarded.
654 // can they be of any use in lyx?
657 if (!readValue(value, ifs, strings))
662 // Citation entry. Read the key and all name = value pairs
667 docstring commaNewline;
669 if (!readTypeOrKey(key, ifs, from_ascii(","),
670 from_ascii("}"), keepCase) || !ifs)
673 // now we have a key, so we will add an entry
674 // (even if it's empty, as bibtex does)
676 // all items must be separated by a comma. If
677 // it is missing the scanning of this entry is
678 // stopped and the next is searched.
679 bool readNext = removeWSAndComma(ifs);
681 while (ifs && readNext) {
684 if (!readTypeOrKey(name, ifs, from_ascii("="),
685 from_ascii("{}(),"), makeLowerCase) || !ifs)
688 // next char must be an equal sign
698 if (!readValue(value, ifs, strings))
701 // append field to the total entry string.
703 // TODO: Here is where the fields can be put in
704 // a more intelligent structure that preserves
705 // the already known parts.
706 fields += commaNewline;
707 fields += name + from_ascii(" = {") + value + '}';
709 if (!commaNewline.length())
710 commaNewline = from_ascii(",\n");
712 readNext = removeWSAndComma(ifs);
716 keys.push_back(pair<string, docstring>(
717 to_utf8(key), fields));
722 } //< for loop over files
727 bool InsetBibtex::addDatabase(string const & db)
730 string bibfiles(to_utf8(getParam("bibfiles")));
731 if (tokenPos(bibfiles, ',', db) == -1) {
732 if (!bibfiles.empty())
734 setParam("bibfiles", from_utf8(bibfiles + db));
741 bool InsetBibtex::delDatabase(string const & db)
744 string bibfiles(to_utf8(getParam("bibfiles")));
745 if (contains(bibfiles, db)) {
746 int const n = tokenPos(bibfiles, ',', db);
749 // this is not the first database
750 string tmp = ',' + bd;
751 setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
753 // this is the first (or only) database
754 setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
762 void InsetBibtex::validate(LaTeXFeatures & features) const
764 if (features.bufferParams().use_bibtopic)
765 features.require("bibtopic");