]> git.lyx.org Git - lyx.git/blob - src/insets/InsetBibtex.cpp
Introducing FileNameList, cleanup some headers and put back dirList() into FileName.
[lyx.git] / src / insets / InsetBibtex.cpp
1 /**
2  * \file InsetBibtex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Richard Heck (BibTeX parser improvements)
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetBibtex.h"
15
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "DispatchResult.h"
19 #include "support/debug.h"
20 #include "Encoding.h"
21 #include "FuncRequest.h"
22 #include "support/gettext.h"
23 #include "LaTeXFeatures.h"
24 #include "MetricsInfo.h"
25 #include "OutputParams.h"
26 #include "TextClass.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/ExceptionMessage.h"
31 #include "support/docstream.h"
32 #include "support/FileNameList.h"
33 #include "support/filetools.h"
34 #include "support/lstrings.h"
35 #include "support/lyxlib.h"
36 #include "support/os.h"
37 #include "support/Path.h"
38 #include "support/textutils.h"
39
40 #include <boost/tokenizer.hpp>
41
42
43 namespace lyx {
44
45 using support::absolutePath;
46 using support::ascii_lowercase;
47 using support::changeExtension;
48 using support::contains;
49 using support::copy;
50 using support::DocFileName;
51 using support::FileName;
52 using support::FileNameList;
53 using support::findtexfile;
54 using support::isValidLaTeXFilename;
55 using support::latex_path;
56 using support::ltrim;
57 using support::makeAbsPath;
58 using support::makeRelPath;
59 using support::prefixIs;
60 using support::removeExtension;
61 using support::rtrim;
62 using support::split;
63 using support::subst;
64 using support::tokenPos;
65 using support::trim;
66 using support::lowercase;
67
68 namespace Alert = frontend::Alert;
69 namespace os = support::os;
70
71 using std::endl;
72 using std::getline;
73 using std::string;
74 using std::ostream;
75 using std::pair;
76 using std::vector;
77 using std::map;
78
79
80 InsetBibtex::InsetBibtex(InsetCommandParams const & p)
81         : InsetCommand(p, "bibtex")
82 {}
83
84
85 CommandInfo const * InsetBibtex::findInfo(std::string const & /* cmdName */)
86 {
87         static const char * const paramnames[] = 
88                 {"options", "btprint", "bibfiles", ""};
89         static const bool isoptional[] = {true, true, false};
90         static const CommandInfo info = {3, paramnames, isoptional};
91         return &info;
92 }
93
94
95 Inset * InsetBibtex::clone() const
96 {
97         return new InsetBibtex(*this);
98 }
99
100
101 void InsetBibtex::doDispatch(Cursor & cur, FuncRequest & cmd)
102 {
103         switch (cmd.action) {
104
105         case LFUN_INSET_MODIFY: {
106                 InsetCommandParams p(BIBTEX_CODE);
107                 try {
108                         if (!InsetCommandMailer::string2params("bibtex", 
109                                         to_utf8(cmd.argument()), p)) {
110                                 cur.noUpdate();
111                                 break;
112                         }
113                 } catch (support::ExceptionMessage const & message) {
114                         if (message.type_ == support::WarningException) {
115                                 Alert::warning(message.title_, message.details_);
116                                 cur.noUpdate();
117                         } else 
118                                 throw message;
119                         break;
120                 }
121                 setParams(p);
122                 cur.buffer().updateBibfilesCache();
123                 break;
124         }
125
126         default:
127                 InsetCommand::doDispatch(cur, cmd);
128                 break;
129         }
130 }
131
132
133 docstring const InsetBibtex::getScreenLabel(Buffer const &) const
134 {
135         return _("BibTeX Generated Bibliography");
136 }
137
138
139 namespace {
140
141 string normalizeName(Buffer const & buffer, OutputParams const & runparams,
142                       string const & name, string const & ext)
143 {
144         string const fname = makeAbsPath(name, buffer.filePath()).absFilename();
145         if (absolutePath(name) || !FileName(fname + ext).isReadableFile())
146                 return name;
147         if (!runparams.nice)
148                 return fname;
149
150         // FIXME UNICODE
151         return to_utf8(makeRelPath(from_utf8(fname),
152                                          from_utf8(buffer.masterBuffer()->filePath())));
153 }
154
155 }
156
157
158 int InsetBibtex::latex(Buffer const & buffer, odocstream & os,
159                        OutputParams const & runparams) const
160 {
161         // the sequence of the commands:
162         // 1. \bibliographystyle{style}
163         // 2. \addcontentsline{...} - if option bibtotoc set
164         // 3. \bibliography{database}
165         // and with bibtopic:
166         // 1. \bibliographystyle{style}
167         // 2. \begin{btSect}{database}
168         // 3. \btPrint{Cited|NotCited|All}
169         // 4. \end{btSect}
170
171         // Database(s)
172         // If we are processing the LaTeX file in a temp directory then
173         // copy the .bib databases to this temp directory, mangling their
174         // names in the process. Store this mangled name in the list of
175         // all databases.
176         // (We need to do all this because BibTeX *really*, *really*
177         // can't handle "files with spaces" and Windows users tend to
178         // use such filenames.)
179         // Otherwise, store the (maybe absolute) path to the original,
180         // unmangled database name.
181         typedef boost::char_separator<char_type> Separator;
182         typedef boost::tokenizer<Separator, docstring::const_iterator, docstring> Tokenizer;
183
184         Separator const separator(from_ascii(",").c_str());
185         // The tokenizer must not be called with temporary strings, since
186         // it does not make a copy and uses iterators of the string further
187         // down. getParam returns a reference, so this is OK.
188         Tokenizer const tokens(getParam("bibfiles"), separator);
189         Tokenizer::const_iterator const begin = tokens.begin();
190         Tokenizer::const_iterator const end = tokens.end();
191
192         odocstringstream dbs;
193         for (Tokenizer::const_iterator it = begin; it != end; ++it) {
194                 docstring const input = trim(*it);
195                 // FIXME UNICODE
196                 string utf8input = to_utf8(input);
197                 string database =
198                         normalizeName(buffer, runparams, utf8input, ".bib");
199                 FileName const try_in_file(makeAbsPath(database + ".bib", buffer.filePath()));
200                 bool const not_from_texmf = try_in_file.isReadableFile();
201
202                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
203                     not_from_texmf) {
204
205                         // mangledFilename() needs the extension
206                         DocFileName const in_file = DocFileName(try_in_file);
207                         database = removeExtension(in_file.mangledFilename());
208                         FileName const out_file = makeAbsPath(database + ".bib",
209                                         buffer.masterBuffer()->temppath());
210
211                         bool const success = copy(in_file, out_file);
212                         if (!success) {
213                                 lyxerr << "Failed to copy '" << in_file
214                                        << "' to '" << out_file << "'"
215                                        << endl;
216                         }
217                 } else if (!runparams.inComment && runparams.nice && not_from_texmf &&
218                            !isValidLaTeXFilename(database)) {
219                                 frontend::Alert::warning(_("Invalid filename"),
220                                                          _("The following filename is likely to cause trouble "
221                                                            "when running the exported file through LaTeX: ") +
222                                                             from_utf8(database));
223                 }
224
225                 if (it != begin)
226                         dbs << ',';
227                 // FIXME UNICODE
228                 dbs << from_utf8(latex_path(database));
229         }
230         docstring const db_out = dbs.str();
231
232         // Post this warning only once.
233         static bool warned_about_spaces = false;
234         if (!warned_about_spaces &&
235             runparams.nice && db_out.find(' ') != docstring::npos) {
236                 warned_about_spaces = true;
237
238                 Alert::warning(_("Export Warning!"),
239                                _("There are spaces in the paths to your BibTeX databases.\n"
240                                               "BibTeX will be unable to find them."));
241         }
242
243         // Style-Options
244         string style = to_utf8(getParam("options")); // maybe empty! and with bibtotoc
245         string bibtotoc;
246         if (prefixIs(style, "bibtotoc")) {
247                 bibtotoc = "bibtotoc";
248                 if (contains(style, ','))
249                         style = split(style, bibtotoc, ',');
250         }
251
252         // line count
253         int nlines = 0;
254
255         if (!style.empty()) {
256                 string base = normalizeName(buffer, runparams, style, ".bst");
257                 FileName const try_in_file(makeAbsPath(base + ".bst", buffer.filePath()));
258                 bool const not_from_texmf = try_in_file.isReadableFile();
259                 // If this style does not come from texmf and we are not
260                 // exporting to .tex copy it to the tmp directory.
261                 // This prevents problems with spaces and 8bit charcaters
262                 // in the file name.
263                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
264                     not_from_texmf) {
265                         // use new style name
266                         DocFileName const in_file = DocFileName(try_in_file);
267                         base = removeExtension(in_file.mangledFilename());
268                         FileName const out_file(makeAbsPath(base + ".bst",
269                                         buffer.masterBuffer()->temppath()));
270                         bool const success = copy(in_file, out_file);
271                         if (!success) {
272                                 lyxerr << "Failed to copy '" << in_file
273                                        << "' to '" << out_file << "'"
274                                        << endl;
275                         }
276                 }
277                 // FIXME UNICODE
278                 os << "\\bibliographystyle{"
279                    << from_utf8(latex_path(normalizeName(buffer, runparams, base, ".bst")))
280                    << "}\n";
281                 nlines += 1;
282         }
283
284         // Post this warning only once.
285         static bool warned_about_bst_spaces = false;
286         if (!warned_about_bst_spaces && runparams.nice && contains(style, ' ')) {
287                 warned_about_bst_spaces = true;
288                 Alert::warning(_("Export Warning!"),
289                                _("There are spaces in the path to your BibTeX style file.\n"
290                                               "BibTeX will be unable to find it."));
291         }
292
293         if (!db_out.empty() && buffer.params().use_bibtopic){
294                 os << "\\begin{btSect}{" << db_out << "}\n";
295                 docstring btprint = getParam("btprint");
296                 if (btprint.empty())
297                         // default
298                         btprint = from_ascii("btPrintCited");
299                 os << "\\" << btprint << "\n"
300                    << "\\end{btSect}\n";
301                 nlines += 3;
302         }
303
304         // bibtotoc-Option
305         if (!bibtotoc.empty() && !buffer.params().use_bibtopic) {
306                 // maybe a problem when a textclass has no "art" as
307                 // part of its name, because it's than book.
308                 // For the "official" lyx-layouts it's no problem to support
309                 // all well
310                 if (!contains(buffer.params().getTextClass().name(),
311                               "art")) {
312                         if (buffer.params().sides == OneSide) {
313                                 // oneside
314                                 os << "\\clearpage";
315                         } else {
316                                 // twoside
317                                 os << "\\cleardoublepage";
318                         }
319
320                         // bookclass
321                         os << "\\addcontentsline{toc}{chapter}{\\bibname}";
322
323                 } else {
324                         // article class
325                         os << "\\addcontentsline{toc}{section}{\\refname}";
326                 }
327         }
328
329         if (!db_out.empty() && !buffer.params().use_bibtopic){
330                 os << "\\bibliography{" << db_out << "}\n";
331                 nlines += 1;
332         }
333
334         return nlines;
335 }
336
337
338 FileNameList const InsetBibtex::getFiles(Buffer const & buffer) const
339 {
340         FileName path(buffer.filePath());
341         support::PathChanger p(path);
342
343         FileNameList vec;
344
345         string tmp;
346         // FIXME UNICODE
347         string bibfiles = to_utf8(getParam("bibfiles"));
348         bibfiles = split(bibfiles, tmp, ',');
349         while (!tmp.empty()) {
350                 FileName const file = findtexfile(changeExtension(tmp, "bib"), "bib");
351                 LYXERR(Debug::LATEX, "Bibfile: " << file);
352
353                 // If we didn't find a matching file name just fail silently
354                 if (!file.empty())
355                         vec.push_back(file);
356
357                 // Get next file name
358                 bibfiles = split(bibfiles, tmp, ',');
359         }
360
361         return vec;
362 }
363
364 namespace {
365
366         // methods for parsing bibtex files
367
368         typedef map<docstring, docstring> VarMap;
369
370         /// remove whitespace characters, optionally a single comma,
371         /// and further whitespace characters from the stream.
372         /// @return true if a comma was found, false otherwise
373         ///
374         bool removeWSAndComma(idocfstream & ifs) {
375                 char_type ch;
376
377                 if (!ifs)
378                         return false;
379
380                 // skip whitespace
381                 do {
382                         ifs.get(ch);
383                 } while (ifs && isSpace(ch));
384
385                 if (!ifs)
386                         return false;
387
388                 if (ch != ',') {
389                         ifs.putback(ch);
390                         return false;
391                 }
392
393                 // skip whitespace
394                 do {
395                         ifs.get(ch);
396                 } while (ifs && isSpace(ch));
397
398                 if (ifs) {
399                         ifs.putback(ch);
400                 }
401
402                 return true;
403         }
404
405
406         enum charCase {
407                 makeLowerCase,
408                 keepCase
409         };
410
411         /// remove whitespace characters, read characer sequence
412         /// not containing whitespace characters or characters in
413         /// delimChars, and remove further whitespace characters.
414         ///
415         /// @return true if a string of length > 0 could be read.
416         ///
417         bool readTypeOrKey(docstring & val, idocfstream & ifs,
418                 docstring const & delimChars, docstring const &illegalChars, 
419                 charCase chCase) {
420
421                 char_type ch;
422
423                 val.clear();
424
425                 if (!ifs)
426                         return false;
427
428                 // skip whitespace
429                 do {
430                         ifs.get(ch);
431                 } while (ifs && isSpace(ch));
432
433                 if (!ifs)
434                         return false;
435
436                 // read value
437                 bool legalChar = true;
438                 while (ifs && !isSpace(ch) && 
439                                                  delimChars.find(ch) == docstring::npos &&
440                                                  (legalChar = (illegalChars.find(ch) == docstring::npos))
441                                         ) 
442                 {
443                         if (chCase == makeLowerCase)
444                                 val += lowercase(ch);
445                         else
446                                 val += ch;
447                         ifs.get(ch);
448                 }
449                 
450                 if (!legalChar) {
451                         ifs.putback(ch);
452                         return false;
453                 }
454
455                 // skip whitespace
456                 while (ifs && isSpace(ch)) {
457                         ifs.get(ch);
458                 }
459
460                 if (ifs) {
461                         ifs.putback(ch);
462                 }
463
464                 return val.length() > 0;
465         }
466
467         /// read subsequent bibtex values that are delimited with a #-character.
468         /// Concatenate all parts and replace names with the associated string in
469         /// the variable strings.
470         /// @return true if reading was successfull (all single parts were delimited
471         /// correctly)
472         bool readValue(docstring & val, idocfstream & ifs, const VarMap & strings) {
473
474                 char_type ch;
475
476                 val.clear();
477
478                 if (!ifs)
479                         return false;
480
481                 do {
482                         // skip whitespace
483                         do {
484                                 ifs.get(ch);
485                         } while (ifs && isSpace(ch));
486
487                         if (!ifs)
488                                 return false;
489
490                         // check for field type
491                         if (isDigit(ch)) {
492
493                                 // read integer value
494                                 do {
495                                         val += ch;
496                                         ifs.get(ch);
497                                 } while (ifs && isDigit(ch));
498
499                                 if (!ifs)
500                                         return false;
501
502                         } else if (ch == '"' || ch == '{') {
503                                 // set end delimiter
504                                 char_type delim = ch == '"' ? '"': '}';
505
506                                 //Skip whitespace
507                                 do {
508                                         ifs.get(ch);
509                                 } while (ifs && isSpace(ch));
510                                 
511                                 if (!ifs)
512                                         return false;
513                                 
514                                 //We now have the first non-whitespace character
515                                 //We'll collapse adjacent whitespace.
516                                 bool lastWasWhiteSpace = false;
517                                 
518                                 // inside this delimited text braces must match.
519                                 // Thus we can have a closing delimiter only
520                                 // when nestLevel == 0
521                                 int nestLevel = 0;
522  
523                                 while (ifs && (nestLevel > 0 || ch != delim)) {
524                                         if (isSpace(ch)) {
525                                                 lastWasWhiteSpace = true;
526                                                 ifs.get(ch);
527                                                 continue;
528                                         }
529                                         //We output the space only after we stop getting 
530                                         //whitespace so as not to output any whitespace
531                                         //at the end of the value.
532                                         if (lastWasWhiteSpace) {
533                                                 lastWasWhiteSpace = false;
534                                                 val += ' ';
535                                         }
536                                         
537                                         val += ch;
538
539                                         // update nesting level
540                                         switch (ch) {
541                                                 case '{':
542                                                         ++nestLevel;
543                                                         break;
544                                                 case '}':
545                                                         --nestLevel;
546                                                         if (nestLevel < 0) return false;
547                                                         break;
548                                         }
549
550                                         ifs.get(ch);
551                                 }
552
553                                 if (!ifs)
554                                         return false;
555
556                                 ifs.get(ch);
557
558                                 if (!ifs)
559                                         return false;
560
561                         } else {
562
563                                 // reading a string name
564                                 docstring strName;
565
566                                 while (ifs && !isSpace(ch) && ch != '#' && ch != ',' && ch != '}' && ch != ')') {
567                                         strName += lowercase(ch);
568                                         ifs.get(ch);
569                                 }
570
571                                 if (!ifs)
572                                         return false;
573
574                                 // replace the string with its assigned value or
575                                 // discard it if it's not assigned
576                                 if (strName.length()) {
577                                         VarMap::const_iterator pos = strings.find(strName);
578                                         if (pos != strings.end()) {
579                                                 val += pos->second;
580                                         }
581                                 }
582                         }
583
584                         // skip WS
585                         while (ifs && isSpace(ch)) {
586                                 ifs.get(ch);
587                         }
588
589                         if (!ifs)
590                                 return false;
591
592                         // continue reading next value on concatenate with '#'
593                 } while (ch == '#');
594
595                 ifs.putback(ch);
596
597                 return true;
598         }
599 }
600
601
602 // This method returns a comma separated list of Bibtex entries
603 void InsetBibtex::fillWithBibKeys(Buffer const & buffer,
604                 BiblioInfo & keylist, InsetIterator const & /*di*/) const
605 {
606         FileNameList const files = getFiles(buffer);
607         for (vector<FileName>::const_iterator it = files.begin();
608              it != files.end(); ++ it) {
609                 // This bibtex parser is a first step to parse bibtex files
610                 // more precisely.
611                 //
612                 // - it reads the whole bibtex entry and does a syntax check
613                 //   (matching delimiters, missing commas,...
614                 // - it recovers from errors starting with the next @-character
615                 // - it reads @string definitions and replaces them in the
616                 //   field values.
617                 // - it accepts more characters in keys or value names than
618                 //   bibtex does.
619                 //
620                 // Officially bibtex does only support ASCII, but in practice
621                 // you can use the encoding of the main document as long as
622                 // some elements like keys and names are pure ASCII. Therefore
623                 // we convert the file from the buffer encoding.
624                 // We don't restrict keys to ASCII in LyX, since our own
625                 // InsetBibitem can generate non-ASCII keys, and nonstandard
626                 // 8bit clean bibtex forks exist.
627                 
628                 idocfstream ifs(it->toFilesystemEncoding().c_str(),
629                         std::ios_base::in,
630                         buffer.params().encoding().iconvName());
631
632                 char_type ch;
633                 VarMap strings;
634
635                 while (ifs) {
636
637                         ifs.get(ch);
638                         if (!ifs)
639                                 break;
640
641                         if (ch != '@')
642                                 continue;
643
644                         docstring entryType;
645
646                         if (!readTypeOrKey(entryType, ifs, from_ascii("{("), 
647                                            docstring(), makeLowerCase) || !ifs)
648                                 continue;
649
650                         if (entryType == from_ascii("comment")) {
651
652                                 ifs.ignore(std::numeric_limits<int>::max(), '\n');
653                                 continue;
654                         }
655
656                         ifs.get(ch);
657                         if (!ifs)
658                                 break;
659
660                         if ((ch != '(') && (ch != '{')) {
661                                 // invalid entry delimiter
662                                 ifs.putback(ch);
663                                 continue;
664                         }
665
666                         // process the entry
667                         if (entryType == from_ascii("string")) {
668
669                                 // read string and add it to the strings map
670                                 // (or replace it's old value)
671                                 docstring name;
672                                 docstring value;
673
674                                 if (!readTypeOrKey(name, ifs, from_ascii("="), 
675                                                    from_ascii("#{}(),"), makeLowerCase) || !ifs)
676                                         continue;
677
678                                 // next char must be an equal sign
679                                 ifs.get(ch);
680                                 if (!ifs || ch != '=')
681                                         continue;
682
683                                 if (!readValue(value, ifs, strings))
684                                         continue;
685
686                                 strings[name] = value;
687
688                         } else if (entryType == from_ascii("preamble")) {
689
690                                 // preamble definitions are discarded.
691                                 // can they be of any use in lyx?
692                                 docstring value;
693
694                                 if (!readValue(value, ifs, strings))
695                                         continue;
696
697                         } else {
698
699                                 // Citation entry. Try to read the key.
700                                 docstring key;
701
702                                 if (!readTypeOrKey(key, ifs, from_ascii(","), 
703                                                    from_ascii("}"), keepCase) || !ifs)
704                                         continue;
705
706                                 /////////////////////////////////////////////
707                                 // now we have a key, so we will add an entry 
708                                 // (even if it's empty, as bibtex does)
709                                 //
710                                 // we now read the field = value pairs.
711                                 // all items must be separated by a comma. If
712                                 // it is missing the scanning of this entry is
713                                 // stopped and the next is searched.
714                                 docstring fields;
715                                 docstring name;
716                                 docstring value;
717                                 docstring commaNewline;
718                                 docstring data;
719                                 BibTeXInfo keyvalmap;
720                                 keyvalmap.entryType = entryType;
721                                 
722                                 bool readNext = removeWSAndComma(ifs);
723  
724                                 while (ifs && readNext) {
725
726                                         // read field name
727                                         if (!readTypeOrKey(name, ifs, from_ascii("="), 
728                                                            from_ascii("{}(),"), makeLowerCase) || !ifs)
729                                                 break;
730
731                                         // next char must be an equal sign
732                                         ifs.get(ch);
733                                         if (!ifs)
734                                                 break;
735                                         if (ch != '=') {
736                                                 ifs.putback(ch);
737                                                 break;
738                                         }
739
740                                         // read field value
741                                         if (!readValue(value, ifs, strings))
742                                                 break;
743
744                                         keyvalmap[name] = value;
745                                         data += "\n\n" + value;
746                                         keylist.fieldNames.insert(name);
747                                         readNext = removeWSAndComma(ifs);
748                                 }
749
750                                 // add the new entry
751                                 keylist.entryTypes.insert(entryType);
752                                 keyvalmap.allData = data;
753                                 keyvalmap.isBibTeX = true;
754                                 keyvalmap.bibKey = key;
755                                 keylist[key] = keyvalmap;
756                         }
757                 } //< searching '@'
758         } //< for loop over files
759 }
760
761
762
763 bool InsetBibtex::addDatabase(string const & db)
764 {
765         // FIXME UNICODE
766         string bibfiles(to_utf8(getParam("bibfiles")));
767         if (tokenPos(bibfiles, ',', db) == -1) {
768                 if (!bibfiles.empty())
769                         bibfiles += ',';
770                 setParam("bibfiles", from_utf8(bibfiles + db));
771                 return true;
772         }
773         return false;
774 }
775
776
777 bool InsetBibtex::delDatabase(string const & db)
778 {
779         // FIXME UNICODE
780         string bibfiles(to_utf8(getParam("bibfiles")));
781         if (contains(bibfiles, db)) {
782                 int const n = tokenPos(bibfiles, ',', db);
783                 string bd = db;
784                 if (n > 0) {
785                         // this is not the first database
786                         string tmp = ',' + bd;
787                         setParam("bibfiles", from_utf8(subst(bibfiles, tmp, string())));
788                 } else if (n == 0)
789                         // this is the first (or only) database
790                         setParam("bibfiles", from_utf8(split(bibfiles, bd, ',')));
791                 else
792                         return false;
793         }
794         return true;
795 }
796
797
798 void InsetBibtex::validate(LaTeXFeatures & features) const
799 {
800         if (features.bufferParams().use_bibtopic)
801                 features.require("bibtopic");
802 }
803
804
805 } // namespace lyx