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"
19 #include "EmbeddedFiles.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "MetricsInfo.h"
24 #include "OutputParams.h"
25 #include "TextClass.h"
27 #include "frontends/alert.h"
29 #include "support/debug.h"
30 #include "support/docstream.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/filetools.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35 #include "support/os.h"
36 #include "support/Path.h"
37 #include "support/textutils.h"
42 using namespace lyx::support;
46 namespace Alert = frontend::Alert;
47 namespace os = support::os;
50 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
51 : InsetCommand(p, "bibtex"), bibfiles_()
55 void InsetBibtex::setBuffer(Buffer & buffer)
58 EmbeddedFileList::iterator it = bibfiles_.begin();
59 EmbeddedFileList::iterator it_end = bibfiles_.end();
60 for (; it != it_end; ++it)
61 *it = it->copyTo(&buffer);
63 Inset::setBuffer(buffer);
67 ParamInfo const & InsetBibtex::findInfo(string const & /* cmdName */)
69 static ParamInfo param_info_;
70 if (param_info_.empty()) {
71 param_info_.add("btprint", ParamInfo::LATEX_OPTIONAL);
72 param_info_.add("bibfiles", ParamInfo::LATEX_REQUIRED);
73 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
74 param_info_.add("options", ParamInfo::LYX_INTERNAL);
80 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
84 case LFUN_INSET_MODIFY: {
85 InsetCommandParams p(BIBTEX_CODE);
87 if (!InsetCommandMailer::string2params("bibtex",
88 to_utf8(cmd.argument()), p)) {
92 } catch (ExceptionMessage const & message) {
93 if (message.type_ == WarningException) {
94 Alert::warning(message.title_, message.details_);
101 createBibFiles(p["bibfiles"], p["embed"]);
103 buffer().updateBibfilesCache();
108 InsetCommand::doDispatch(cur, cmd);
114 docstring InsetBibtex::screenLabel() const
116 return _("BibTeX Generated Bibliography");
120 static string normalizeName(Buffer const & buffer,
121 OutputParams const & runparams, string const & name, string const & ext)
123 string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
124 if (FileName(name).isAbsolute() || !FileName(fname + ext).isReadableFile())
130 return to_utf8(makeRelPath(from_utf8(fname),
131 from_utf8(buffer.masterBuffer()->filePath())));
135 int InsetBibtex::latex(odocstream & os, OutputParams const & runparams) const
137 // the sequence of the commands:
138 // 1. \bibliographystyle{style}
139 // 2. \addcontentsline{...} - if option bibtotoc set
140 // 3. \bibliography{database}
141 // and with bibtopic:
142 // 1. \bibliographystyle{style}
143 // 2. \begin{btSect}{database}
144 // 3. \btPrint{Cited|NotCited|All}
148 // If we are processing the LaTeX file in a temp directory then
149 // copy the .bib databases to this temp directory, mangling their
150 // names in the process. Store this mangled name in the list of
152 // (We need to do all this because BibTeX *really*, *really*
153 // can't handle "files with spaces" and Windows users tend to
154 // use such filenames.)
155 // Otherwise, store the (maybe absolute) path to the original,
156 // unmangled database name.
157 EmbeddedFileList::const_iterator it = bibfiles_.begin();
158 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
159 odocstringstream dbs;
160 for (; it != it_end; ++it) {
161 string utf8input = removeExtension(it->availableFile().absFilename());
163 normalizeName(buffer(), runparams, utf8input, ".bib");
164 FileName const try_in_file =
165 makeAbsPath(database + ".bib", buffer().filePath());
166 bool const not_from_texmf = try_in_file.isReadableFile();
168 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
171 // mangledFilename() needs the extension
172 DocFileName const in_file = DocFileName(try_in_file);
173 database = removeExtension(in_file.mangledFilename());
174 FileName const out_file = makeAbsPath(database + ".bib",
175 buffer().masterBuffer()->temppath());
177 bool const success = in_file.copyTo(out_file);
179 lyxerr << "Failed to copy '" << in_file
180 << "' to '" << out_file << "'"
183 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
184 !isValidLaTeXFilename(database)) {
185 frontend::Alert::warning(_("Invalid filename"),
186 _("The following filename is likely to cause trouble "
187 "when running the exported file through LaTeX: ") +
188 from_utf8(database));
191 if (it != bibfiles_.begin())
194 dbs << from_utf8(latex_path(database));
196 docstring const db_out = dbs.str();
198 // Post this warning only once.
199 static bool warned_about_spaces = false;
200 if (!warned_about_spaces &&
201 runparams.nice && db_out.find(' ') != docstring::npos) {
202 warned_about_spaces = true;
204 Alert::warning(_("Export Warning!"),
205 _("There are spaces in the paths to your BibTeX databases.\n"
206 "BibTeX will be unable to find them."));
210 string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
212 if (prefixIs(style, "bibtotoc")) {
213 bibtotoc = "bibtotoc";
214 if (contains(style, ','))
215 style = split(style, bibtotoc, ',');
221 if (!style.empty()) {
222 string base = normalizeName(buffer(), runparams, style, ".bst");
223 FileName const try_in_file =
224 makeAbsPath(base + ".bst", buffer().filePath());
225 bool const not_from_texmf = try_in_file.isReadableFile();
226 // If this style does not come from texmf and we are not
227 // exporting to .tex copy it to the tmp directory.
228 // This prevents problems with spaces and 8bit charcaters
230 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
232 // use new style name
233 DocFileName const in_file = DocFileName(try_in_file);
234 base = removeExtension(in_file.mangledFilename());
235 FileName const out_file = makeAbsPath(base + ".bst",
236 buffer().masterBuffer()->temppath());
237 bool const success = in_file.copyTo(out_file);
239 lyxerr << "Failed to copy '" << in_file
240 << "' to '" << out_file << "'"
245 os << "\\bibliographystyle{"
246 << from_utf8(latex_path(normalizeName(buffer(), runparams, base, ".bst")))
251 // Post this warning only once.
252 static bool warned_about_bst_spaces = false;
253 if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
254 warned_about_bst_spaces = true;
255 Alert::warning(_("Export Warning!"),
256 _("There are spaces in the path to your BibTeX style file.\n"
257 "BibTeX will be unable to find it."));
260 if (!db_out.empty() && buffer().params().use_bibtopic) {
261 os << "\\begin{btSect}{" << db_out << "}\n";
262 docstring btprint = getParam("btprint");
265 btprint = from_ascii("btPrintCited");
266 os << "\\" << btprint << "\n"
267 << "\\end{btSect}\n";
272 if (!bibtotoc.empty() && !buffer().params().use_bibtopic) {
273 if (buffer().params().documentClass().hasLaTeXLayout("chapter")) {
274 if (buffer().params().sides == OneSide) {
279 os << "\\cleardoublepage";
281 os << "\\addcontentsline{toc}{chapter}{\\bibname}";
282 } else if (buffer().params().documentClass().hasLaTeXLayout("section"))
283 os << "\\addcontentsline{toc}{section}{\\refname}";
286 if (!db_out.empty() && !buffer().params().use_bibtopic) {
287 docstring btprint = getParam("btprint");
288 if (btprint == "btPrintAll") {
289 os << "\\nocite{*}\n";
292 os << "\\bibliography{" << db_out << "}\n";
300 EmbeddedFileList InsetBibtex::embeddedFiles() const
307 // methods for parsing bibtex files
309 typedef map<docstring, docstring> VarMap;
311 /// remove whitespace characters, optionally a single comma,
312 /// and further whitespace characters from the stream.
313 /// @return true if a comma was found, false otherwise
315 bool removeWSAndComma(idocfstream & ifs) {
324 } while (ifs && isSpace(ch));
337 } while (ifs && isSpace(ch));
352 /// remove whitespace characters, read characer sequence
353 /// not containing whitespace characters or characters in
354 /// delimChars, and remove further whitespace characters.
356 /// @return true if a string of length > 0 could be read.
358 bool readTypeOrKey(docstring & val, idocfstream & ifs,
359 docstring const & delimChars, docstring const &illegalChars,
372 } while (ifs && isSpace(ch));
378 bool legalChar = true;
379 while (ifs && !isSpace(ch) &&
380 delimChars.find(ch) == docstring::npos &&
381 (legalChar = (illegalChars.find(ch) == docstring::npos))
384 if (chCase == makeLowerCase)
385 val += lowercase(ch);
397 while (ifs && isSpace(ch)) {
405 return val.length() > 0;
408 /// read subsequent bibtex values that are delimited with a #-character.
409 /// Concatenate all parts and replace names with the associated string in
410 /// the variable strings.
411 /// @return true if reading was successfull (all single parts were delimited
413 bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
426 } while (ifs && isSpace(ch));
431 // check for field type
434 // read integer value
438 } while (ifs && isDigit(ch));
443 } else if (ch == '"' || ch == '{') {
445 char_type delim = ch == '"' ? '"': '}';
450 } while (ifs && isSpace(ch));
455 //We now have the first non-whitespace character
456 //We'll collapse adjacent whitespace.
457 bool lastWasWhiteSpace = false;
459 // inside this delimited text braces must match.
460 // Thus we can have a closing delimiter only
461 // when nestLevel == 0
464 while (ifs && (nestLevel > 0 || ch != delim)) {
466 lastWasWhiteSpace = true;
470 //We output the space only after we stop getting
471 //whitespace so as not to output any whitespace
472 //at the end of the value.
473 if (lastWasWhiteSpace) {
474 lastWasWhiteSpace = false;
480 // update nesting level
487 if (nestLevel < 0) return false;
504 // reading a string name
507 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
508 strName += lowercase(ch);
515 // replace the string with its assigned value or
516 // discard it if it's not assigned
517 if (strName.length()) {
518 VarMap::const_iterator pos = strings.find(strName);
519 if (pos != strings.end()) {
526 while (ifs && isSpace(ch)) {
533 // continue reading next value on concatenate with '#'
543 // This method returns a comma separated list of Bibtex entries
544 void InsetBibtex::fillWithBibKeys(BiblioInfo & keylist,
545 InsetIterator const & /*di*/) const
547 EmbeddedFileList const files = embeddedFiles();
548 for (vector<EmbeddedFile>::const_iterator it = files.begin();
549 it != files.end(); ++ it) {
550 // This bibtex parser is a first step to parse bibtex files
553 // - it reads the whole bibtex entry and does a syntax check
554 // (matching delimiters, missing commas,...
555 // - it recovers from errors starting with the next @-character
556 // - it reads @string definitions and replaces them in the
558 // - it accepts more characters in keys or value names than
561 // Officially bibtex does only support ASCII, but in practice
562 // you can use the encoding of the main document as long as
563 // some elements like keys and names are pure ASCII. Therefore
564 // we convert the file from the buffer encoding.
565 // We don't restrict keys to ASCII in LyX, since our own
566 // InsetBibitem can generate non-ASCII keys, and nonstandard
567 // 8bit clean bibtex forks exist.
569 idocfstream ifs(it->availableFile().toFilesystemEncoding().c_str(),
570 ios_base::in, buffer().params().encoding().iconvName());
586 if (!readTypeOrKey(entryType, ifs, from_ascii("{("),
587 docstring(), makeLowerCase) || !ifs)
590 if (entryType == from_ascii("comment")) {
592 ifs.ignore(numeric_limits<int>::max(), '\n');
600 if ((ch != '(') && (ch != '{')) {
601 // invalid entry delimiter
607 if (entryType == from_ascii("string")) {
609 // read string and add it to the strings map
610 // (or replace it's old value)
614 if (!readTypeOrKey(name, ifs, from_ascii("="),
615 from_ascii("#{}(),"), makeLowerCase) || !ifs)
618 // next char must be an equal sign
620 if (!ifs || ch != '=')
623 if (!readValue(value, ifs, strings))
626 strings[name] = value;
628 } else if (entryType == from_ascii("preamble")) {
630 // preamble definitions are discarded.
631 // can they be of any use in lyx?
634 if (!readValue(value, ifs, strings))
639 // Citation entry. Try to read the key.
642 if (!readTypeOrKey(key, ifs, from_ascii(","),
643 from_ascii("}"), keepCase) || !ifs)
646 /////////////////////////////////////////////
647 // now we have a key, so we will add an entry
648 // (even if it's empty, as bibtex does)
650 // we now read the field = value pairs.
651 // all items must be separated by a comma. If
652 // it is missing the scanning of this entry is
653 // stopped and the next is searched.
657 docstring commaNewline;
659 BibTeXInfo keyvalmap(key, entryType);
661 bool readNext = removeWSAndComma(ifs);
663 while (ifs && readNext) {
666 if (!readTypeOrKey(name, ifs, from_ascii("="),
667 from_ascii("{}(),"), makeLowerCase) || !ifs)
670 // next char must be an equal sign
680 if (!readValue(value, ifs, strings))
683 keyvalmap[name] = value;
684 data += "\n\n" + value;
685 keylist.addFieldName(name);
686 readNext = removeWSAndComma(ifs);
690 keylist.addEntryType(entryType);
691 keyvalmap.setAllData(data);
692 keylist[key] = keyvalmap;
695 } //< for loop over files
700 bool InsetBibtex::addDatabase(string const & db)
702 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
704 // only compare filename
705 EmbeddedFileList::iterator it = bibfiles_.begin();
706 EmbeddedFileList::iterator it_end = bibfiles_.end();
707 for (; it != it_end; ++it)
708 if (it->absFilename() == file.absFilename())
711 bibfiles_.push_back(file);
717 bool InsetBibtex::delDatabase(string const & db)
719 EmbeddedFile file(changeExtension(db, "bib"), buffer().filePath());
721 // only compare filename
722 EmbeddedFileList::iterator it = bibfiles_.begin();
723 EmbeddedFileList::iterator it_end = bibfiles_.end();
724 for (; it != it_end; ++it)
725 if (it->absFilename() == file.absFilename()) {
734 void InsetBibtex::validate(LaTeXFeatures & features) const
736 if (features.bufferParams().use_bibtopic)
737 features.require("bibtopic");
741 void InsetBibtex::createBibFiles(docstring const & bibParam,
742 docstring const & embedParam) const
749 string bibfiles = to_utf8(bibParam);
750 string embedStatus = to_utf8(embedParam);
752 LYXERR(Debug::FILES, "Create bib files from parameters "
753 << bibfiles << " and " << embedStatus);
755 bibfiles = split(bibfiles, tmp, ',');
756 embedStatus = split(embedStatus, emb, ',');
758 while (!tmp.empty()) {
759 EmbeddedFile file(changeExtension(tmp, "bib"), buffer().filePath());
761 file.setInzipName(emb);
762 file.setEmbed(!emb.empty());
763 file.enable(buffer().embedded(), &buffer(), false);
764 bibfiles_.push_back(file);
765 // Get next file name
766 bibfiles = split(bibfiles, tmp, ',');
767 embedStatus = split(embedStatus, emb, ',');
772 void InsetBibtex::updateParam()
778 for (EmbeddedFileList::iterator it = bibfiles_.begin();
779 it != bibfiles_.end(); ++it) {
785 bibfiles += from_utf8(it->outputFilename(buffer().filePath()));
787 embed += from_utf8(it->inzipName());
789 setParam("bibfiles", bibfiles);
790 setParam("embed", embed);
794 void InsetBibtex::registerEmbeddedFiles(EmbeddedFileList & files) const
796 if (bibfiles_.empty())
797 createBibFiles(params()["bibfiles"], params()["embed"]);
799 EmbeddedFileList::const_iterator it = bibfiles_.begin();
800 EmbeddedFileList::const_iterator it_end = bibfiles_.end();
801 for (; it != it_end; ++it)
802 files.registerFile(*it, this, buffer());
806 void InsetBibtex::updateEmbeddedFile(EmbeddedFile const & file)
808 // look for the item and update status
809 for (EmbeddedFileList::iterator it = bibfiles_.begin();
810 it != bibfiles_.end(); ++it)
811 if (it->absFilename() == file.absFilename())