]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
* GuiPrefs: fix typo.
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
29 #include "Encoding.h"
30 #include "ErrorList.h"
31 #include "Exporter.h"
32 #include "Format.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "InsetIterator.h"
36 #include "InsetList.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "LaTeX.h"
40 #include "Layout.h"
41 #include "Lexer.h"
42 #include "LyXAction.h"
43 #include "LyX.h"
44 #include "LyXRC.h"
45 #include "LyXVC.h"
46 #include "output_docbook.h"
47 #include "output.h"
48 #include "output_latex.h"
49 #include "output_plaintext.h"
50 #include "paragraph_funcs.h"
51 #include "Paragraph.h"
52 #include "ParagraphParameters.h"
53 #include "ParIterator.h"
54 #include "PDFOptions.h"
55 #include "SpellChecker.h"
56 #include "sgml.h"
57 #include "TexRow.h"
58 #include "TexStream.h"
59 #include "Text.h"
60 #include "TextClass.h"
61 #include "TocBackend.h"
62 #include "Undo.h"
63 #include "VCBackend.h"
64 #include "version.h"
65 #include "WordLangTuple.h"
66 #include "WordList.h"
67
68 #include "insets/InsetBibitem.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetInclude.h"
71 #include "insets/InsetText.h"
72
73 #include "mathed/MacroTable.h"
74 #include "mathed/MathMacroTemplate.h"
75 #include "mathed/MathSupport.h"
76
77 #include "frontends/alert.h"
78 #include "frontends/Delegates.h"
79 #include "frontends/WorkAreaManager.h"
80
81 #include "graphics/Previews.h"
82
83 #include "support/lassert.h"
84 #include "support/convert.h"
85 #include "support/debug.h"
86 #include "support/docstring_list.h"
87 #include "support/ExceptionMessage.h"
88 #include "support/FileName.h"
89 #include "support/FileNameList.h"
90 #include "support/filetools.h"
91 #include "support/ForkedCalls.h"
92 #include "support/gettext.h"
93 #include "support/gzstream.h"
94 #include "support/lstrings.h"
95 #include "support/lyxalgo.h"
96 #include "support/os.h"
97 #include "support/Package.h"
98 #include "support/Path.h"
99 #include "support/Systemcall.h"
100 #include "support/textutils.h"
101 #include "support/types.h"
102
103 #include <boost/bind.hpp>
104 #include <boost/shared_ptr.hpp>
105
106 #include <algorithm>
107 #include <fstream>
108 #include <iomanip>
109 #include <map>
110 #include <set>
111 #include <sstream>
112 #include <stack>
113 #include <vector>
114
115 using namespace std;
116 using namespace lyx::support;
117
118 namespace lyx {
119
120 namespace Alert = frontend::Alert;
121 namespace os = support::os;
122
123 namespace {
124
125 // Do not remove the comment below, so we get merge conflict in
126 // independent branches. Instead add your own.
127 int const LYX_FORMAT = 351;  // uwestoehr: support for page background color
128
129 typedef map<string, bool> DepClean;
130 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
131
132 void showPrintError(string const & name)
133 {
134         docstring str = bformat(_("Could not print the document %1$s.\n"
135                                             "Check that your printer is set up correctly."),
136                              makeDisplayPath(name, 50));
137         Alert::error(_("Print document failed"), str);
138 }
139
140 } // namespace anon
141
142 class BufferSet : public std::set<Buffer const *> {};
143
144 class Buffer::Impl
145 {
146 public:
147         Impl(Buffer & parent, FileName const & file, bool readonly);
148
149         ~Impl()
150         {
151                 if (wa_) {
152                         wa_->closeAll();
153                         delete wa_;
154                 }
155                 delete inset;
156         }
157
158         BufferParams params;
159         LyXVC lyxvc;
160         FileName temppath;
161         mutable TexRow texrow;
162
163         /// need to regenerate .tex?
164         DepClean dep_clean;
165
166         /// is save needed?
167         mutable bool lyx_clean;
168
169         /// is autosave needed?
170         mutable bool bak_clean;
171
172         /// is this a unnamed file (New...)?
173         bool unnamed;
174
175         /// buffer is r/o
176         bool read_only;
177
178         /// name of the file the buffer is associated with.
179         FileName filename;
180
181         /** Set to true only when the file is fully loaded.
182          *  Used to prevent the premature generation of previews
183          *  and by the citation inset.
184          */
185         bool file_fully_loaded;
186
187         ///
188         mutable TocBackend toc_backend;
189
190         /// macro tables
191         typedef pair<DocIterator, MacroData> ScopeMacro;
192         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
193         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
194         /// map from the macro name to the position map,
195         /// which maps the macro definition position to the scope and the MacroData.
196         NamePositionScopeMacroMap macros;
197         bool macro_lock;
198
199         /// positions of child buffers in the buffer
200         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
201         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
202         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
203         /// position of children buffers in this buffer
204         BufferPositionMap children_positions;
205         /// map from children inclusion positions to their scope and their buffer
206         PositionScopeBufferMap position_to_children;
207
208         /// Container for all sort of Buffer dependant errors.
209         map<string, ErrorList> errorLists;
210
211         /// timestamp and checksum used to test if the file has been externally
212         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
213         time_t timestamp_;
214         unsigned long checksum_;
215
216         ///
217         frontend::WorkAreaManager * wa_;
218
219         ///
220         Undo undo_;
221
222         /// A cache for the bibfiles (including bibfiles of loaded child
223         /// documents), needed for appropriate update of natbib labels.
224         mutable support::FileNameList bibfilesCache_;
225
226         // FIXME The caching mechanism could be improved. At present, we have a
227         // cache for each Buffer, that caches all the bibliography info for that
228         // Buffer. A more efficient solution would be to have a global cache per
229         // file, and then to construct the Buffer's bibinfo from that.
230         /// A cache for bibliography info
231         mutable BiblioInfo bibinfo_;
232         /// whether the bibinfo cache is valid
233         bool bibinfoCacheValid_;
234         /// Cache of timestamps of .bib files
235         map<FileName, time_t> bibfileStatus_;
236
237         mutable RefCache ref_cache_;
238
239         /// our Text that should be wrapped in an InsetText
240         InsetText * inset;
241
242         /// This is here to force the test to be done whenever parent_buffer
243         /// is accessed.
244         Buffer const * parent() const { 
245                 // if parent_buffer is not loaded, then it has been unloaded,
246                 // which means that parent_buffer is an invalid pointer. So we
247                 // set it to null in that case.
248                 if (!theBufferList().isLoaded(parent_buffer))
249                         parent_buffer = 0;
250                 return parent_buffer; 
251         }
252         ///
253         void setParent(Buffer const * pb) { parent_buffer = pb; }
254 private:
255         /// So we can force access via the accessors.
256         mutable Buffer const * parent_buffer;
257 };
258
259
260 /// Creates the per buffer temporary directory
261 static FileName createBufferTmpDir()
262 {
263         static int count;
264         // We are in our own directory.  Why bother to mangle name?
265         // In fact I wrote this code to circumvent a problematic behaviour
266         // (bug?) of EMX mkstemp().
267         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
268                 convert<string>(count++));
269
270         if (!tmpfl.createDirectory(0777)) {
271                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
272                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
273                         from_utf8(tmpfl.absFilename())));
274         }
275         return tmpfl;
276 }
277
278
279 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
280         : lyx_clean(true), bak_clean(true), unnamed(false),
281           read_only(readonly_), filename(file), file_fully_loaded(false),
282           toc_backend(&parent), macro_lock(false), timestamp_(0),
283           checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
284           parent_buffer(0)
285 {
286         temppath = createBufferTmpDir();
287         lyxvc.setBuffer(&parent);
288         if (use_gui)
289                 wa_ = new frontend::WorkAreaManager;
290 }
291
292
293 Buffer::Buffer(string const & file, bool readonly)
294         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
295 {
296         LYXERR(Debug::INFO, "Buffer::Buffer()");
297
298         d->inset = new InsetText(*this);
299         d->inset->setAutoBreakRows(true);
300         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
301 }
302
303
304 Buffer::~Buffer()
305 {
306         LYXERR(Debug::INFO, "Buffer::~Buffer()");
307         // here the buffer should take care that it is
308         // saved properly, before it goes into the void.
309
310         // GuiView already destroyed
311         gui_ = 0;
312
313         if (d->unnamed && d->filename.extension() == "internal") {
314                 // No need to do additional cleanups for internal buffer.
315                 delete d;
316                 return;
317         }
318
319         // loop over children
320         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
321         Impl::BufferPositionMap::iterator end = d->children_positions.end();
322         for (; it != end; ++it) {
323                 Buffer * child = const_cast<Buffer *>(it->first);
324                 // The child buffer might have been closed already.
325                 if (theBufferList().isLoaded(child))
326                         theBufferList().releaseChild(this, child);
327         }
328
329         // clear references to children in macro tables
330         d->children_positions.clear();
331         d->position_to_children.clear();
332
333         if (!d->temppath.destroyDirectory()) {
334                 Alert::warning(_("Could not remove temporary directory"),
335                         bformat(_("Could not remove the temporary directory %1$s"),
336                         from_utf8(d->temppath.absFilename())));
337         }
338
339         // Remove any previewed LaTeX snippets associated with this buffer.
340         thePreviews().removeLoader(*this);
341
342         delete d;
343 }
344
345
346 void Buffer::changed() const
347 {
348         if (d->wa_)
349                 d->wa_->redrawAll();
350 }
351
352
353 frontend::WorkAreaManager & Buffer::workAreaManager() const
354 {
355         LASSERT(d->wa_, /**/);
356         return *d->wa_;
357 }
358
359
360 Text & Buffer::text() const
361 {
362         return d->inset->text();
363 }
364
365
366 Inset & Buffer::inset() const
367 {
368         return *d->inset;
369 }
370
371
372 BufferParams & Buffer::params()
373 {
374         return d->params;
375 }
376
377
378 BufferParams const & Buffer::params() const
379 {
380         return d->params;
381 }
382
383
384 ParagraphList & Buffer::paragraphs()
385 {
386         return text().paragraphs();
387 }
388
389
390 ParagraphList const & Buffer::paragraphs() const
391 {
392         return text().paragraphs();
393 }
394
395
396 LyXVC & Buffer::lyxvc()
397 {
398         return d->lyxvc;
399 }
400
401
402 LyXVC const & Buffer::lyxvc() const
403 {
404         return d->lyxvc;
405 }
406
407
408 string const Buffer::temppath() const
409 {
410         return d->temppath.absFilename();
411 }
412
413
414 TexRow & Buffer::texrow()
415 {
416         return d->texrow;
417 }
418
419
420 TexRow const & Buffer::texrow() const
421 {
422         return d->texrow;
423 }
424
425
426 TocBackend & Buffer::tocBackend() const
427 {
428         return d->toc_backend;
429 }
430
431
432 Undo & Buffer::undo()
433 {
434         return d->undo_;
435 }
436
437
438 string Buffer::latexName(bool const no_path) const
439 {
440         FileName latex_name = makeLatexName(d->filename);
441         return no_path ? latex_name.onlyFileName()
442                 : latex_name.absFilename();
443 }
444
445
446 string Buffer::logName(LogType * type) const
447 {
448         string const filename = latexName(false);
449
450         if (filename.empty()) {
451                 if (type)
452                         *type = latexlog;
453                 return string();
454         }
455
456         string const path = temppath();
457
458         FileName const fname(addName(temppath(),
459                                      onlyFilename(changeExtension(filename,
460                                                                   ".log"))));
461         FileName const bname(
462                 addName(path, onlyFilename(
463                         changeExtension(filename,
464                                         formats.extension("literate") + ".out"))));
465
466         // If no Latex log or Build log is newer, show Build log
467
468         if (bname.exists() &&
469             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
470                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
471                 if (type)
472                         *type = buildlog;
473                 return bname.absFilename();
474         }
475         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
476         if (type)
477                         *type = latexlog;
478         return fname.absFilename();
479 }
480
481
482 void Buffer::setReadonly(bool const flag)
483 {
484         if (d->read_only != flag) {
485                 d->read_only = flag;
486                 setReadOnly(flag);
487         }
488 }
489
490
491 void Buffer::setFileName(string const & newfile)
492 {
493         d->filename = makeAbsPath(newfile);
494         setReadonly(d->filename.isReadOnly());
495         updateTitles();
496 }
497
498
499 int Buffer::readHeader(Lexer & lex)
500 {
501         int unknown_tokens = 0;
502         int line = -1;
503         int begin_header_line = -1;
504
505         // Initialize parameters that may be/go lacking in header:
506         params().branchlist().clear();
507         params().preamble.erase();
508         params().options.erase();
509         params().master.erase();
510         params().float_placement.erase();
511         params().paperwidth.erase();
512         params().paperheight.erase();
513         params().leftmargin.erase();
514         params().rightmargin.erase();
515         params().topmargin.erase();
516         params().bottommargin.erase();
517         params().headheight.erase();
518         params().headsep.erase();
519         params().footskip.erase();
520         params().columnsep.erase();
521         params().fontsCJK.erase();
522         params().listings_params.clear();
523         params().clearLayoutModules();
524         params().clearRemovedModules();
525         params().pdfoptions().clear();
526
527         for (int i = 0; i < 4; ++i) {
528                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
529                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
530         }
531
532         ErrorList & errorList = d->errorLists["Parse"];
533
534         while (lex.isOK()) {
535                 string token;
536                 lex >> token;
537
538                 if (token.empty())
539                         continue;
540
541                 if (token == "\\end_header")
542                         break;
543
544                 ++line;
545                 if (token == "\\begin_header") {
546                         begin_header_line = line;
547                         continue;
548                 }
549
550                 LYXERR(Debug::PARSER, "Handling document header token: `"
551                                       << token << '\'');
552
553                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
554                 if (!unknown.empty()) {
555                         if (unknown[0] != '\\' && token == "\\textclass") {
556                                 Alert::warning(_("Unknown document class"),
557                        bformat(_("Using the default document class, because the "
558                                               "class %1$s is unknown."), from_utf8(unknown)));
559                         } else {
560                                 ++unknown_tokens;
561                                 docstring const s = bformat(_("Unknown token: "
562                                                                         "%1$s %2$s\n"),
563                                                          from_utf8(token),
564                                                          lex.getDocString());
565                                 errorList.push_back(ErrorItem(_("Document header error"),
566                                         s, -1, 0, 0));
567                         }
568                 }
569         }
570         if (begin_header_line) {
571                 docstring const s = _("\\begin_header is missing");
572                 errorList.push_back(ErrorItem(_("Document header error"),
573                         s, -1, 0, 0));
574         }
575
576         params().makeDocumentClass();
577
578         return unknown_tokens;
579 }
580
581
582 // Uwe C. Schroeder
583 // changed to be public and have one parameter
584 // Returns true if "\end_document" is not read (Asger)
585 bool Buffer::readDocument(Lexer & lex)
586 {
587         ErrorList & errorList = d->errorLists["Parse"];
588         errorList.clear();
589
590         if (!lex.checkFor("\\begin_document")) {
591                 docstring const s = _("\\begin_document is missing");
592                 errorList.push_back(ErrorItem(_("Document header error"),
593                         s, -1, 0, 0));
594         }
595
596         // we are reading in a brand new document
597         LASSERT(paragraphs().empty(), /**/);
598
599         readHeader(lex);
600
601         if (params().outputChanges) {
602                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
603                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
604                                   LaTeXFeatures::isAvailable("xcolor");
605
606                 if (!dvipost && !xcolorulem) {
607                         Alert::warning(_("Changes not shown in LaTeX output"),
608                                        _("Changes will not be highlighted in LaTeX output, "
609                                          "because neither dvipost nor xcolor/ulem are installed.\n"
610                                          "Please install these packages or redefine "
611                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
612                 } else if (!xcolorulem) {
613                         Alert::warning(_("Changes not shown in LaTeX output"),
614                                        _("Changes will not be highlighted in LaTeX output "
615                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
616                                          "Please install both packages or redefine "
617                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
618                 }
619         }
620
621         if (!params().master.empty()) {
622                 FileName const master_file = makeAbsPath(params().master,
623                            onlyPath(absFileName()));
624                 if (isLyXFilename(master_file.absFilename())) {
625                         Buffer * master = 
626                                 checkAndLoadLyXFile(master_file, true);
627                         if (master) {
628                                 // necessary e.g. after a reload
629                                 // to re-register the child (bug 5873)
630                                 // FIXME: clean up updateMacros (here, only
631                                 // child registering is needed).
632                                 master->updateMacros();
633                                 // set master as master buffer, but only
634                                 // if we are a real child
635                                 if (master->isChild(this))
636                                         setParent(master);
637                                 // if the master is not fully loaded
638                                 // it is probably just loading this
639                                 // child. No warning needed then.
640                                 else if (master->isFullyLoaded())
641                                         LYXERR0("The master '"
642                                                 << params().master
643                                                 << "' assigned to this document ("
644                                                 << absFileName()
645                                                 << ") does not include "
646                                                 "this document. Ignoring the master assignment.");
647                         }
648                 }
649         }
650
651         // read main text
652         bool const res = text().read(*this, lex, errorList, d->inset);
653
654         updateMacros();
655         updateMacroInstances();
656         return res;
657 }
658
659
660 // needed to insert the selection
661 void Buffer::insertStringAsLines(ParagraphList & pars,
662         pit_type & pit, pos_type & pos,
663         Font const & fn, docstring const & str, bool autobreakrows)
664 {
665         Font font = fn;
666
667         // insert the string, don't insert doublespace
668         bool space_inserted = true;
669         for (docstring::const_iterator cit = str.begin();
670             cit != str.end(); ++cit) {
671                 Paragraph & par = pars[pit];
672                 if (*cit == '\n') {
673                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
674                                 breakParagraph(params(), pars, pit, pos,
675                                                par.layout().isEnvironment());
676                                 ++pit;
677                                 pos = 0;
678                                 space_inserted = true;
679                         } else {
680                                 continue;
681                         }
682                         // do not insert consecutive spaces if !free_spacing
683                 } else if ((*cit == ' ' || *cit == '\t') &&
684                            space_inserted && !par.isFreeSpacing()) {
685                         continue;
686                 } else if (*cit == '\t') {
687                         if (!par.isFreeSpacing()) {
688                                 // tabs are like spaces here
689                                 par.insertChar(pos, ' ', font, params().trackChanges);
690                                 ++pos;
691                                 space_inserted = true;
692                         } else {
693                                 par.insertChar(pos, *cit, font, params().trackChanges);
694                                 ++pos;
695                                 space_inserted = true;
696                         }
697                 } else if (!isPrintable(*cit)) {
698                         // Ignore unprintables
699                         continue;
700                 } else {
701                         // just insert the character
702                         par.insertChar(pos, *cit, font, params().trackChanges);
703                         ++pos;
704                         space_inserted = (*cit == ' ');
705                 }
706
707         }
708 }
709
710
711 bool Buffer::readString(string const & s)
712 {
713         params().compressed = false;
714
715         // remove dummy empty par
716         paragraphs().clear();
717         Lexer lex;
718         istringstream is(s);
719         lex.setStream(is);
720         FileName const name = FileName::tempName("Buffer_readString");
721         switch (readFile(lex, name, true)) {
722         case failure:
723                 return false;
724         case wrongversion: {
725                 // We need to call lyx2lyx, so write the input to a file
726                 ofstream os(name.toFilesystemEncoding().c_str());
727                 os << s;
728                 os.close();
729                 return readFile(name);
730         }
731         case success:
732                 break;
733         }
734
735         return true;
736 }
737
738
739 bool Buffer::readFile(FileName const & filename)
740 {
741         FileName fname(filename);
742
743         params().compressed = fname.isZippedFile();
744
745         // remove dummy empty par
746         paragraphs().clear();
747         Lexer lex;
748         lex.setFile(fname);
749         if (readFile(lex, fname) != success)
750                 return false;
751
752         return true;
753 }
754
755
756 bool Buffer::isFullyLoaded() const
757 {
758         return d->file_fully_loaded;
759 }
760
761
762 void Buffer::setFullyLoaded(bool value)
763 {
764         d->file_fully_loaded = value;
765 }
766
767
768 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
769                 bool fromstring)
770 {
771         LASSERT(!filename.empty(), /**/);
772
773         // the first (non-comment) token _must_ be...
774         if (!lex.checkFor("\\lyxformat")) {
775                 Alert::error(_("Document format failure"),
776                              bformat(_("%1$s is not a readable LyX document."),
777                                        from_utf8(filename.absFilename())));
778                 return failure;
779         }
780
781         string tmp_format;
782         lex >> tmp_format;
783         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
784         // if present remove ".," from string.
785         size_t dot = tmp_format.find_first_of(".,");
786         //lyxerr << "           dot found at " << dot << endl;
787         if (dot != string::npos)
788                         tmp_format.erase(dot, 1);
789         int const file_format = convert<int>(tmp_format);
790         //lyxerr << "format: " << file_format << endl;
791
792         // save timestamp and checksum of the original disk file, making sure
793         // to not overwrite them with those of the file created in the tempdir
794         // when it has to be converted to the current format.
795         if (!d->checksum_) {
796                 // Save the timestamp and checksum of disk file. If filename is an
797                 // emergency file, save the timestamp and checksum of the original lyx file
798                 // because isExternallyModified will check for this file. (BUG4193)
799                 string diskfile = filename.absFilename();
800                 if (suffixIs(diskfile, ".emergency"))
801                         diskfile = diskfile.substr(0, diskfile.size() - 10);
802                 saveCheckSum(FileName(diskfile));
803         }
804
805         if (file_format != LYX_FORMAT) {
806
807                 if (fromstring)
808                         // lyx2lyx would fail
809                         return wrongversion;
810
811                 FileName const tmpfile = FileName::tempName("Buffer_readFile");
812                 if (tmpfile.empty()) {
813                         Alert::error(_("Conversion failed"),
814                                      bformat(_("%1$s is from a different"
815                                               " version of LyX, but a temporary"
816                                               " file for converting it could"
817                                               " not be created."),
818                                               from_utf8(filename.absFilename())));
819                         return failure;
820                 }
821                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
822                 if (lyx2lyx.empty()) {
823                         Alert::error(_("Conversion script not found"),
824                                      bformat(_("%1$s is from a different"
825                                                " version of LyX, but the"
826                                                " conversion script lyx2lyx"
827                                                " could not be found."),
828                                                from_utf8(filename.absFilename())));
829                         return failure;
830                 }
831                 ostringstream command;
832                 command << os::python()
833                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
834                         << " -t " << convert<string>(LYX_FORMAT)
835                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
836                         << ' ' << quoteName(filename.toFilesystemEncoding());
837                 string const command_str = command.str();
838
839                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
840
841                 cmd_ret const ret = runCommand(command_str);
842                 if (ret.first != 0) {
843                         Alert::error(_("Conversion script failed"),
844                                      bformat(_("%1$s is from a different version"
845                                               " of LyX, but the lyx2lyx script"
846                                               " failed to convert it."),
847                                               from_utf8(filename.absFilename())));
848                         return failure;
849                 } else {
850                         bool const ret = readFile(tmpfile);
851                         // Do stuff with tmpfile name and buffer name here.
852                         return ret ? success : failure;
853                 }
854
855         }
856
857         if (readDocument(lex)) {
858                 Alert::error(_("Document format failure"),
859                              bformat(_("%1$s ended unexpectedly, which means"
860                                                     " that it is probably corrupted."),
861                                        from_utf8(filename.absFilename())));
862         }
863
864         d->file_fully_loaded = true;
865         return success;
866 }
867
868
869 // Should probably be moved to somewhere else: BufferView? LyXView?
870 bool Buffer::save() const
871 {
872         // We don't need autosaves in the immediate future. (Asger)
873         resetAutosaveTimers();
874
875         string const encodedFilename = d->filename.toFilesystemEncoding();
876
877         FileName backupName;
878         bool madeBackup = false;
879
880         // make a backup if the file already exists
881         if (lyxrc.make_backup && fileName().exists()) {
882                 backupName = FileName(absFileName() + '~');
883                 if (!lyxrc.backupdir_path.empty()) {
884                         string const mangledName =
885                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
886                         backupName = FileName(addName(lyxrc.backupdir_path,
887                                                       mangledName));
888                 }
889                 if (fileName().copyTo(backupName)) {
890                         madeBackup = true;
891                 } else {
892                         Alert::error(_("Backup failure"),
893                                      bformat(_("Cannot create backup file %1$s.\n"
894                                                "Please check whether the directory exists and is writeable."),
895                                              from_utf8(backupName.absFilename())));
896                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
897                 }
898         }
899
900         // ask if the disk file has been externally modified (use checksum method)
901         if (fileName().exists() && isExternallyModified(checksum_method)) {
902                 docstring const file = makeDisplayPath(absFileName(), 20);
903                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
904                                                              "you want to overwrite this file?"), file);
905                 int const ret = Alert::prompt(_("Overwrite modified file?"),
906                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
907                 if (ret == 1)
908                         return false;
909         }
910
911         if (writeFile(d->filename)) {
912                 markClean();
913                 return true;
914         } else {
915                 // Saving failed, so backup is not backup
916                 if (madeBackup)
917                         backupName.moveTo(d->filename);
918                 return false;
919         }
920 }
921
922
923 bool Buffer::writeFile(FileName const & fname) const
924 {
925         if (d->read_only && fname == d->filename)
926                 return false;
927
928         bool retval = false;
929
930         docstring const str = bformat(_("Saving document %1$s..."),
931                 makeDisplayPath(fname.absFilename()));
932         message(str);
933
934         if (params().compressed) {
935                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
936                 retval = ofs && write(ofs);
937         } else {
938                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
939                 retval = ofs && write(ofs);
940         }
941
942         if (!retval) {
943                 message(str + _(" could not write file!"));
944                 return false;
945         }
946
947         removeAutosaveFile();
948
949         saveCheckSum(d->filename);
950         message(str + _(" done."));
951
952         return true;
953 }
954
955
956 bool Buffer::write(ostream & ofs) const
957 {
958 #ifdef HAVE_LOCALE
959         // Use the standard "C" locale for file output.
960         ofs.imbue(locale::classic());
961 #endif
962
963         // The top of the file should not be written by params().
964
965         // write out a comment in the top of the file
966         ofs << "#LyX " << lyx_version
967             << " created this file. For more info see http://www.lyx.org/\n"
968             << "\\lyxformat " << LYX_FORMAT << "\n"
969             << "\\begin_document\n";
970
971         /// For each author, set 'used' to true if there is a change
972         /// by this author in the document; otherwise set it to 'false'.
973         AuthorList::Authors::const_iterator a_it = params().authors().begin();
974         AuthorList::Authors::const_iterator a_end = params().authors().end();
975         for (; a_it != a_end; ++a_it)
976                 a_it->second.setUsed(false);
977
978         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
979         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
980         for ( ; it != end; ++it)
981                 it->checkAuthors(params().authors());
982
983         // now write out the buffer parameters.
984         ofs << "\\begin_header\n";
985         params().writeFile(ofs);
986         ofs << "\\end_header\n";
987
988         // write the text
989         ofs << "\n\\begin_body\n";
990         text().write(*this, ofs);
991         ofs << "\n\\end_body\n";
992
993         // Write marker that shows file is complete
994         ofs << "\\end_document" << endl;
995
996         // Shouldn't really be needed....
997         //ofs.close();
998
999         // how to check if close went ok?
1000         // Following is an attempt... (BE 20001011)
1001
1002         // good() returns false if any error occured, including some
1003         //        formatting error.
1004         // bad()  returns true if something bad happened in the buffer,
1005         //        which should include file system full errors.
1006
1007         bool status = true;
1008         if (!ofs) {
1009                 status = false;
1010                 lyxerr << "File was not closed properly." << endl;
1011         }
1012
1013         return status;
1014 }
1015
1016
1017 bool Buffer::makeLaTeXFile(FileName const & fname,
1018                            string const & original_path,
1019                            OutputParams const & runparams_in,
1020                            bool output_preamble, bool output_body) const
1021 {
1022         OutputParams runparams = runparams_in;
1023         if (params().useXetex)
1024                 runparams.flavor = OutputParams::XETEX;
1025
1026         string const encoding = runparams.encoding->iconvName();
1027         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1028
1029         ofdocstream ofs;
1030         try { ofs.reset(encoding); }
1031         catch (iconv_codecvt_facet_exception & e) {
1032                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1033                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1034                         "verify that the support software for your encoding (%1$s) is "
1035                         "properly installed"), from_ascii(encoding)));
1036                 return false;
1037         }
1038         if (!openFileWrite(ofs, fname))
1039                 return false;
1040
1041         //TexStream ts(ofs.rdbuf(), &texrow());
1042         ErrorList & errorList = d->errorLists["Export"];
1043         errorList.clear();
1044         bool failed_export = false;
1045         try {
1046                 d->texrow.reset();
1047                 writeLaTeXSource(ofs, original_path,
1048                       runparams, output_preamble, output_body);
1049         }
1050         catch (EncodingException & e) {
1051                 odocstringstream ods;
1052                 ods.put(e.failed_char);
1053                 ostringstream oss;
1054                 oss << "0x" << hex << e.failed_char << dec;
1055                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1056                                           " (code point %2$s)"),
1057                                           ods.str(), from_utf8(oss.str()));
1058                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1059                                 "representable in the chosen encoding.\n"
1060                                 "Changing the document encoding to utf8 could help."),
1061                                 e.par_id, e.pos, e.pos + 1));
1062                 failed_export = true;
1063         }
1064         catch (iconv_codecvt_facet_exception & e) {
1065                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1066                         _(e.what()), -1, 0, 0));
1067                 failed_export = true;
1068         }
1069         catch (exception const & e) {
1070                 errorList.push_back(ErrorItem(_("conversion failed"),
1071                         _(e.what()), -1, 0, 0));
1072                 failed_export = true;
1073         }
1074         catch (...) {
1075                 lyxerr << "Caught some really weird exception..." << endl;
1076                 lyx_exit(1);
1077         }
1078
1079         ofs.close();
1080         if (ofs.fail()) {
1081                 failed_export = true;
1082                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1083         }
1084
1085         errors("Export");
1086         return !failed_export;
1087 }
1088
1089
1090 void Buffer::writeLaTeXSource(odocstream & os,
1091                            string const & original_path,
1092                            OutputParams const & runparams_in,
1093                            bool const output_preamble, bool const output_body) const
1094 {
1095         // The child documents, if any, shall be already loaded at this point.
1096
1097         OutputParams runparams = runparams_in;
1098
1099         // Classify the unicode characters appearing in math insets
1100         Encodings::initUnicodeMath(*this);
1101
1102         // validate the buffer.
1103         LYXERR(Debug::LATEX, "  Validating buffer...");
1104         LaTeXFeatures features(*this, params(), runparams);
1105         validate(features);
1106         LYXERR(Debug::LATEX, "  Buffer validation done.");
1107
1108         // The starting paragraph of the coming rows is the
1109         // first paragraph of the document. (Asger)
1110         if (output_preamble && runparams.nice) {
1111                 os << "%% LyX " << lyx_version << " created this file.  "
1112                         "For more info, see http://www.lyx.org/.\n"
1113                         "%% Do not edit unless you really know what "
1114                         "you are doing.\n";
1115                 d->texrow.newline();
1116                 d->texrow.newline();
1117         }
1118         LYXERR(Debug::INFO, "lyx document header finished");
1119
1120         // Don't move this behind the parent_buffer=0 code below,
1121         // because then the macros will not get the right "redefinition"
1122         // flag as they don't see the parent macros which are output before.
1123         updateMacros();
1124
1125         // fold macros if possible, still with parent buffer as the
1126         // macros will be put in the prefix anyway.
1127         updateMacroInstances();
1128
1129         // There are a few differences between nice LaTeX and usual files:
1130         // usual is \batchmode and has a
1131         // special input@path to allow the including of figures
1132         // with either \input or \includegraphics (what figinsets do).
1133         // input@path is set when the actual parameter
1134         // original_path is set. This is done for usual tex-file, but not
1135         // for nice-latex-file. (Matthias 250696)
1136         // Note that input@path is only needed for something the user does
1137         // in the preamble, included .tex files or ERT, files included by
1138         // LyX work without it.
1139         if (output_preamble) {
1140                 if (!runparams.nice) {
1141                         // code for usual, NOT nice-latex-file
1142                         os << "\\batchmode\n"; // changed
1143                         // from \nonstopmode
1144                         d->texrow.newline();
1145                 }
1146                 if (!original_path.empty()) {
1147                         // FIXME UNICODE
1148                         // We don't know the encoding of inputpath
1149                         docstring const inputpath = from_utf8(latex_path(original_path));
1150                         os << "\\makeatletter\n"
1151                            << "\\def\\input@path{{"
1152                            << inputpath << "/}}\n"
1153                            << "\\makeatother\n";
1154                         d->texrow.newline();
1155                         d->texrow.newline();
1156                         d->texrow.newline();
1157                 }
1158
1159                 // get parent macros (if this buffer has a parent) which will be
1160                 // written at the document begin further down.
1161                 MacroSet parentMacros;
1162                 listParentMacros(parentMacros, features);
1163
1164                 // Write the preamble
1165                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1166
1167                 runparams.use_japanese = features.isRequired("japanese");
1168
1169                 if (!output_body)
1170                         return;
1171
1172                 // make the body.
1173                 os << "\\begin{document}\n";
1174                 d->texrow.newline();
1175
1176                 // output the parent macros
1177                 MacroSet::iterator it = parentMacros.begin();
1178                 MacroSet::iterator end = parentMacros.end();
1179                 for (; it != end; ++it)
1180                         (*it)->write(os, true);
1181         } // output_preamble
1182
1183         d->texrow.start(paragraphs().begin()->id(), 0);
1184
1185         LYXERR(Debug::INFO, "preamble finished, now the body.");
1186
1187         // if we are doing a real file with body, even if this is the
1188         // child of some other buffer, let's cut the link here.
1189         // This happens for example if only a child document is printed.
1190         Buffer const * save_parent = 0;
1191         if (output_preamble) {
1192                 save_parent = d->parent();
1193                 d->setParent(0);
1194         }
1195
1196         // the real stuff
1197         latexParagraphs(*this, text(), os, d->texrow, runparams);
1198
1199         // Restore the parenthood if needed
1200         if (output_preamble)
1201                 d->setParent(save_parent);
1202
1203         // add this just in case after all the paragraphs
1204         os << endl;
1205         d->texrow.newline();
1206
1207         if (output_preamble) {
1208                 os << "\\end{document}\n";
1209                 d->texrow.newline();
1210                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1211         } else {
1212                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1213         }
1214         runparams_in.encoding = runparams.encoding;
1215
1216         // Just to be sure. (Asger)
1217         d->texrow.newline();
1218
1219         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1220         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1221 }
1222
1223
1224 bool Buffer::isLatex() const
1225 {
1226         return params().documentClass().outputType() == LATEX;
1227 }
1228
1229
1230 bool Buffer::isLiterate() const
1231 {
1232         return params().documentClass().outputType() == LITERATE;
1233 }
1234
1235
1236 bool Buffer::isDocBook() const
1237 {
1238         return params().documentClass().outputType() == DOCBOOK;
1239 }
1240
1241
1242 void Buffer::makeDocBookFile(FileName const & fname,
1243                               OutputParams const & runparams,
1244                               bool const body_only) const
1245 {
1246         LYXERR(Debug::LATEX, "makeDocBookFile...");
1247
1248         ofdocstream ofs;
1249         if (!openFileWrite(ofs, fname))
1250                 return;
1251
1252         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1253
1254         ofs.close();
1255         if (ofs.fail())
1256                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1257 }
1258
1259
1260 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1261                              OutputParams const & runparams,
1262                              bool const only_body) const
1263 {
1264         LaTeXFeatures features(*this, params(), runparams);
1265         validate(features);
1266
1267         d->texrow.reset();
1268
1269         DocumentClass const & tclass = params().documentClass();
1270         string const top_element = tclass.latexname();
1271
1272         if (!only_body) {
1273                 if (runparams.flavor == OutputParams::XML)
1274                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1275
1276                 // FIXME UNICODE
1277                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1278
1279                 // FIXME UNICODE
1280                 if (! tclass.class_header().empty())
1281                         os << from_ascii(tclass.class_header());
1282                 else if (runparams.flavor == OutputParams::XML)
1283                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1284                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1285                 else
1286                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1287
1288                 docstring preamble = from_utf8(params().preamble);
1289                 if (runparams.flavor != OutputParams::XML ) {
1290                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1291                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1292                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1293                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1294                 }
1295
1296                 string const name = runparams.nice
1297                         ? changeExtension(absFileName(), ".sgml") : fname;
1298                 preamble += features.getIncludedFiles(name);
1299                 preamble += features.getLyXSGMLEntities();
1300
1301                 if (!preamble.empty()) {
1302                         os << "\n [ " << preamble << " ]";
1303                 }
1304                 os << ">\n\n";
1305         }
1306
1307         string top = top_element;
1308         top += " lang=\"";
1309         if (runparams.flavor == OutputParams::XML)
1310                 top += params().language->code();
1311         else
1312                 top += params().language->code().substr(0, 2);
1313         top += '"';
1314
1315         if (!params().options.empty()) {
1316                 top += ' ';
1317                 top += params().options;
1318         }
1319
1320         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1321             << " file was created by LyX " << lyx_version
1322             << "\n  See http://www.lyx.org/ for more information -->\n";
1323
1324         params().documentClass().counters().reset();
1325
1326         updateMacros();
1327
1328         sgml::openTag(os, top);
1329         os << '\n';
1330         docbookParagraphs(paragraphs(), *this, os, runparams);
1331         sgml::closeTag(os, top_element);
1332 }
1333
1334
1335 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1336 // Other flags: -wall -v0 -x
1337 int Buffer::runChktex()
1338 {
1339         setBusy(true);
1340
1341         // get LaTeX-Filename
1342         FileName const path(temppath());
1343         string const name = addName(path.absFilename(), latexName());
1344         string const org_path = filePath();
1345
1346         PathChanger p(path); // path to LaTeX file
1347         message(_("Running chktex..."));
1348
1349         // Generate the LaTeX file if neccessary
1350         OutputParams runparams(&params().encoding());
1351         runparams.flavor = OutputParams::LATEX;
1352         runparams.nice = false;
1353         makeLaTeXFile(FileName(name), org_path, runparams);
1354
1355         TeXErrors terr;
1356         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1357         int const res = chktex.run(terr); // run chktex
1358
1359         if (res == -1) {
1360                 Alert::error(_("chktex failure"),
1361                              _("Could not run chktex successfully."));
1362         } else if (res > 0) {
1363                 ErrorList & errlist = d->errorLists["ChkTeX"];
1364                 errlist.clear();
1365                 bufferErrors(terr, errlist);
1366         }
1367
1368         setBusy(false);
1369
1370         errors("ChkTeX");
1371
1372         return res;
1373 }
1374
1375
1376 void Buffer::validate(LaTeXFeatures & features) const
1377 {
1378         params().validate(features);
1379
1380         updateMacros();
1381
1382         for_each(paragraphs().begin(), paragraphs().end(),
1383                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1384
1385         if (lyxerr.debugging(Debug::LATEX)) {
1386                 features.showStruct();
1387         }
1388 }
1389
1390
1391 void Buffer::getLabelList(vector<docstring> & list) const
1392 {
1393         // If this is a child document, use the parent's list instead.
1394         Buffer const * const pbuf = d->parent();
1395         if (pbuf) {
1396                 pbuf->getLabelList(list);
1397                 return;
1398         }
1399
1400         list.clear();
1401         Toc & toc = d->toc_backend.toc("label");
1402         TocIterator toc_it = toc.begin();
1403         TocIterator end = toc.end();
1404         for (; toc_it != end; ++toc_it) {
1405                 if (toc_it->depth() == 0)
1406                         list.push_back(toc_it->str());
1407         }
1408 }
1409
1410
1411 void Buffer::updateBibfilesCache(UpdateScope scope) const
1412 {
1413         // If this is a child document, use the parent's cache instead.
1414         Buffer const * const pbuf = d->parent();
1415         if (pbuf && scope != UpdateChildOnly) {
1416                 pbuf->updateBibfilesCache();
1417                 return;
1418         }
1419
1420         d->bibfilesCache_.clear();
1421         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1422                 if (it->lyxCode() == BIBTEX_CODE) {
1423                         InsetBibtex const & inset =
1424                                 static_cast<InsetBibtex const &>(*it);
1425                         support::FileNameList const bibfiles = inset.getBibFiles();
1426                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1427                                 bibfiles.begin(),
1428                                 bibfiles.end());
1429                 } else if (it->lyxCode() == INCLUDE_CODE) {
1430                         InsetInclude & inset =
1431                                 static_cast<InsetInclude &>(*it);
1432                         inset.updateBibfilesCache();
1433                         support::FileNameList const & bibfiles =
1434                                         inset.getBibfilesCache();
1435                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1436                                 bibfiles.begin(),
1437                                 bibfiles.end());
1438                 }
1439         }
1440         // the bibinfo cache is now invalid
1441         d->bibinfoCacheValid_ = false;
1442 }
1443
1444
1445 void Buffer::invalidateBibinfoCache()
1446 {
1447         d->bibinfoCacheValid_ = false;
1448 }
1449
1450
1451 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1452 {
1453         // If this is a child document, use the parent's cache instead.
1454         Buffer const * const pbuf = d->parent();
1455         if (pbuf && scope != UpdateChildOnly)
1456                 return pbuf->getBibfilesCache();
1457
1458         // We update the cache when first used instead of at loading time.
1459         if (d->bibfilesCache_.empty())
1460                 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1461
1462         return d->bibfilesCache_;
1463 }
1464
1465
1466 BiblioInfo const & Buffer::masterBibInfo() const
1467 {
1468         // if this is a child document and the parent is already loaded
1469         // use the parent's list instead  [ale990412]
1470         Buffer const * const tmp = masterBuffer();
1471         LASSERT(tmp, /**/);
1472         if (tmp != this)
1473                 return tmp->masterBibInfo();
1474         return localBibInfo();
1475 }
1476
1477
1478 BiblioInfo const & Buffer::localBibInfo() const
1479 {
1480         if (d->bibinfoCacheValid_) {
1481                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1482                 // compare the cached timestamps with the actual ones.
1483                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1484                 support::FileNameList::const_iterator en = bibfilesCache.end();
1485                 for (; ei != en; ++ ei) {
1486                         time_t lastw = ei->lastModified();
1487                         if (lastw != d->bibfileStatus_[*ei]) {
1488                                 d->bibinfoCacheValid_ = false;
1489                                 d->bibfileStatus_[*ei] = lastw;
1490                                 break;
1491                         }
1492                 }
1493         }
1494
1495         if (!d->bibinfoCacheValid_) {
1496                 d->bibinfo_.clear();
1497                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1498                         it->fillWithBibKeys(d->bibinfo_, it);
1499                 d->bibinfoCacheValid_ = true;
1500         }
1501         return d->bibinfo_;
1502 }
1503
1504
1505 bool Buffer::isDepClean(string const & name) const
1506 {
1507         DepClean::const_iterator const it = d->dep_clean.find(name);
1508         if (it == d->dep_clean.end())
1509                 return true;
1510         return it->second;
1511 }
1512
1513
1514 void Buffer::markDepClean(string const & name)
1515 {
1516         d->dep_clean[name] = true;
1517 }
1518
1519
1520 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1521 {
1522         switch (cmd.action) {
1523                 case LFUN_BUFFER_EXPORT: {
1524                         docstring const arg = cmd.argument();
1525                         bool enable = arg == "custom" || isExportable(to_utf8(arg));
1526                         if (!enable)
1527                                 flag.message(bformat(
1528                                         _("Don't know how to export to format: %1$s"), arg));
1529                         flag.setEnabled(enable);
1530                         break;
1531                 }
1532
1533                 case LFUN_BRANCH_ACTIVATE: 
1534                 case LFUN_BRANCH_DEACTIVATE: {
1535                 BranchList const & branchList = params().branchlist();
1536                 docstring const branchName = cmd.argument();
1537                 flag.setEnabled(!branchName.empty()
1538                                 && branchList.find(branchName));
1539                         break;
1540                 }
1541
1542                 case LFUN_BUFFER_PRINT:
1543                         // if no Buffer is present, then of course we won't be called!
1544                         flag.setEnabled(true);
1545                         break;
1546
1547                 default:
1548                         return false;
1549         }
1550         return true;
1551 }
1552
1553
1554 void Buffer::dispatch(string const & command, DispatchResult & result)
1555 {
1556         return dispatch(lyxaction.lookupFunc(command), result);
1557 }
1558
1559
1560 // NOTE We can end up here even if we have no GUI, because we are called
1561 // by LyX::exec to handled command-line requests. So we may need to check 
1562 // whether we have a GUI or not. The boolean use_gui holds this information.
1563 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1564 {
1565         // We'll set this back to false if need be.
1566         bool dispatched = true;
1567
1568         switch (func.action) {
1569                 case LFUN_BUFFER_EXPORT: {
1570                         bool success = doExport(to_utf8(func.argument()), false);
1571                         dr.setError(success);
1572                         if (!success)
1573                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1574                                                       func.argument()));
1575                         break;
1576                 }
1577
1578                 case LFUN_BRANCH_ACTIVATE:
1579                 case LFUN_BRANCH_DEACTIVATE: {
1580                         BranchList & branchList = params().branchlist();
1581                         docstring const branchName = func.argument();
1582                         // the case without a branch name is handled elsewhere
1583                         if (branchName.empty()) {
1584                                 dispatched = false;
1585                                 break;
1586                         }
1587                         Branch * branch = branchList.find(branchName);
1588                         if (!branch) {
1589                                 LYXERR0("Branch " << branchName << " does not exist.");
1590                                 dr.setError(true);
1591                                 docstring const msg = 
1592                                         bformat(_("Branch \"%1$s\" does not exist."), branchName);
1593                                 dr.setMessage(msg);
1594                         } else {
1595                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1596                                 dr.setError(false);
1597                                 dr.update(Update::Force);
1598                         }
1599                         break;
1600                 }
1601
1602                 case LFUN_BUFFER_PRINT: {
1603                         // we'll assume there's a problem until we succeed
1604                         dr.setError(true); 
1605                         string target = func.getArg(0);
1606                         string target_name = func.getArg(1);
1607                         string command = func.getArg(2);
1608
1609                         if (target.empty()
1610                             || target_name.empty()
1611                             || command.empty()) {
1612                                 LYXERR0("Unable to parse " << func.argument());
1613                                 docstring const msg = 
1614                                         bformat(_("Unable to parse \"%1$s\""), func.argument());
1615                                 dr.setMessage(msg);
1616                                 break;
1617                         }
1618                         if (target != "printer" && target != "file") {
1619                                 LYXERR0("Unrecognized target \"" << target << '"');
1620                                 docstring const msg = 
1621                                         bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1622                                 dr.setMessage(msg);
1623                                 break;
1624                         }
1625
1626                         if (!doExport("dvi", true)) {
1627                                 showPrintError(absFileName());
1628                                 dr.setMessage(_("Error exporting to DVI."));
1629                                 break;
1630                         }
1631
1632                         // Push directory path.
1633                         string const path = temppath();
1634                         // Prevent the compiler from optimizing away p
1635                         FileName pp(path);
1636                         PathChanger p(pp);
1637
1638                         // there are three cases here:
1639                         // 1. we print to a file
1640                         // 2. we print directly to a printer
1641                         // 3. we print using a spool command (print to file first)
1642                         Systemcall one;
1643                         int res = 0;
1644                         string const dviname = changeExtension(latexName(true), "dvi");
1645
1646                         if (target == "printer") {
1647                                 if (!lyxrc.print_spool_command.empty()) {
1648                                         // case 3: print using a spool
1649                                         string const psname = changeExtension(dviname,".ps");
1650                                         command += ' ' + lyxrc.print_to_file
1651                                                 + quoteName(psname)
1652                                                 + ' '
1653                                                 + quoteName(dviname);
1654
1655                                         string command2 = lyxrc.print_spool_command + ' ';
1656                                         if (target_name != "default") {
1657                                                 command2 += lyxrc.print_spool_printerprefix
1658                                                         + target_name
1659                                                         + ' ';
1660                                         }
1661                                         command2 += quoteName(psname);
1662                                         // First run dvips.
1663                                         // If successful, then spool command
1664                                         res = one.startscript(Systemcall::Wait, command);
1665
1666                                         if (res == 0) {
1667                                                 // If there's no GUI, we have to wait on this command. Otherwise,
1668                                                 // LyX deletes the temporary directory, and with it the spooled
1669                                                 // file, before it can be printed!!
1670                                                 Systemcall::Starttype stype = use_gui ?
1671                                                         Systemcall::DontWait : Systemcall::Wait;
1672                                                 res = one.startscript(stype, command2);
1673                                         }
1674                                 } else {
1675                                         // case 2: print directly to a printer
1676                                         if (target_name != "default")
1677                                                 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1678                                         // as above....
1679                                         Systemcall::Starttype stype = use_gui ?
1680                                                 Systemcall::DontWait : Systemcall::Wait;
1681                                         res = one.startscript(stype, command + quoteName(dviname));
1682                                 }
1683
1684                         } else {
1685                                 // case 1: print to a file
1686                                 FileName const filename(makeAbsPath(target_name, filePath()));
1687                                 FileName const dvifile(makeAbsPath(dviname, path));
1688                                 if (filename.exists()) {
1689                                         docstring text = bformat(
1690                                                 _("The file %1$s already exists.\n\n"
1691                                                   "Do you want to overwrite that file?"),
1692                                                 makeDisplayPath(filename.absFilename()));
1693                                         if (Alert::prompt(_("Overwrite file?"),
1694                                             text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1695                                                 break;
1696                                 }
1697                                 command += ' ' + lyxrc.print_to_file
1698                                         + quoteName(filename.toFilesystemEncoding())
1699                                         + ' '
1700                                         + quoteName(dvifile.toFilesystemEncoding());
1701                                 // as above....
1702                                 Systemcall::Starttype stype = use_gui ?
1703                                         Systemcall::DontWait : Systemcall::Wait;
1704                                 res = one.startscript(stype, command);
1705                         }
1706
1707                         if (res == 0) 
1708                                 dr.setError(false);
1709                         else {
1710                                 dr.setMessage(_("Error running external commands."));
1711                                 showPrintError(absFileName());
1712                         }
1713                         break;
1714                 }
1715
1716                 default:
1717                         dispatched = false;
1718                         break;
1719         }
1720         dr.dispatched(dispatched);
1721 }
1722
1723
1724 void Buffer::changeLanguage(Language const * from, Language const * to)
1725 {
1726         LASSERT(from, /**/);
1727         LASSERT(to, /**/);
1728
1729         for_each(par_iterator_begin(),
1730                  par_iterator_end(),
1731                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1732 }
1733
1734
1735 bool Buffer::isMultiLingual() const
1736 {
1737         ParConstIterator end = par_iterator_end();
1738         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1739                 if (it->isMultiLingual(params()))
1740                         return true;
1741
1742         return false;
1743 }
1744
1745
1746 DocIterator Buffer::getParFromID(int const id) const
1747 {
1748         Buffer * buf = const_cast<Buffer *>(this);
1749         if (id < 0) {
1750                 // John says this is called with id == -1 from undo
1751                 lyxerr << "getParFromID(), id: " << id << endl;
1752                 return doc_iterator_end(buf);
1753         }
1754
1755         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1756                 if (it.paragraph().id() == id)
1757                         return it;
1758
1759         return doc_iterator_end(buf);
1760 }
1761
1762
1763 bool Buffer::hasParWithID(int const id) const
1764 {
1765         return !getParFromID(id).atEnd();
1766 }
1767
1768
1769 ParIterator Buffer::par_iterator_begin()
1770 {
1771         return ParIterator(doc_iterator_begin(this));
1772 }
1773
1774
1775 ParIterator Buffer::par_iterator_end()
1776 {
1777         return ParIterator(doc_iterator_end(this));
1778 }
1779
1780
1781 ParConstIterator Buffer::par_iterator_begin() const
1782 {
1783         return ParConstIterator(doc_iterator_begin(this));
1784 }
1785
1786
1787 ParConstIterator Buffer::par_iterator_end() const
1788 {
1789         return ParConstIterator(doc_iterator_end(this));
1790 }
1791
1792
1793 Language const * Buffer::language() const
1794 {
1795         return params().language;
1796 }
1797
1798
1799 docstring const Buffer::B_(string const & l10n) const
1800 {
1801         return params().B_(l10n);
1802 }
1803
1804
1805 bool Buffer::isClean() const
1806 {
1807         return d->lyx_clean;
1808 }
1809
1810
1811 bool Buffer::isBakClean() const
1812 {
1813         return d->bak_clean;
1814 }
1815
1816
1817 bool Buffer::isExternallyModified(CheckMethod method) const
1818 {
1819         LASSERT(d->filename.exists(), /**/);
1820         // if method == timestamp, check timestamp before checksum
1821         return (method == checksum_method
1822                 || d->timestamp_ != d->filename.lastModified())
1823                 && d->checksum_ != d->filename.checksum();
1824 }
1825
1826
1827 void Buffer::saveCheckSum(FileName const & file) const
1828 {
1829         if (file.exists()) {
1830                 d->timestamp_ = file.lastModified();
1831                 d->checksum_ = file.checksum();
1832         } else {
1833                 // in the case of save to a new file.
1834                 d->timestamp_ = 0;
1835                 d->checksum_ = 0;
1836         }
1837 }
1838
1839
1840 void Buffer::markClean() const
1841 {
1842         if (!d->lyx_clean) {
1843                 d->lyx_clean = true;
1844                 updateTitles();
1845         }
1846         // if the .lyx file has been saved, we don't need an
1847         // autosave
1848         d->bak_clean = true;
1849 }
1850
1851
1852 void Buffer::markBakClean() const
1853 {
1854         d->bak_clean = true;
1855 }
1856
1857
1858 void Buffer::setUnnamed(bool flag)
1859 {
1860         d->unnamed = flag;
1861 }
1862
1863
1864 bool Buffer::isUnnamed() const
1865 {
1866         return d->unnamed;
1867 }
1868
1869
1870 // FIXME: this function should be moved to buffer_pimpl.C
1871 void Buffer::markDirty()
1872 {
1873         if (d->lyx_clean) {
1874                 d->lyx_clean = false;
1875                 updateTitles();
1876         }
1877         d->bak_clean = false;
1878
1879         DepClean::iterator it = d->dep_clean.begin();
1880         DepClean::const_iterator const end = d->dep_clean.end();
1881
1882         for (; it != end; ++it)
1883                 it->second = false;
1884 }
1885
1886
1887 FileName Buffer::fileName() const
1888 {
1889         return d->filename;
1890 }
1891
1892
1893 string Buffer::absFileName() const
1894 {
1895         return d->filename.absFilename();
1896 }
1897
1898
1899 string Buffer::filePath() const
1900 {
1901         return d->filename.onlyPath().absFilename() + "/";
1902 }
1903
1904
1905 bool Buffer::isReadonly() const
1906 {
1907         return d->read_only;
1908 }
1909
1910
1911 void Buffer::setParent(Buffer const * buffer)
1912 {
1913         // Avoids recursive include.
1914         d->setParent(buffer == this ? 0 : buffer);
1915         updateMacros();
1916 }
1917
1918
1919 Buffer const * Buffer::parent() const
1920 {
1921         return d->parent();
1922 }
1923
1924
1925 void Buffer::collectRelatives(BufferSet & bufs) const
1926 {
1927         bufs.insert(this);
1928         if (parent())
1929                 parent()->collectRelatives(bufs);
1930
1931         // loop over children
1932         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1933         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1934         for (; it != end; ++it)
1935                 bufs.insert(const_cast<Buffer *>(it->first));
1936 }
1937
1938
1939 std::vector<Buffer const *> Buffer::allRelatives() const
1940 {
1941         BufferSet bufs;
1942         collectRelatives(bufs);
1943         BufferSet::iterator it = bufs.begin();
1944         std::vector<Buffer const *> ret;
1945         for (; it != bufs.end(); ++it)
1946                 ret.push_back(*it);
1947         return ret;
1948 }
1949
1950
1951 Buffer const * Buffer::masterBuffer() const
1952 {
1953         Buffer const * const pbuf = d->parent();
1954         if (!pbuf)
1955                 return this;
1956
1957         return pbuf->masterBuffer();
1958 }
1959
1960
1961 bool Buffer::isChild(Buffer * child) const
1962 {
1963         return d->children_positions.find(child) != d->children_positions.end();
1964 }
1965
1966
1967 DocIterator Buffer::firstChildPosition(Buffer const * child)
1968 {
1969         Impl::BufferPositionMap::iterator it;
1970         it = d->children_positions.find(child);
1971         if (it == d->children_positions.end())
1972                 return DocIterator(this);
1973         return it->second;
1974 }
1975
1976
1977 std::vector<Buffer *> Buffer::getChildren() const
1978 {
1979         std::vector<Buffer *> clist;
1980         // loop over children
1981         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1982         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1983         for (; it != end; ++it) {
1984                 Buffer * child = const_cast<Buffer *>(it->first);
1985                 clist.push_back(child);
1986                 // there might be grandchildren
1987                 std::vector<Buffer *> glist = child->getChildren();
1988                 for (vector<Buffer *>::const_iterator git = glist.begin();
1989                      git != glist.end(); ++git)
1990                         clist.push_back(*git);
1991         }
1992         return clist;
1993 }
1994
1995
1996 template<typename M>
1997 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1998 {
1999         if (m.empty())
2000                 return m.end();
2001
2002         typename M::iterator it = m.lower_bound(x);
2003         if (it == m.begin())
2004                 return m.end();
2005
2006         it--;
2007         return it;
2008 }
2009
2010
2011 MacroData const * Buffer::getBufferMacro(docstring const & name,
2012                                          DocIterator const & pos) const
2013 {
2014         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2015
2016         // if paragraphs have no macro context set, pos will be empty
2017         if (pos.empty())
2018                 return 0;
2019
2020         // we haven't found anything yet
2021         DocIterator bestPos = par_iterator_begin();
2022         MacroData const * bestData = 0;
2023
2024         // find macro definitions for name
2025         Impl::NamePositionScopeMacroMap::iterator nameIt
2026                 = d->macros.find(name);
2027         if (nameIt != d->macros.end()) {
2028                 // find last definition in front of pos or at pos itself
2029                 Impl::PositionScopeMacroMap::const_iterator it
2030                         = greatest_below(nameIt->second, pos);
2031                 if (it != nameIt->second.end()) {
2032                         while (true) {
2033                                 // scope ends behind pos?
2034                                 if (pos < it->second.first) {
2035                                         // Looks good, remember this. If there
2036                                         // is no external macro behind this,
2037                                         // we found the right one already.
2038                                         bestPos = it->first;
2039                                         bestData = &it->second.second;
2040                                         break;
2041                                 }
2042
2043                                 // try previous macro if there is one
2044                                 if (it == nameIt->second.begin())
2045                                         break;
2046                                 it--;
2047                         }
2048                 }
2049         }
2050
2051         // find macros in included files
2052         Impl::PositionScopeBufferMap::const_iterator it
2053                 = greatest_below(d->position_to_children, pos);
2054         if (it == d->position_to_children.end())
2055                 // no children before
2056                 return bestData;
2057
2058         while (true) {
2059                 // do we know something better (i.e. later) already?
2060                 if (it->first < bestPos )
2061                         break;
2062
2063                 // scope ends behind pos?
2064                 if (pos < it->second.first) {
2065                         // look for macro in external file
2066                         d->macro_lock = true;
2067                         MacroData const * data
2068                         = it->second.second->getMacro(name, false);
2069                         d->macro_lock = false;
2070                         if (data) {
2071                                 bestPos = it->first;
2072                                 bestData = data;
2073                                 break;
2074                         }
2075                 }
2076
2077                 // try previous file if there is one
2078                 if (it == d->position_to_children.begin())
2079                         break;
2080                 --it;
2081         }
2082
2083         // return the best macro we have found
2084         return bestData;
2085 }
2086
2087
2088 MacroData const * Buffer::getMacro(docstring const & name,
2089         DocIterator const & pos, bool global) const
2090 {
2091         if (d->macro_lock)
2092                 return 0;
2093
2094         // query buffer macros
2095         MacroData const * data = getBufferMacro(name, pos);
2096         if (data != 0)
2097                 return data;
2098
2099         // If there is a master buffer, query that
2100         Buffer const * const pbuf = d->parent();
2101         if (pbuf) {
2102                 d->macro_lock = true;
2103                 MacroData const * macro = pbuf->getMacro(
2104                         name, *this, false);
2105                 d->macro_lock = false;
2106                 if (macro)
2107                         return macro;
2108         }
2109
2110         if (global) {
2111                 data = MacroTable::globalMacros().get(name);
2112                 if (data != 0)
2113                         return data;
2114         }
2115
2116         return 0;
2117 }
2118
2119
2120 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2121 {
2122         // set scope end behind the last paragraph
2123         DocIterator scope = par_iterator_begin();
2124         scope.pit() = scope.lastpit() + 1;
2125
2126         return getMacro(name, scope, global);
2127 }
2128
2129
2130 MacroData const * Buffer::getMacro(docstring const & name,
2131         Buffer const & child, bool global) const
2132 {
2133         // look where the child buffer is included first
2134         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2135         if (it == d->children_positions.end())
2136                 return 0;
2137
2138         // check for macros at the inclusion position
2139         return getMacro(name, it->second, global);
2140 }
2141
2142
2143 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2144 {
2145         pit_type lastpit = it.lastpit();
2146
2147         // look for macros in each paragraph
2148         while (it.pit() <= lastpit) {
2149                 Paragraph & par = it.paragraph();
2150
2151                 // iterate over the insets of the current paragraph
2152                 InsetList const & insets = par.insetList();
2153                 InsetList::const_iterator iit = insets.begin();
2154                 InsetList::const_iterator end = insets.end();
2155                 for (; iit != end; ++iit) {
2156                         it.pos() = iit->pos;
2157
2158                         // is it a nested text inset?
2159                         if (iit->inset->asInsetText()) {
2160                                 // Inset needs its own scope?
2161                                 InsetText const * itext = iit->inset->asInsetText();
2162                                 bool newScope = itext->isMacroScope();
2163
2164                                 // scope which ends just behind the inset
2165                                 DocIterator insetScope = it;
2166                                 ++insetScope.pos();
2167
2168                                 // collect macros in inset
2169                                 it.push_back(CursorSlice(*iit->inset));
2170                                 updateMacros(it, newScope ? insetScope : scope);
2171                                 it.pop_back();
2172                                 continue;
2173                         }
2174
2175                         // is it an external file?
2176                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2177                                 // get buffer of external file
2178                                 InsetInclude const & inset =
2179                                         static_cast<InsetInclude const &>(*iit->inset);
2180                                 d->macro_lock = true;
2181                                 Buffer * child = inset.getChildBuffer();
2182                                 d->macro_lock = false;
2183                                 if (!child)
2184                                         continue;
2185
2186                                 // register its position, but only when it is
2187                                 // included first in the buffer
2188                                 if (d->children_positions.find(child) ==
2189                                         d->children_positions.end())
2190                                                 d->children_positions[child] = it;
2191
2192                                 // register child with its scope
2193                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2194                                 continue;
2195                         }
2196
2197                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2198                                 continue;
2199
2200                         // get macro data
2201                         MathMacroTemplate & macroTemplate =
2202                                 static_cast<MathMacroTemplate &>(*iit->inset);
2203                         MacroContext mc(*this, it);
2204                         macroTemplate.updateToContext(mc);
2205
2206                         // valid?
2207                         bool valid = macroTemplate.validMacro();
2208                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2209                         // then the BufferView's cursor will be invalid in
2210                         // some cases which leads to crashes.
2211                         if (!valid)
2212                                 continue;
2213
2214                         // register macro
2215                         d->macros[macroTemplate.name()][it] =
2216                                 Impl::ScopeMacro(scope, MacroData(*this, it));
2217                 }
2218
2219                 // next paragraph
2220                 it.pit()++;
2221                 it.pos() = 0;
2222         }
2223 }
2224
2225
2226 void Buffer::updateMacros() const
2227 {
2228         if (d->macro_lock)
2229                 return;
2230
2231         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2232
2233         // start with empty table
2234         d->macros.clear();
2235         d->children_positions.clear();
2236         d->position_to_children.clear();
2237
2238         // Iterate over buffer, starting with first paragraph
2239         // The scope must be bigger than any lookup DocIterator
2240         // later. For the global lookup, lastpit+1 is used, hence
2241         // we use lastpit+2 here.
2242         DocIterator it = par_iterator_begin();
2243         DocIterator outerScope = it;
2244         outerScope.pit() = outerScope.lastpit() + 2;
2245         updateMacros(it, outerScope);
2246 }
2247
2248
2249 void Buffer::updateMacroInstances() const
2250 {
2251         LYXERR(Debug::MACROS, "updateMacroInstances for "
2252                 << d->filename.onlyFileName());
2253         DocIterator it = doc_iterator_begin(this);
2254         DocIterator end = doc_iterator_end(this);
2255         for (; it != end; it.forwardPos()) {
2256                 // look for MathData cells in InsetMathNest insets
2257                 Inset * inset = it.nextInset();
2258                 if (!inset)
2259                         continue;
2260
2261                 InsetMath * minset = inset->asInsetMath();
2262                 if (!minset)
2263                         continue;
2264
2265                 // update macro in all cells of the InsetMathNest
2266                 DocIterator::idx_type n = minset->nargs();
2267                 MacroContext mc = MacroContext(*this, it);
2268                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2269                         MathData & data = minset->cell(i);
2270                         data.updateMacros(0, mc);
2271                 }
2272         }
2273 }
2274
2275
2276 void Buffer::listMacroNames(MacroNameSet & macros) const
2277 {
2278         if (d->macro_lock)
2279                 return;
2280
2281         d->macro_lock = true;
2282
2283         // loop over macro names
2284         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2285         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2286         for (; nameIt != nameEnd; ++nameIt)
2287                 macros.insert(nameIt->first);
2288
2289         // loop over children
2290         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2291         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2292         for (; it != end; ++it)
2293                 it->first->listMacroNames(macros);
2294
2295         // call parent
2296         Buffer const * const pbuf = d->parent();
2297         if (pbuf)
2298                 pbuf->listMacroNames(macros);
2299
2300         d->macro_lock = false;
2301 }
2302
2303
2304 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2305 {
2306         Buffer const * const pbuf = d->parent();
2307         if (!pbuf)
2308                 return;
2309
2310         MacroNameSet names;
2311         pbuf->listMacroNames(names);
2312
2313         // resolve macros
2314         MacroNameSet::iterator it = names.begin();
2315         MacroNameSet::iterator end = names.end();
2316         for (; it != end; ++it) {
2317                 // defined?
2318                 MacroData const * data =
2319                 pbuf->getMacro(*it, *this, false);
2320                 if (data) {
2321                         macros.insert(data);
2322
2323                         // we cannot access the original MathMacroTemplate anymore
2324                         // here to calls validate method. So we do its work here manually.
2325                         // FIXME: somehow make the template accessible here.
2326                         if (data->optionals() > 0)
2327                                 features.require("xargs");
2328                 }
2329         }
2330 }
2331
2332
2333 Buffer::References & Buffer::references(docstring const & label)
2334 {
2335         if (d->parent())
2336                 return const_cast<Buffer *>(masterBuffer())->references(label);
2337
2338         RefCache::iterator it = d->ref_cache_.find(label);
2339         if (it != d->ref_cache_.end())
2340                 return it->second.second;
2341
2342         static InsetLabel const * dummy_il = 0;
2343         static References const dummy_refs;
2344         it = d->ref_cache_.insert(
2345                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2346         return it->second.second;
2347 }
2348
2349
2350 Buffer::References const & Buffer::references(docstring const & label) const
2351 {
2352         return const_cast<Buffer *>(this)->references(label);
2353 }
2354
2355
2356 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2357 {
2358         masterBuffer()->d->ref_cache_[label].first = il;
2359 }
2360
2361
2362 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2363 {
2364         return masterBuffer()->d->ref_cache_[label].first;
2365 }
2366
2367
2368 void Buffer::clearReferenceCache() const
2369 {
2370         if (!d->parent())
2371                 d->ref_cache_.clear();
2372 }
2373
2374
2375 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2376         InsetCode code)
2377 {
2378         //FIXME: This does not work for child documents yet.
2379         LASSERT(code == CITE_CODE, /**/);
2380         // Check if the label 'from' appears more than once
2381         vector<docstring> labels;
2382         string paramName;
2383         BiblioInfo const & keys = masterBibInfo();
2384         BiblioInfo::const_iterator bit  = keys.begin();
2385         BiblioInfo::const_iterator bend = keys.end();
2386
2387         for (; bit != bend; ++bit)
2388                 // FIXME UNICODE
2389                 labels.push_back(bit->first);
2390         paramName = "key";
2391
2392         if (count(labels.begin(), labels.end(), from) > 1)
2393                 return;
2394
2395         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2396                 if (it->lyxCode() == code) {
2397                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2398                         docstring const oldValue = inset.getParam(paramName);
2399                         if (oldValue == from)
2400                                 inset.setParam(paramName, to);
2401                 }
2402         }
2403 }
2404
2405
2406 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2407         pit_type par_end, bool full_source) const
2408 {
2409         OutputParams runparams(&params().encoding());
2410         runparams.nice = true;
2411         runparams.flavor = params().useXetex ? 
2412                 OutputParams::XETEX : OutputParams::LATEX;
2413         runparams.linelen = lyxrc.plaintext_linelen;
2414         // No side effect of file copying and image conversion
2415         runparams.dryrun = true;
2416
2417         d->texrow.reset();
2418         if (full_source) {
2419                 os << "% " << _("Preview source code") << "\n\n";
2420                 d->texrow.newline();
2421                 d->texrow.newline();
2422                 if (isDocBook())
2423                         writeDocBookSource(os, absFileName(), runparams, false);
2424                 else
2425                         // latex or literate
2426                         writeLaTeXSource(os, string(), runparams, true, true);
2427         } else {
2428                 runparams.par_begin = par_begin;
2429                 runparams.par_end = par_end;
2430                 if (par_begin + 1 == par_end) {
2431                         os << "% "
2432                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2433                            << "\n\n";
2434                 } else {
2435                         os << "% "
2436                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2437                                         convert<docstring>(par_begin),
2438                                         convert<docstring>(par_end - 1))
2439                            << "\n\n";
2440                 }
2441                 d->texrow.newline();
2442                 d->texrow.newline();
2443                 // output paragraphs
2444                 if (isDocBook())
2445                         docbookParagraphs(paragraphs(), *this, os, runparams);
2446                 else 
2447                         // latex or literate
2448                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2449         }
2450 }
2451
2452
2453 ErrorList & Buffer::errorList(string const & type) const
2454 {
2455         static ErrorList emptyErrorList;
2456         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2457         if (I == d->errorLists.end())
2458                 return emptyErrorList;
2459
2460         return I->second;
2461 }
2462
2463
2464 void Buffer::updateTocItem(std::string const & type,
2465         DocIterator const & dit) const
2466 {
2467         if (gui_)
2468                 gui_->updateTocItem(type, dit);
2469 }
2470
2471
2472 void Buffer::structureChanged() const
2473 {
2474         if (gui_)
2475                 gui_->structureChanged();
2476 }
2477
2478
2479 void Buffer::errors(string const & err) const
2480 {
2481         if (gui_)
2482                 gui_->errors(err);
2483 }
2484
2485
2486 void Buffer::message(docstring const & msg) const
2487 {
2488         if (gui_)
2489                 gui_->message(msg);
2490 }
2491
2492
2493 void Buffer::setBusy(bool on) const
2494 {
2495         if (gui_)
2496                 gui_->setBusy(on);
2497 }
2498
2499
2500 void Buffer::setReadOnly(bool on) const
2501 {
2502         if (d->wa_)
2503                 d->wa_->setReadOnly(on);
2504 }
2505
2506
2507 void Buffer::updateTitles() const
2508 {
2509         if (d->wa_)
2510                 d->wa_->updateTitles();
2511 }
2512
2513
2514 void Buffer::resetAutosaveTimers() const
2515 {
2516         if (gui_)
2517                 gui_->resetAutosaveTimers();
2518 }
2519
2520
2521 bool Buffer::hasGuiDelegate() const
2522 {
2523         return gui_;
2524 }
2525
2526
2527 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2528 {
2529         gui_ = gui;
2530 }
2531
2532
2533
2534 namespace {
2535
2536 class AutoSaveBuffer : public ForkedProcess {
2537 public:
2538         ///
2539         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2540                 : buffer_(buffer), fname_(fname) {}
2541         ///
2542         virtual boost::shared_ptr<ForkedProcess> clone() const
2543         {
2544                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2545         }
2546         ///
2547         int start()
2548         {
2549                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2550                                                  from_utf8(fname_.absFilename())));
2551                 return run(DontWait);
2552         }
2553 private:
2554         ///
2555         virtual int generateChild();
2556         ///
2557         Buffer const & buffer_;
2558         FileName fname_;
2559 };
2560
2561
2562 int AutoSaveBuffer::generateChild()
2563 {
2564         // tmp_ret will be located (usually) in /tmp
2565         // will that be a problem?
2566         // Note that this calls ForkedCalls::fork(), so it's
2567         // ok cross-platform.
2568         pid_t const pid = fork();
2569         // If you want to debug the autosave
2570         // you should set pid to -1, and comment out the fork.
2571         if (pid != 0 && pid != -1)
2572                 return pid;
2573
2574         // pid = -1 signifies that lyx was unable
2575         // to fork. But we will do the save
2576         // anyway.
2577         bool failed = false;
2578         FileName const tmp_ret = FileName::tempName("lyxauto");
2579         if (!tmp_ret.empty()) {
2580                 buffer_.writeFile(tmp_ret);
2581                 // assume successful write of tmp_ret
2582                 if (!tmp_ret.moveTo(fname_))
2583                         failed = true;
2584         } else
2585                 failed = true;
2586
2587         if (failed) {
2588                 // failed to write/rename tmp_ret so try writing direct
2589                 if (!buffer_.writeFile(fname_)) {
2590                         // It is dangerous to do this in the child,
2591                         // but safe in the parent, so...
2592                         if (pid == -1) // emit message signal.
2593                                 buffer_.message(_("Autosave failed!"));
2594                 }
2595         }
2596
2597         if (pid == 0) // we are the child so...
2598                 _exit(0);
2599
2600         return pid;
2601 }
2602
2603 } // namespace anon
2604
2605
2606 FileName Buffer::getAutosaveFilename() const
2607 {
2608         string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2609         string const fname = "#" + d->filename.onlyFileName() + "#";
2610         return makeAbsPath(fname, fpath);
2611 }
2612
2613
2614 void Buffer::removeAutosaveFile() const
2615 {
2616         FileName const f = getAutosaveFilename();
2617         if (f.exists())
2618                 f.removeFile();
2619 }
2620
2621
2622 // Perfect target for a thread...
2623 void Buffer::autoSave() const
2624 {
2625         if (isBakClean() || isReadonly()) {
2626                 // We don't save now, but we'll try again later
2627                 resetAutosaveTimers();
2628                 return;
2629         }
2630
2631         // emit message signal.
2632         message(_("Autosaving current document..."));
2633         AutoSaveBuffer autosave(*this, getAutosaveFilename());
2634         autosave.start();
2635
2636         markBakClean();
2637         resetAutosaveTimers();
2638 }
2639
2640
2641 string Buffer::bufferFormat() const
2642 {
2643         if (isDocBook())
2644                 return "docbook";
2645         if (isLiterate())
2646                 return "literate";
2647         if (params().useXetex)
2648                 return "xetex";
2649         if (params().encoding().package() == Encoding::japanese)
2650                 return "platex";
2651         return "latex";
2652 }
2653
2654
2655 string Buffer::getDefaultOutputFormat() const
2656 {
2657         if (!params().defaultOutputFormat.empty()
2658             && params().defaultOutputFormat != "default")
2659                 return params().defaultOutputFormat;
2660         typedef vector<Format const *> Formats;
2661         Formats formats = exportableFormats(true);
2662         if (isDocBook()
2663             || isLiterate()
2664             || params().useXetex
2665             || params().encoding().package() == Encoding::japanese) {
2666                 if (formats.empty())
2667                         return string();
2668                 // return the first we find
2669                 return formats.front()->name();
2670         }
2671         return lyxrc.default_view_format;
2672 }
2673
2674
2675
2676 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2677         string & result_file) const
2678 {
2679         string backend_format;
2680         OutputParams runparams(&params().encoding());
2681         runparams.flavor = OutputParams::LATEX;
2682         runparams.linelen = lyxrc.plaintext_linelen;
2683         vector<string> backs = backends();
2684         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2685                 // Get shortest path to format
2686                 Graph::EdgePath path;
2687                 for (vector<string>::const_iterator it = backs.begin();
2688                      it != backs.end(); ++it) {
2689                         Graph::EdgePath p = theConverters().getPath(*it, format);
2690                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2691                                 backend_format = *it;
2692                                 path = p;
2693                         }
2694                 }
2695                 if (!path.empty())
2696                         runparams.flavor = theConverters().getFlavor(path);
2697                 else {
2698                         Alert::error(_("Couldn't export file"),
2699                                 bformat(_("No information for exporting the format %1$s."),
2700                                    formats.prettyName(format)));
2701                         return false;
2702                 }
2703         } else {
2704                 backend_format = format;
2705                 // FIXME: Don't hardcode format names here, but use a flag
2706                 if (backend_format == "pdflatex")
2707                         runparams.flavor = OutputParams::PDFLATEX;
2708         }
2709
2710         string filename = latexName(false);
2711         filename = addName(temppath(), filename);
2712         filename = changeExtension(filename,
2713                                    formats.extension(backend_format));
2714
2715         // fix macros
2716         updateMacroInstances();
2717
2718         // Plain text backend
2719         if (backend_format == "text")
2720                 writePlaintextFile(*this, FileName(filename), runparams);
2721         // no backend
2722         else if (backend_format == "lyx")
2723                 writeFile(FileName(filename));
2724         // Docbook backend
2725         else if (isDocBook()) {
2726                 runparams.nice = !put_in_tempdir;
2727                 makeDocBookFile(FileName(filename), runparams);
2728         }
2729         // LaTeX backend
2730         else if (backend_format == format) {
2731                 runparams.nice = true;
2732                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2733                         return false;
2734         } else if (!lyxrc.tex_allows_spaces
2735                    && contains(filePath(), ' ')) {
2736                 Alert::error(_("File name error"),
2737                            _("The directory path to the document cannot contain spaces."));
2738                 return false;
2739         } else {
2740                 runparams.nice = false;
2741                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2742                         return false;
2743         }
2744
2745         string const error_type = (format == "program")
2746                 ? "Build" : bufferFormat();
2747         ErrorList & error_list = d->errorLists[error_type];
2748         string const ext = formats.extension(format);
2749         FileName const tmp_result_file(changeExtension(filename, ext));
2750         bool const success = theConverters().convert(this, FileName(filename),
2751                 tmp_result_file, FileName(absFileName()), backend_format, format,
2752                 error_list);
2753         // Emit the signal to show the error list.
2754         if (format != backend_format)
2755                 errors(error_type);
2756         if (!success)
2757                 return false;
2758
2759         if (put_in_tempdir) {
2760                 result_file = tmp_result_file.absFilename();
2761                 return true;
2762         }
2763
2764         result_file = changeExtension(absFileName(), ext);
2765         // We need to copy referenced files (e. g. included graphics
2766         // if format == "dvi") to the result dir.
2767         vector<ExportedFile> const files =
2768                 runparams.exportdata->externalFiles(format);
2769         string const dest = onlyPath(result_file);
2770         CopyStatus status = SUCCESS;
2771         for (vector<ExportedFile>::const_iterator it = files.begin();
2772                 it != files.end() && status != CANCEL; ++it) {
2773                 string const fmt = formats.getFormatFromFile(it->sourceName);
2774                 status = copyFile(fmt, it->sourceName,
2775                         makeAbsPath(it->exportName, dest),
2776                         it->exportName, status == FORCE);
2777         }
2778         if (status == CANCEL) {
2779                 message(_("Document export cancelled."));
2780         } else if (tmp_result_file.exists()) {
2781                 // Finally copy the main file
2782                 status = copyFile(format, tmp_result_file,
2783                         FileName(result_file), result_file,
2784                         status == FORCE);
2785                 message(bformat(_("Document exported as %1$s "
2786                         "to file `%2$s'"),
2787                         formats.prettyName(format),
2788                         makeDisplayPath(result_file)));
2789         } else {
2790                 // This must be a dummy converter like fax (bug 1888)
2791                 message(bformat(_("Document exported as %1$s"),
2792                         formats.prettyName(format)));
2793         }
2794
2795         return true;
2796 }
2797
2798
2799 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2800 {
2801         string result_file;
2802         return doExport(format, put_in_tempdir, result_file);
2803 }
2804
2805
2806 bool Buffer::preview(string const & format) const
2807 {
2808         string result_file;
2809         if (!doExport(format, true, result_file))
2810                 return false;
2811         return formats.view(*this, FileName(result_file), format);
2812 }
2813
2814
2815 bool Buffer::isExportable(string const & format) const
2816 {
2817         vector<string> backs = backends();
2818         for (vector<string>::const_iterator it = backs.begin();
2819              it != backs.end(); ++it)
2820                 if (theConverters().isReachable(*it, format))
2821                         return true;
2822         return false;
2823 }
2824
2825
2826 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2827 {
2828         vector<string> backs = backends();
2829         vector<Format const *> result =
2830                 theConverters().getReachable(backs[0], only_viewable, true);
2831         for (vector<string>::const_iterator it = backs.begin() + 1;
2832              it != backs.end(); ++it) {
2833                 vector<Format const *>  r =
2834                         theConverters().getReachable(*it, only_viewable, false);
2835                 result.insert(result.end(), r.begin(), r.end());
2836         }
2837         return result;
2838 }
2839
2840
2841 vector<string> Buffer::backends() const
2842 {
2843         vector<string> v;
2844         if (params().baseClass()->isTeXClassAvailable()) {
2845                 v.push_back(bufferFormat());
2846                 // FIXME: Don't hardcode format names here, but use a flag
2847                 if (v.back() == "latex")
2848                         v.push_back("pdflatex");
2849         }
2850         v.push_back("text");
2851         v.push_back("lyx");
2852         return v;
2853 }
2854
2855
2856 bool Buffer::readFileHelper(FileName const & s)
2857 {
2858         // File information about normal file
2859         if (!s.exists()) {
2860                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2861                 docstring text = bformat(_("The specified document\n%1$s"
2862                                                      "\ncould not be read."), file);
2863                 Alert::error(_("Could not read document"), text);
2864                 return false;
2865         }
2866
2867         // Check if emergency save file exists and is newer.
2868         FileName const e(s.absFilename() + ".emergency");
2869
2870         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2871                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2872                 docstring const text =
2873                         bformat(_("An emergency save of the document "
2874                                   "%1$s exists.\n\n"
2875                                                "Recover emergency save?"), file);
2876                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2877                                       _("&Recover"),  _("&Load Original"),
2878                                       _("&Cancel")))
2879                 {
2880                 case 0:
2881                         // the file is not saved if we load the emergency file.
2882                         markDirty();
2883                         return readFile(e);
2884                 case 1:
2885                         break;
2886                 default:
2887                         return false;
2888                 }
2889         }
2890
2891         // Now check if autosave file is newer.
2892         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2893
2894         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2895                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2896                 docstring const text =
2897                         bformat(_("The backup of the document "
2898                                   "%1$s is newer.\n\nLoad the "
2899                                                "backup instead?"), file);
2900                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2901                                       _("&Load backup"), _("Load &original"),
2902                                       _("&Cancel") ))
2903                 {
2904                 case 0:
2905                         // the file is not saved if we load the autosave file.
2906                         markDirty();
2907                         return readFile(a);
2908                 case 1:
2909                         // Here we delete the autosave
2910                         a.removeFile();
2911                         break;
2912                 default:
2913                         return false;
2914                 }
2915         }
2916         return readFile(s);
2917 }
2918
2919
2920 bool Buffer::loadLyXFile(FileName const & s)
2921 {
2922         if (s.isReadableFile()) {
2923                 if (readFileHelper(s)) {
2924                         lyxvc().file_found_hook(s);
2925                         if (!s.isWritable())
2926                                 setReadonly(true);
2927                         return true;
2928                 }
2929         } else {
2930                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2931                 // Here we probably should run
2932                 if (LyXVC::file_not_found_hook(s)) {
2933                         docstring const text =
2934                                 bformat(_("Do you want to retrieve the document"
2935                                                        " %1$s from version control?"), file);
2936                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2937                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2938
2939                         if (ret == 0) {
2940                                 // How can we know _how_ to do the checkout?
2941                                 // With the current VC support it has to be,
2942                                 // a RCS file since CVS do not have special ,v files.
2943                                 RCS::retrieve(s);
2944                                 return loadLyXFile(s);
2945                         }
2946                 }
2947         }
2948         return false;
2949 }
2950
2951
2952 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2953 {
2954         TeXErrors::Errors::const_iterator cit = terr.begin();
2955         TeXErrors::Errors::const_iterator end = terr.end();
2956
2957         for (; cit != end; ++cit) {
2958                 int id_start = -1;
2959                 int pos_start = -1;
2960                 int errorRow = cit->error_in_line;
2961                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2962                                                        pos_start);
2963                 int id_end = -1;
2964                 int pos_end = -1;
2965                 do {
2966                         ++errorRow;
2967                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2968                 } while (found && id_start == id_end && pos_start == pos_end);
2969
2970                 errorList.push_back(ErrorItem(cit->error_desc,
2971                         cit->error_text, id_start, pos_start, pos_end));
2972         }
2973 }
2974
2975
2976 void Buffer::setBuffersForInsets() const
2977 {
2978         inset().setBuffer(const_cast<Buffer &>(*this)); 
2979 }
2980
2981
2982 void Buffer::updateLabels(UpdateScope scope) const
2983 {
2984         // Use the master text class also for child documents
2985         Buffer const * const master = masterBuffer();
2986         DocumentClass const & textclass = master->params().documentClass();
2987
2988         // keep the buffers to be children in this set. If the call from the
2989         // master comes back we can see which of them were actually seen (i.e.
2990         // via an InsetInclude). The remaining ones in the set need still be updated.
2991         static std::set<Buffer const *> bufToUpdate;
2992         if (scope == UpdateMaster) {
2993                 // If this is a child document start with the master
2994                 if (master != this) {
2995                         bufToUpdate.insert(this);
2996                         master->updateLabels();
2997                         // Do this here in case the master has no gui associated with it. Then, 
2998                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2999                         if (!master->gui_)
3000                                 structureChanged();     
3001
3002                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3003                         if (bufToUpdate.find(this) == bufToUpdate.end())
3004                                 return;
3005                 }
3006
3007                 // start over the counters in the master
3008                 textclass.counters().reset();
3009         }
3010
3011         // update will be done below for this buffer
3012         bufToUpdate.erase(this);
3013
3014         // update all caches
3015         clearReferenceCache();
3016         updateMacros();
3017
3018         Buffer & cbuf = const_cast<Buffer &>(*this);
3019
3020         LASSERT(!text().paragraphs().empty(), /**/);
3021
3022         // do the real work
3023         ParIterator parit = cbuf.par_iterator_begin();
3024         updateLabels(parit);
3025
3026         if (master != this)
3027                 // TocBackend update will be done later.
3028                 return;
3029
3030         cbuf.tocBackend().update();
3031         if (scope == UpdateMaster)
3032                 cbuf.structureChanged();
3033 }
3034
3035
3036 static depth_type getDepth(DocIterator const & it)
3037 {
3038         depth_type depth = 0;
3039         for (size_t i = 0 ; i < it.depth() ; ++i)
3040                 if (!it[i].inset().inMathed())
3041                         depth += it[i].paragraph().getDepth() + 1;
3042         // remove 1 since the outer inset does not count
3043         return depth - 1;
3044 }
3045
3046 static depth_type getItemDepth(ParIterator const & it)
3047 {
3048         Paragraph const & par = *it;
3049         LabelType const labeltype = par.layout().labeltype;
3050
3051         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3052                 return 0;
3053
3054         // this will hold the lowest depth encountered up to now.
3055         depth_type min_depth = getDepth(it);
3056         ParIterator prev_it = it;
3057         while (true) {
3058                 if (prev_it.pit())
3059                         --prev_it.top().pit();
3060                 else {
3061                         // start of nested inset: go to outer par
3062                         prev_it.pop_back();
3063                         if (prev_it.empty()) {
3064                                 // start of document: nothing to do
3065                                 return 0;
3066                         }
3067                 }
3068
3069                 // We search for the first paragraph with same label
3070                 // that is not more deeply nested.
3071                 Paragraph & prev_par = *prev_it;
3072                 depth_type const prev_depth = getDepth(prev_it);
3073                 if (labeltype == prev_par.layout().labeltype) {
3074                         if (prev_depth < min_depth)
3075                                 return prev_par.itemdepth + 1;
3076                         if (prev_depth == min_depth)
3077                                 return prev_par.itemdepth;
3078                 }
3079                 min_depth = min(min_depth, prev_depth);
3080                 // small optimization: if we are at depth 0, we won't
3081                 // find anything else
3082                 if (prev_depth == 0)
3083                         return 0;
3084         }
3085 }
3086
3087
3088 static bool needEnumCounterReset(ParIterator const & it)
3089 {
3090         Paragraph const & par = *it;
3091         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3092         depth_type const cur_depth = par.getDepth();
3093         ParIterator prev_it = it;
3094         while (prev_it.pit()) {
3095                 --prev_it.top().pit();
3096                 Paragraph const & prev_par = *prev_it;
3097                 if (prev_par.getDepth() <= cur_depth)
3098                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3099         }
3100         // start of nested inset: reset
3101         return true;
3102 }
3103
3104
3105 // set the label of a paragraph. This includes the counters.
3106 static void setLabel(Buffer const & buf, ParIterator & it)
3107 {
3108         BufferParams const & bp = buf.masterBuffer()->params();
3109         DocumentClass const & textclass = bp.documentClass();
3110         Paragraph & par = it.paragraph();
3111         Layout const & layout = par.layout();
3112         Counters & counters = textclass.counters();
3113
3114         if (par.params().startOfAppendix()) {
3115                 // FIXME: only the counter corresponding to toplevel
3116                 // sectionning should be reset
3117                 counters.reset();
3118                 counters.appendix(true);
3119         }
3120         par.params().appendix(counters.appendix());
3121
3122         // Compute the item depth of the paragraph
3123         par.itemdepth = getItemDepth(it);
3124
3125         if (layout.margintype == MARGIN_MANUAL) {
3126                 if (par.params().labelWidthString().empty())
3127                         par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3128         } else {
3129                 par.params().labelWidthString(docstring());
3130         }
3131
3132         switch(layout.labeltype) {
3133         case LABEL_COUNTER:
3134                 if (layout.toclevel <= bp.secnumdepth
3135                     && (layout.latextype != LATEX_ENVIRONMENT
3136                         || isFirstInSequence(it.pit(), it.plist()))) {
3137                         counters.step(layout.counter);
3138                         par.params().labelString(
3139                                 par.expandLabel(layout, bp));
3140                 } else
3141                         par.params().labelString(docstring());
3142                 break;
3143
3144         case LABEL_ITEMIZE: {
3145                 // At some point of time we should do something more
3146                 // clever here, like:
3147                 //   par.params().labelString(
3148                 //    bp.user_defined_bullet(par.itemdepth).getText());
3149                 // for now, use a simple hardcoded label
3150                 docstring itemlabel;
3151                 switch (par.itemdepth) {
3152                 case 0:
3153                         itemlabel = char_type(0x2022);
3154                         break;
3155                 case 1:
3156                         itemlabel = char_type(0x2013);
3157                         break;
3158                 case 2:
3159                         itemlabel = char_type(0x2217);
3160                         break;
3161                 case 3:
3162                         itemlabel = char_type(0x2219); // or 0x00b7
3163                         break;
3164                 }
3165                 par.params().labelString(itemlabel);
3166                 break;
3167         }
3168
3169         case LABEL_ENUMERATE: {
3170                 // FIXME: Yes I know this is a really, really! bad solution
3171                 // (Lgb)
3172                 docstring enumcounter = from_ascii("enum");
3173
3174                 switch (par.itemdepth) {
3175                 case 2:
3176                         enumcounter += 'i';
3177                 case 1:
3178                         enumcounter += 'i';
3179                 case 0:
3180                         enumcounter += 'i';
3181                         break;
3182                 case 3:
3183                         enumcounter += "iv";
3184                         break;
3185                 default:
3186                         // not a valid enumdepth...
3187                         break;
3188                 }
3189
3190                 // Maybe we have to reset the enumeration counter.
3191                 if (needEnumCounterReset(it))
3192                         counters.reset(enumcounter);
3193
3194                 counters.step(enumcounter);
3195
3196                 string format;
3197
3198                 switch (par.itemdepth) {
3199                 case 0:
3200                         format = N_("\\arabic{enumi}.");
3201                         break;
3202                 case 1:
3203                         format = N_("(\\alph{enumii})");
3204                         break;
3205                 case 2:
3206                         format = N_("\\roman{enumiii}.");
3207                         break;
3208                 case 3:
3209                         format = N_("\\Alph{enumiv}.");
3210                         break;
3211                 default:
3212                         // not a valid enumdepth...
3213                         break;
3214                 }
3215
3216                 par.params().labelString(counters.counterLabel(
3217                         par.translateIfPossible(from_ascii(format), bp)));
3218
3219                 break;
3220         }
3221
3222         case LABEL_SENSITIVE: {
3223                 string const & type = counters.current_float();
3224                 docstring full_label;
3225                 if (type.empty())
3226                         full_label = buf.B_("Senseless!!! ");
3227                 else {
3228                         docstring name = buf.B_(textclass.floats().getType(type).name());
3229                         if (counters.hasCounter(from_utf8(type))) {
3230                                 counters.step(from_utf8(type));
3231                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3232                                                      name, 
3233                                                      counters.theCounter(from_utf8(type)));
3234                         } else
3235                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3236                 }
3237                 par.params().labelString(full_label);   
3238                 break;
3239         }
3240
3241         case LABEL_NO_LABEL:
3242                 par.params().labelString(docstring());
3243                 break;
3244
3245         case LABEL_MANUAL:
3246         case LABEL_TOP_ENVIRONMENT:
3247         case LABEL_CENTERED_TOP_ENVIRONMENT:
3248         case LABEL_STATIC:      
3249         case LABEL_BIBLIO:
3250                 par.params().labelString(
3251                         par.translateIfPossible(layout.labelstring(), bp));
3252                 break;
3253         }
3254 }
3255
3256
3257 void Buffer::updateLabels(ParIterator & parit) const
3258 {
3259         LASSERT(parit.pit() == 0, /**/);
3260
3261         // set the position of the text in the buffer to be able
3262         // to resolve macros in it. This has nothing to do with
3263         // labels, but by putting it here we avoid implementing
3264         // a whole bunch of traversal routines just for this call.
3265         parit.text()->setMacrocontextPosition(parit);
3266
3267         depth_type maxdepth = 0;
3268         pit_type const lastpit = parit.lastpit();
3269         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3270                 // reduce depth if necessary
3271                 parit->params().depth(min(parit->params().depth(), maxdepth));
3272                 maxdepth = parit->getMaxDepthAfter();
3273
3274                 // set the counter for this paragraph
3275                 setLabel(*this, parit);
3276
3277                 // Now the insets
3278                 InsetList::const_iterator iit = parit->insetList().begin();
3279                 InsetList::const_iterator end = parit->insetList().end();
3280                 for (; iit != end; ++iit) {
3281                         parit.pos() = iit->pos;
3282                         iit->inset->updateLabels(parit);
3283                 }
3284         }
3285 }
3286
3287
3288 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3289         docstring & word) const
3290 {
3291         bool inword = false;
3292         bool ignoreword = false;
3293         string lang_code;
3294         // Go backward a bit if needed in order to return the word currently
3295         // pointed by 'from'.
3296         while (from && from.pos() && isLetter(from))
3297                 from.backwardPos();
3298         // OK, we start from here.
3299         to = from;
3300         while (to.depth()) {
3301                 if (isLetter(to)) {
3302                         if (!inword) {
3303                                 inword = true;
3304                                 ignoreword = false;
3305                                 from = to;
3306                                 word.clear();
3307                                 lang_code = to.paragraph().getFontSettings(params(),
3308                                         to.pos()).language()->code();
3309                         }
3310                         // Insets like optional hyphens and ligature
3311                         // break are part of a word.
3312                         if (!to.paragraph().isInset(to.pos())) {
3313                                 char_type const c = to.paragraph().getChar(to.pos());
3314                                 word += c;
3315                                 if (isDigit(c))
3316                                         ignoreword = true;
3317                         }
3318                 } else { // !isLetter(cur)
3319                         if (inword && !word.empty() && !ignoreword)
3320                                 return true;
3321                         inword = false;
3322                 }
3323                 to.forwardPos();
3324         }
3325         from = to;
3326         word.clear();
3327         return false;
3328 }
3329
3330
3331 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3332         WordLangTuple & word_lang, docstring_list & suggestions) const
3333 {
3334         int progress = 0;
3335         SpellChecker::Result res = SpellChecker::OK;
3336         SpellChecker * speller = theSpellChecker();
3337         suggestions.clear();
3338         docstring word;
3339         while (nextWord(from, to, word)) {
3340                 ++progress;
3341                 string lang_code = lyxrc.spellchecker_use_alt_lang
3342                       ? lyxrc.spellchecker_alt_lang
3343                       : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3344                 WordLangTuple wl(word, lang_code);
3345                 res = speller->check(wl);
3346                 // ... just bail out if the spellchecker reports an error.
3347                 if (!speller->error().empty()) {
3348                         throw ExceptionMessage(WarningException,
3349                                 _("The spellchecker has failed."), speller->error());
3350                 }
3351                 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3352                         word_lang = wl;
3353                         break;
3354                 }
3355                 from = to;
3356         }
3357         while (!(word = speller->nextMiss()).empty())
3358                 suggestions.push_back(word);
3359         return progress;
3360 }
3361
3362 } // namespace lyx