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