]> git.lyx.org Git - features.git/blob - src/Buffer.cpp
Refactor Buffer.cpp: loadLyXFile():
[features.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 "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "LaTeXFeatures.h"
40 #include "LaTeX.h"
41 #include "Layout.h"
42 #include "Lexer.h"
43 #include "LyXAction.h"
44 #include "LyX.h"
45 #include "LyXRC.h"
46 #include "LyXVC.h"
47 #include "output_docbook.h"
48 #include "output.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
57 #include "sgml.h"
58 #include "TexRow.h"
59 #include "TexStream.h"
60 #include "Text.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
63 #include "Undo.h"
64 #include "VCBackend.h"
65 #include "version.h"
66 #include "WordLangTuple.h"
67 #include "WordList.h"
68
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
75
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
80
81 #include "frontends/alert.h"
82 #include "frontends/Delegates.h"
83 #include "frontends/WorkAreaManager.h"
84
85 #include "graphics/Previews.h"
86
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
106
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
109
110 #include <algorithm>
111 #include <fstream>
112 #include <iomanip>
113 #include <map>
114 #include <set>
115 #include <sstream>
116 #include <stack>
117 #include <vector>
118
119 using namespace std;
120 using namespace lyx::support;
121
122 namespace lyx {
123
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
126
127 namespace {
128
129 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 404; // rgh: refstyle
132
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135
136 void showPrintError(string const & name)
137 {
138         docstring str = bformat(_("Could not print the document %1$s.\n"
139                                             "Check that your printer is set up correctly."),
140                              makeDisplayPath(name, 50));
141         Alert::error(_("Print document failed"), str);
142 }
143
144 } // namespace anon
145
146
147 class Buffer::Impl
148 {
149 public:
150         Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
151
152         ~Impl()
153         {
154                 if (wa_) {
155                         wa_->closeAll();
156                         delete wa_;
157                 }
158                 delete inset;
159         }
160         
161         /// search for macro in local (buffer) table or in children
162         MacroData const * getBufferMacro(docstring const & name,
163                 DocIterator const & pos) const;
164
165         /// Update macro table starting with position of it \param it in some
166         /// text inset.
167         void updateMacros(DocIterator & it, DocIterator & scope);
168         ///
169         void setLabel(ParIterator & it, UpdateType utype) const;
170
171         /** If we have branches that use the file suffix
172             feature, return the file name with suffix appended.
173         */
174         support::FileName exportFileName() const;
175
176         Buffer * owner_;
177
178         BufferParams params;
179         LyXVC lyxvc;
180         FileName temppath;
181         mutable TexRow texrow;
182
183         /// need to regenerate .tex?
184         DepClean dep_clean;
185
186         /// is save needed?
187         mutable bool lyx_clean;
188
189         /// is autosave needed?
190         mutable bool bak_clean;
191
192         /// is this a unnamed file (New...)?
193         bool unnamed;
194
195         /// buffer is r/o
196         bool read_only;
197
198         /// name of the file the buffer is associated with.
199         FileName filename;
200
201         /** Set to true only when the file is fully loaded.
202          *  Used to prevent the premature generation of previews
203          *  and by the citation inset.
204          */
205         bool file_fully_loaded;
206
207         ///
208         mutable TocBackend toc_backend;
209
210         /// macro tables
211         typedef pair<DocIterator, MacroData> ScopeMacro;
212         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214         /// map from the macro name to the position map,
215         /// which maps the macro definition position to the scope and the MacroData.
216         NamePositionScopeMacroMap macros;
217         /// This seem to change the way Buffer::getMacro() works
218         mutable bool macro_lock;
219
220         /// positions of child buffers in the buffer
221         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224         /// position of children buffers in this buffer
225         BufferPositionMap children_positions;
226         /// map from children inclusion positions to their scope and their buffer
227         PositionScopeBufferMap position_to_children;
228
229         /// Container for all sort of Buffer dependant errors.
230         map<string, ErrorList> errorLists;
231
232         /// timestamp and checksum used to test if the file has been externally
233         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
234         time_t timestamp_;
235         unsigned long checksum_;
236
237         ///
238         frontend::WorkAreaManager * wa_;
239         ///
240         frontend::GuiBufferDelegate * gui_;
241
242         ///
243         Undo undo_;
244
245         /// A cache for the bibfiles (including bibfiles of loaded child
246         /// documents), needed for appropriate update of natbib labels.
247         mutable support::FileNameList bibfiles_cache_;
248
249         // FIXME The caching mechanism could be improved. At present, we have a
250         // cache for each Buffer, that caches all the bibliography info for that
251         // Buffer. A more efficient solution would be to have a global cache per
252         // file, and then to construct the Buffer's bibinfo from that.
253         /// A cache for bibliography info
254         mutable BiblioInfo bibinfo_;
255         /// whether the bibinfo cache is valid
256         mutable bool bibinfo_cache_valid_;
257         /// whether the bibfile cache is valid
258         mutable bool bibfile_cache_valid_;
259         /// Cache of timestamps of .bib files
260         map<FileName, time_t> bibfile_status_;
261
262         mutable RefCache ref_cache_;
263
264         /// our Text that should be wrapped in an InsetText
265         InsetText * inset;
266
267         /// This is here to force the test to be done whenever parent_buffer
268         /// is accessed.
269         Buffer const * parent() const { 
270                 // if parent_buffer is not loaded, then it has been unloaded,
271                 // which means that parent_buffer is an invalid pointer. So we
272                 // set it to null in that case.
273                 // however, the BufferList doesn't know about cloned buffers, so
274                 // they will always be regarded as unloaded. in that case, we hope
275                 // for the best.
276                 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
277                         parent_buffer = 0;
278                 return parent_buffer; 
279         }
280         
281         ///
282         void setParent(Buffer const * pb) {
283                 if (parent_buffer == pb)
284                         // nothing to do
285                         return;
286                 if (!cloned_buffer_ && parent_buffer && pb)
287                         LYXERR0("Warning: a buffer should not have two parents!");
288                 parent_buffer = pb;
289                 if (!cloned_buffer_ && parent_buffer) {
290                         parent_buffer->invalidateBibfileCache();
291                         parent_buffer->invalidateBibinfoCache();
292                 }
293         }
294
295         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296         /// This one is useful for preview detached in a thread.
297         Buffer const * cloned_buffer_;
298         /// are we in the process of exporting this buffer?
299         mutable bool doing_export;
300         
301 private:
302         /// So we can force access via the accessors.
303         mutable Buffer const * parent_buffer;
304
305 };
306
307
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
310 {
311         static int count;
312         // We are in our own directory.  Why bother to mangle name?
313         // In fact I wrote this code to circumvent a problematic behaviour
314         // (bug?) of EMX mkstemp().
315         FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316                 convert<string>(count++));
317
318         if (!tmpfl.createDirectory(0777)) {
319                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321                         from_utf8(tmpfl.absFileName())));
322         }
323         return tmpfl;
324 }
325
326
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328         Buffer const * cloned_buffer)
329         : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330           read_only(readonly_), filename(file), file_fully_loaded(false),
331           toc_backend(owner), macro_lock(false), timestamp_(0),
332           checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333                 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer), 
334                 doing_export(false), parent_buffer(0)
335 {
336         if (!cloned_buffer_) {
337                 temppath = createBufferTmpDir();
338                 lyxvc.setBuffer(owner_);
339                 if (use_gui)
340                         wa_ = new frontend::WorkAreaManager;
341                 return;
342         }
343         temppath = cloned_buffer_->d->temppath;
344         file_fully_loaded = true;
345         params = cloned_buffer_->d->params;
346         bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347         bibinfo_ = cloned_buffer_->d->bibinfo_;
348         bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349         bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350         bibfile_status_ = cloned_buffer_->d->bibfile_status_;
351 }
352
353
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355         : d(new Impl(this, FileName(file), readonly, cloned_buffer))
356 {
357         LYXERR(Debug::INFO, "Buffer::Buffer()");
358         if (cloned_buffer) {
359                 d->inset = new InsetText(*cloned_buffer->d->inset);
360                 d->inset->setBuffer(*this);
361                 // FIXME: optimize this loop somewhat, maybe by creating a new
362                 // general recursive Inset::setId().
363                 DocIterator it = doc_iterator_begin(this);
364                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366                         it.paragraph().setId(cloned_it.paragraph().id());
367         } else
368                 d->inset = new InsetText(this);
369         d->inset->setAutoBreakRows(true);
370         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
371 }
372
373
374 Buffer::~Buffer()
375 {
376         LYXERR(Debug::INFO, "Buffer::~Buffer()");
377         // here the buffer should take care that it is
378         // saved properly, before it goes into the void.
379
380         // GuiView already destroyed
381         d->gui_ = 0;
382
383         if (isInternal()) {
384                 // No need to do additional cleanups for internal buffer.
385                 delete d;
386                 return;
387         }
388
389         // loop over children
390         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391         Impl::BufferPositionMap::iterator end = d->children_positions.end();
392         for (; it != end; ++it) {
393                 Buffer * child = const_cast<Buffer *>(it->first);
394                 if (d->cloned_buffer_)
395                         delete child;
396                 // The child buffer might have been closed already.
397                 else if (theBufferList().isLoaded(child))
398                         theBufferList().releaseChild(this, child);
399         }
400
401         if (!isClean()) {
402                 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403                 msg += emergencyWrite();
404                 Alert::warning(_("Attempting to close changed document!"), msg);
405         }
406                 
407         // clear references to children in macro tables
408         d->children_positions.clear();
409         d->position_to_children.clear();
410
411         if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412                 Alert::warning(_("Could not remove temporary directory"),
413                         bformat(_("Could not remove the temporary directory %1$s"),
414                         from_utf8(d->temppath.absFileName())));
415         }
416
417         // Remove any previewed LaTeX snippets associated with this buffer.
418         if (!isClone())
419                 thePreviews().removeLoader(*this);
420
421         delete d;
422 }
423
424
425 Buffer * Buffer::clone() const
426 {
427         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
428         buffer_clone->d->macro_lock = true;
429         buffer_clone->d->children_positions.clear();
430         // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
431         // math macro caches need to be rethought and simplified.
432         // I am not sure wether we should handle Buffer cloning here or in BufferList.
433         // Right now BufferList knows nothing about buffer clones.
434         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
435         Impl::BufferPositionMap::iterator end = d->children_positions.end();
436         for (; it != end; ++it) {
437                 DocIterator dit = it->second.clone(buffer_clone);
438                 dit.setBuffer(buffer_clone);
439                 Buffer * child = const_cast<Buffer *>(it->first);
440                 Buffer * child_clone = child->clone();
441                 Inset * inset = dit.nextInset();
442                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
443                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
444                 inset_inc->setChildBuffer(child_clone);
445                 child_clone->d->setParent(buffer_clone);
446                 buffer_clone->setChild(dit, child_clone);
447         }
448         buffer_clone->d->macro_lock = false;
449         return buffer_clone;
450 }
451
452
453 bool Buffer::isClone() const
454 {
455         return d->cloned_buffer_;
456 }
457
458
459 void Buffer::changed(bool update_metrics) const
460 {
461         if (d->wa_)
462                 d->wa_->redrawAll(update_metrics);
463 }
464
465
466 frontend::WorkAreaManager & Buffer::workAreaManager() const
467 {
468         LASSERT(d->wa_, /**/);
469         return *d->wa_;
470 }
471
472
473 Text & Buffer::text() const
474 {
475         return d->inset->text();
476 }
477
478
479 Inset & Buffer::inset() const
480 {
481         return *d->inset;
482 }
483
484
485 BufferParams & Buffer::params()
486 {
487         return d->params;
488 }
489
490
491 BufferParams const & Buffer::params() const
492 {
493         return d->params;
494 }
495
496
497 ParagraphList & Buffer::paragraphs()
498 {
499         return text().paragraphs();
500 }
501
502
503 ParagraphList const & Buffer::paragraphs() const
504 {
505         return text().paragraphs();
506 }
507
508
509 LyXVC & Buffer::lyxvc()
510 {
511         return d->lyxvc;
512 }
513
514
515 LyXVC const & Buffer::lyxvc() const
516 {
517         return d->lyxvc;
518 }
519
520
521 string const Buffer::temppath() const
522 {
523         return d->temppath.absFileName();
524 }
525
526
527 TexRow & Buffer::texrow()
528 {
529         return d->texrow;
530 }
531
532
533 TexRow const & Buffer::texrow() const
534 {
535         return d->texrow;
536 }
537
538
539 TocBackend & Buffer::tocBackend() const
540 {
541         return d->toc_backend;
542 }
543
544
545 Undo & Buffer::undo()
546 {
547         return d->undo_;
548 }
549
550
551 void Buffer::setChild(DocIterator const & dit, Buffer * child)
552 {
553         d->children_positions[child] = dit;
554 }
555
556
557 string Buffer::latexName(bool const no_path) const
558 {
559         FileName latex_name =
560                 makeLatexName(d->exportFileName());
561         return no_path ? latex_name.onlyFileName()
562                 : latex_name.absFileName();
563 }
564
565
566 FileName Buffer::Impl::exportFileName() const
567 {
568         docstring const branch_suffix =
569                 params.branchlist().getFileNameSuffix();
570         if (branch_suffix.empty())
571                 return filename;
572
573         string const name = filename.onlyFileNameWithoutExt()
574                 + to_utf8(branch_suffix);
575         FileName res(filename.onlyPath().absFileName() + "/" + name);
576         res.changeExtension(filename.extension());
577
578         return res;
579 }
580
581
582 string Buffer::logName(LogType * type) const
583 {
584         string const filename = latexName(false);
585
586         if (filename.empty()) {
587                 if (type)
588                         *type = latexlog;
589                 return string();
590         }
591
592         string const path = temppath();
593
594         FileName const fname(addName(temppath(),
595                                      onlyFileName(changeExtension(filename,
596                                                                   ".log"))));
597
598         // FIXME: how do we know this is the name of the build log?
599         FileName const bname(
600                 addName(path, onlyFileName(
601                         changeExtension(filename,
602                                         formats.extension(bufferFormat()) + ".out"))));
603
604         // Also consider the master buffer log file
605         FileName masterfname = fname;
606         LogType mtype;
607         if (masterBuffer() != this) {
608                 string const mlogfile = masterBuffer()->logName(&mtype);
609                 masterfname = FileName(mlogfile);
610         }
611
612         // If no Latex log or Build log is newer, show Build log
613         if (bname.exists() &&
614             ((!fname.exists() && !masterfname.exists())
615              || (fname.lastModified() < bname.lastModified()
616                  && masterfname.lastModified() < bname.lastModified()))) {
617                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
618                 if (type)
619                         *type = buildlog;
620                 return bname.absFileName();
621         // If we have a newer master file log or only a master log, show this
622         } else if (fname != masterfname
623                    && (!fname.exists() && (masterfname.exists()
624                    || fname.lastModified() < masterfname.lastModified()))) {
625                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
626                 if (type)
627                         *type = mtype;
628                 return masterfname.absFileName();
629         }
630         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
631         if (type)
632                         *type = latexlog;
633         return fname.absFileName();
634 }
635
636
637 void Buffer::setReadonly(bool const flag)
638 {
639         if (d->read_only != flag) {
640                 d->read_only = flag;
641                 changed(false);
642         }
643 }
644
645
646 void Buffer::setFileName(string const & newfile)
647 {
648         d->filename = makeAbsPath(newfile);
649         setReadonly(d->filename.isReadOnly());
650         updateTitles();
651 }
652
653
654 int Buffer::readHeader(Lexer & lex)
655 {
656         int unknown_tokens = 0;
657         int line = -1;
658         int begin_header_line = -1;
659
660         // Initialize parameters that may be/go lacking in header:
661         params().branchlist().clear();
662         params().preamble.erase();
663         params().options.erase();
664         params().master.erase();
665         params().float_placement.erase();
666         params().paperwidth.erase();
667         params().paperheight.erase();
668         params().leftmargin.erase();
669         params().rightmargin.erase();
670         params().topmargin.erase();
671         params().bottommargin.erase();
672         params().headheight.erase();
673         params().headsep.erase();
674         params().footskip.erase();
675         params().columnsep.erase();
676         params().fontsCJK.erase();
677         params().listings_params.clear();
678         params().clearLayoutModules();
679         params().clearRemovedModules();
680         params().clearIncludedChildren();
681         params().pdfoptions().clear();
682         params().indiceslist().clear();
683         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
684         params().isbackgroundcolor = false;
685         params().fontcolor = lyx::rgbFromHexName("#000000");
686         params().isfontcolor = false;
687         params().notefontcolor = lyx::rgbFromHexName("#cccccc");
688         params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
689         params().html_latex_start.clear();
690         params().html_latex_end.clear();
691         params().html_math_img_scale = 1.0;
692         params().output_sync_macro.erase();
693
694         for (int i = 0; i < 4; ++i) {
695                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
696                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
697         }
698
699         ErrorList & errorList = d->errorLists["Parse"];
700
701         while (lex.isOK()) {
702                 string token;
703                 lex >> token;
704
705                 if (token.empty())
706                         continue;
707
708                 if (token == "\\end_header")
709                         break;
710
711                 ++line;
712                 if (token == "\\begin_header") {
713                         begin_header_line = line;
714                         continue;
715                 }
716
717                 LYXERR(Debug::PARSER, "Handling document header token: `"
718                                       << token << '\'');
719
720                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
721                 if (!unknown.empty()) {
722                         if (unknown[0] != '\\' && token == "\\textclass") {
723                                 Alert::warning(_("Unknown document class"),
724                        bformat(_("Using the default document class, because the "
725                                               "class %1$s is unknown."), from_utf8(unknown)));
726                         } else {
727                                 ++unknown_tokens;
728                                 docstring const s = bformat(_("Unknown token: "
729                                                                         "%1$s %2$s\n"),
730                                                          from_utf8(token),
731                                                          lex.getDocString());
732                                 errorList.push_back(ErrorItem(_("Document header error"),
733                                         s, -1, 0, 0));
734                         }
735                 }
736         }
737         if (begin_header_line) {
738                 docstring const s = _("\\begin_header is missing");
739                 errorList.push_back(ErrorItem(_("Document header error"),
740                         s, -1, 0, 0));
741         }
742
743         params().makeDocumentClass();
744
745         return unknown_tokens;
746 }
747
748
749 // Uwe C. Schroeder
750 // changed to be public and have one parameter
751 // Returns true if "\end_document" is not read (Asger)
752 bool Buffer::readDocument(Lexer & lex)
753 {
754         ErrorList & errorList = d->errorLists["Parse"];
755         errorList.clear();
756
757         if (!lex.checkFor("\\begin_document")) {
758                 docstring const s = _("\\begin_document is missing");
759                 errorList.push_back(ErrorItem(_("Document header error"),
760                         s, -1, 0, 0));
761         }
762
763         // we are reading in a brand new document
764         LASSERT(paragraphs().empty(), /**/);
765
766         readHeader(lex);
767
768         if (params().outputChanges) {
769                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
770                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
771                                   LaTeXFeatures::isAvailable("xcolor");
772
773                 if (!dvipost && !xcolorulem) {
774                         Alert::warning(_("Changes not shown in LaTeX output"),
775                                        _("Changes will not be highlighted in LaTeX output, "
776                                          "because neither dvipost nor xcolor/ulem are installed.\n"
777                                          "Please install these packages or redefine "
778                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779                 } else if (!xcolorulem) {
780                         Alert::warning(_("Changes not shown in LaTeX output"),
781                                        _("Changes will not be highlighted in LaTeX output "
782                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
783                                          "Please install both packages or redefine "
784                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
785                 }
786         }
787
788         if (!params().master.empty()) {
789                 FileName const master_file = makeAbsPath(params().master,
790                            onlyPath(absFileName()));
791                 if (isLyXFileName(master_file.absFileName())) {
792                         Buffer * master = 
793                                 checkAndLoadLyXFile(master_file, true);
794                         if (master) {
795                                 // necessary e.g. after a reload
796                                 // to re-register the child (bug 5873)
797                                 // FIXME: clean up updateMacros (here, only
798                                 // child registering is needed).
799                                 master->updateMacros();
800                                 // set master as master buffer, but only
801                                 // if we are a real child
802                                 if (master->isChild(this))
803                                         setParent(master);
804                                 // if the master is not fully loaded
805                                 // it is probably just loading this
806                                 // child. No warning needed then.
807                                 else if (master->isFullyLoaded())
808                                         LYXERR0("The master '"
809                                                 << params().master
810                                                 << "' assigned to this document ("
811                                                 << absFileName()
812                                                 << ") does not include "
813                                                 "this document. Ignoring the master assignment.");
814                         }
815                 }
816         }
817         
818         // assure we have a default index
819         params().indiceslist().addDefault(B_("Index"));
820
821         // read main text
822         bool const res = text().read(lex, errorList, d->inset);
823
824         usermacros.clear();
825         updateMacros();
826         updateMacroInstances();
827         return res;
828 }
829
830
831 bool Buffer::readString(string const & s)
832 {
833         params().compressed = false;
834
835         // remove dummy empty par
836         paragraphs().clear();
837         Lexer lex;
838         istringstream is(s);
839         lex.setStream(is);
840         FileName const name = FileName::tempName("Buffer_readString");
841         switch (readFile(lex, name, true)) {
842         case ReadFailure:
843                 return false;
844         case ReadWrongVersion: {
845                 // We need to call lyx2lyx, so write the input to a file
846                 ofstream os(name.toFilesystemEncoding().c_str());
847                 os << s;
848                 os.close();
849                 return readFile(name);
850         }
851         case ReadSuccess:
852                 break;
853         }
854
855         return true;
856 }
857
858
859 bool Buffer::readFile(FileName const & filename)
860 {
861         FileName fname(filename);
862
863         params().compressed = fname.isZippedFile();
864
865         // remove dummy empty par
866         paragraphs().clear();
867         Lexer lex;
868         lex.setFile(fname);
869         if (readFile(lex, fname) != ReadSuccess)
870                 return false;
871
872         d->read_only = !fname.isWritable();
873         return true;
874 }
875
876
877 bool Buffer::isFullyLoaded() const
878 {
879         return d->file_fully_loaded;
880 }
881
882
883 void Buffer::setFullyLoaded(bool value)
884 {
885         d->file_fully_loaded = value;
886 }
887
888
889 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
890                 bool fromstring)
891 {
892         LASSERT(!filename.empty(), /**/);
893
894         // the first (non-comment) token _must_ be...
895         if (!lex.checkFor("\\lyxformat")) {
896                 Alert::error(_("Document format failure"),
897                              bformat(_("%1$s is not a readable LyX document."),
898                                        from_utf8(filename.absFileName())));
899                 return ReadFailure;
900         }
901
902         string tmp_format;
903         lex >> tmp_format;
904         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
905         // if present remove ".," from string.
906         size_t dot = tmp_format.find_first_of(".,");
907         //lyxerr << "           dot found at " << dot << endl;
908         if (dot != string::npos)
909                         tmp_format.erase(dot, 1);
910         int const file_format = convert<int>(tmp_format);
911         //lyxerr << "format: " << file_format << endl;
912
913         // save timestamp and checksum of the original disk file, making sure
914         // to not overwrite them with those of the file created in the tempdir
915         // when it has to be converted to the current format.
916         if (!d->checksum_) {
917                 // Save the timestamp and checksum of disk file. If filename is an
918                 // emergency file, save the timestamp and checksum of the original lyx file
919                 // because isExternallyModified will check for this file. (BUG4193)
920                 string diskfile = filename.absFileName();
921                 if (suffixIs(diskfile, ".emergency"))
922                         diskfile = diskfile.substr(0, diskfile.size() - 10);
923                 saveCheckSum(FileName(diskfile));
924         }
925
926         if (file_format != LYX_FORMAT) {
927
928                 if (fromstring)
929                         // lyx2lyx would fail
930                         return ReadWrongVersion;
931
932                 FileName const tmpfile = FileName::tempName("Buffer_readFile");
933                 if (tmpfile.empty()) {
934                         Alert::error(_("Conversion failed"),
935                                      bformat(_("%1$s is from a different"
936                                               " version of LyX, but a temporary"
937                                               " file for converting it could"
938                                               " not be created."),
939                                               from_utf8(filename.absFileName())));
940                         return ReadFailure;
941                 }
942                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
943                 if (lyx2lyx.empty()) {
944                         Alert::error(_("Conversion script not found"),
945                                      bformat(_("%1$s is from a different"
946                                                " version of LyX, but the"
947                                                " conversion script lyx2lyx"
948                                                " could not be found."),
949                                                from_utf8(filename.absFileName())));
950                         return ReadFailure;
951                 }
952                 ostringstream command;
953                 command << os::python()
954                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
955                         << " -t " << convert<string>(LYX_FORMAT)
956                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
957                         << ' ' << quoteName(filename.toSafeFilesystemEncoding());
958                 string const command_str = command.str();
959
960                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
961
962                 cmd_ret const ret = runCommand(command_str);
963                 if (ret.first != 0) {
964                         if (file_format < LYX_FORMAT)
965                                 Alert::error(_("Conversion script failed"),
966                                      bformat(_("%1$s is from an older version"
967                                               " of LyX, but the lyx2lyx script"
968                                               " failed to convert it."),
969                                               from_utf8(filename.absFileName())));
970                         else
971                                 Alert::error(_("Conversion script failed"),
972                                      bformat(_("%1$s is from a newer version"
973                                               " of LyX and cannot be converted by the"
974                                                                 " lyx2lyx script."),
975                                               from_utf8(filename.absFileName())));
976                         return ReadFailure;
977                 } else {
978                         bool const ret = readFile(tmpfile);
979                         // Do stuff with tmpfile name and buffer name here.
980                         return ret ? ReadSuccess : ReadFailure;
981                 }
982
983         }
984
985         if (readDocument(lex)) {
986                 Alert::error(_("Document format failure"),
987                              bformat(_("%1$s ended unexpectedly, which means"
988                                                     " that it is probably corrupted."),
989                                        from_utf8(filename.absFileName())));
990                 return ReadFailure;
991         }
992
993         d->file_fully_loaded = true;
994         return ReadSuccess;
995 }
996
997
998 // Should probably be moved to somewhere else: BufferView? GuiView?
999 bool Buffer::save() const
1000 {
1001         // ask if the disk file has been externally modified (use checksum method)
1002         if (fileName().exists() && isExternallyModified(checksum_method)) {
1003                 docstring const file = makeDisplayPath(absFileName(), 20);
1004                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1005                                                              "you want to overwrite this file?"), file);
1006                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1007                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1008                 if (ret == 1)
1009                         return false;
1010         }
1011
1012         // We don't need autosaves in the immediate future. (Asger)
1013         resetAutosaveTimers();
1014
1015         FileName backupName;
1016         bool madeBackup = false;
1017
1018         // make a backup if the file already exists
1019         if (lyxrc.make_backup && fileName().exists()) {
1020                 backupName = FileName(absFileName() + '~');
1021                 if (!lyxrc.backupdir_path.empty()) {
1022                         string const mangledName =
1023                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1024                         backupName = FileName(addName(lyxrc.backupdir_path,
1025                                                       mangledName));
1026                 }
1027                 // do not copy because of #6587
1028                 if (fileName().moveTo(backupName)) {
1029                         madeBackup = true;
1030                 } else {
1031                         Alert::error(_("Backup failure"),
1032                                      bformat(_("Cannot create backup file %1$s.\n"
1033                                                "Please check whether the directory exists and is writeable."),
1034                                              from_utf8(backupName.absFileName())));
1035                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1036                 }
1037         }
1038
1039         if (writeFile(d->filename)) {
1040                 markClean();
1041                 return true;
1042         } else {
1043                 // Saving failed, so backup is not backup
1044                 if (madeBackup)
1045                         backupName.moveTo(d->filename);
1046                 return false;
1047         }
1048 }
1049
1050
1051 bool Buffer::writeFile(FileName const & fname) const
1052 {
1053         if (d->read_only && fname == d->filename)
1054                 return false;
1055
1056         bool retval = false;
1057
1058         docstring const str = bformat(_("Saving document %1$s..."),
1059                 makeDisplayPath(fname.absFileName()));
1060         message(str);
1061
1062         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1063
1064         if (params().compressed) {
1065                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1066                 retval = ofs && write(ofs);
1067         } else {
1068                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1069                 retval = ofs && write(ofs);
1070         }
1071
1072         if (!retval) {
1073                 message(str + _(" could not write file!"));
1074                 return false;
1075         }
1076
1077         // see bug 6587
1078         // removeAutosaveFile();
1079
1080         saveCheckSum(d->filename);
1081         message(str + _(" done."));
1082
1083         return true;
1084 }
1085
1086
1087 docstring Buffer::emergencyWrite()
1088 {
1089         // No need to save if the buffer has not changed.
1090         if (isClean())
1091                 return docstring();
1092
1093         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1094
1095         docstring user_message = bformat(
1096                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1097
1098         // We try to save three places:
1099         // 1) Same place as document. Unless it is an unnamed doc.
1100         if (!isUnnamed()) {
1101                 string s = absFileName();
1102                 s += ".emergency";
1103                 LYXERR0("  " << s);
1104                 if (writeFile(FileName(s))) {
1105                         markClean();
1106                         user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1107                         return user_message;
1108                 } else {
1109                         user_message += _("  Save failed! Trying again...\n");
1110                 }
1111         }
1112
1113         // 2) In HOME directory.
1114         string s = addName(package().home_dir().absFileName(), absFileName());
1115         s += ".emergency";
1116         lyxerr << ' ' << s << endl;
1117         if (writeFile(FileName(s))) {
1118                 markClean();
1119                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1120                 return user_message;
1121         }
1122
1123         user_message += _("  Save failed! Trying yet again...\n");
1124
1125         // 3) In "/tmp" directory.
1126         // MakeAbsPath to prepend the current
1127         // drive letter on OS/2
1128         s = addName(package().temp_dir().absFileName(), absFileName());
1129         s += ".emergency";
1130         lyxerr << ' ' << s << endl;
1131         if (writeFile(FileName(s))) {
1132                 markClean();
1133                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1134                 return user_message;
1135         }
1136
1137         user_message += _("  Save failed! Bummer. Document is lost.");
1138         // Don't try again.
1139         markClean();
1140         return user_message;
1141 }
1142
1143
1144 bool Buffer::write(ostream & ofs) const
1145 {
1146 #ifdef HAVE_LOCALE
1147         // Use the standard "C" locale for file output.
1148         ofs.imbue(locale::classic());
1149 #endif
1150
1151         // The top of the file should not be written by params().
1152
1153         // write out a comment in the top of the file
1154         ofs << "#LyX " << lyx_version
1155             << " created this file. For more info see http://www.lyx.org/\n"
1156             << "\\lyxformat " << LYX_FORMAT << "\n"
1157             << "\\begin_document\n";
1158
1159         /// For each author, set 'used' to true if there is a change
1160         /// by this author in the document; otherwise set it to 'false'.
1161         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1162         AuthorList::Authors::const_iterator a_end = params().authors().end();
1163         for (; a_it != a_end; ++a_it)
1164                 a_it->setUsed(false);
1165
1166         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1167         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1168         for ( ; it != end; ++it)
1169                 it->checkAuthors(params().authors());
1170
1171         // now write out the buffer parameters.
1172         ofs << "\\begin_header\n";
1173         params().writeFile(ofs);
1174         ofs << "\\end_header\n";
1175
1176         // write the text
1177         ofs << "\n\\begin_body\n";
1178         text().write(ofs);
1179         ofs << "\n\\end_body\n";
1180
1181         // Write marker that shows file is complete
1182         ofs << "\\end_document" << endl;
1183
1184         // Shouldn't really be needed....
1185         //ofs.close();
1186
1187         // how to check if close went ok?
1188         // Following is an attempt... (BE 20001011)
1189
1190         // good() returns false if any error occured, including some
1191         //        formatting error.
1192         // bad()  returns true if something bad happened in the buffer,
1193         //        which should include file system full errors.
1194
1195         bool status = true;
1196         if (!ofs) {
1197                 status = false;
1198                 lyxerr << "File was not closed properly." << endl;
1199         }
1200
1201         return status;
1202 }
1203
1204
1205 bool Buffer::makeLaTeXFile(FileName const & fname,
1206                            string const & original_path,
1207                            OutputParams const & runparams_in,
1208                            bool output_preamble, bool output_body) const
1209 {
1210         OutputParams runparams = runparams_in;
1211         if (params().useXetex)
1212                 runparams.flavor = OutputParams::XETEX;
1213
1214         string const encoding = runparams.encoding->iconvName();
1215         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1216
1217         ofdocstream ofs;
1218         try { ofs.reset(encoding); }
1219         catch (iconv_codecvt_facet_exception & e) {
1220                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1221                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1222                         "verify that the support software for your encoding (%1$s) is "
1223                         "properly installed"), from_ascii(encoding)));
1224                 return false;
1225         }
1226         if (!openFileWrite(ofs, fname))
1227                 return false;
1228
1229         //TexStream ts(ofs.rdbuf(), &texrow());
1230         ErrorList & errorList = d->errorLists["Export"];
1231         errorList.clear();
1232         bool failed_export = false;
1233         try {
1234                 d->texrow.reset();
1235                 writeLaTeXSource(ofs, original_path,
1236                       runparams, output_preamble, output_body);
1237         }
1238         catch (EncodingException & e) {
1239                 odocstringstream ods;
1240                 ods.put(e.failed_char);
1241                 ostringstream oss;
1242                 oss << "0x" << hex << e.failed_char << dec;
1243                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1244                                           " (code point %2$s)"),
1245                                           ods.str(), from_utf8(oss.str()));
1246                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1247                                 "representable in the chosen encoding.\n"
1248                                 "Changing the document encoding to utf8 could help."),
1249                                 e.par_id, e.pos, e.pos + 1));
1250                 failed_export = true;
1251         }
1252         catch (iconv_codecvt_facet_exception & e) {
1253                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1254                         _(e.what()), -1, 0, 0));
1255                 failed_export = true;
1256         }
1257         catch (exception const & e) {
1258                 errorList.push_back(ErrorItem(_("conversion failed"),
1259                         _(e.what()), -1, 0, 0));
1260                 failed_export = true;
1261         }
1262         catch (...) {
1263                 lyxerr << "Caught some really weird exception..." << endl;
1264                 lyx_exit(1);
1265         }
1266
1267         ofs.close();
1268         if (ofs.fail()) {
1269                 failed_export = true;
1270                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1271         }
1272
1273         errors("Export");
1274         return !failed_export;
1275 }
1276
1277
1278 void Buffer::writeLaTeXSource(odocstream & os,
1279                            string const & original_path,
1280                            OutputParams const & runparams_in,
1281                            bool const output_preamble, bool const output_body) const
1282 {
1283         // The child documents, if any, shall be already loaded at this point.
1284
1285         OutputParams runparams = runparams_in;
1286
1287         // Classify the unicode characters appearing in math insets
1288         Encodings::initUnicodeMath(*this);
1289
1290         // validate the buffer.
1291         LYXERR(Debug::LATEX, "  Validating buffer...");
1292         LaTeXFeatures features(*this, params(), runparams);
1293         validate(features);
1294         LYXERR(Debug::LATEX, "  Buffer validation done.");
1295
1296         // The starting paragraph of the coming rows is the
1297         // first paragraph of the document. (Asger)
1298         if (output_preamble && runparams.nice) {
1299                 os << "%% LyX " << lyx_version << " created this file.  "
1300                         "For more info, see http://www.lyx.org/.\n"
1301                         "%% Do not edit unless you really know what "
1302                         "you are doing.\n";
1303                 d->texrow.newline();
1304                 d->texrow.newline();
1305         }
1306         LYXERR(Debug::INFO, "lyx document header finished");
1307
1308         // Don't move this behind the parent_buffer=0 code below,
1309         // because then the macros will not get the right "redefinition"
1310         // flag as they don't see the parent macros which are output before.
1311         updateMacros();
1312
1313         // fold macros if possible, still with parent buffer as the
1314         // macros will be put in the prefix anyway.
1315         updateMacroInstances();
1316
1317         // There are a few differences between nice LaTeX and usual files:
1318         // usual is \batchmode and has a
1319         // special input@path to allow the including of figures
1320         // with either \input or \includegraphics (what figinsets do).
1321         // input@path is set when the actual parameter
1322         // original_path is set. This is done for usual tex-file, but not
1323         // for nice-latex-file. (Matthias 250696)
1324         // Note that input@path is only needed for something the user does
1325         // in the preamble, included .tex files or ERT, files included by
1326         // LyX work without it.
1327         if (output_preamble) {
1328                 if (!runparams.nice) {
1329                         // code for usual, NOT nice-latex-file
1330                         os << "\\batchmode\n"; // changed
1331                         // from \nonstopmode
1332                         d->texrow.newline();
1333                 }
1334                 if (!original_path.empty()) {
1335                         // FIXME UNICODE
1336                         // We don't know the encoding of inputpath
1337                         docstring const inputpath = from_utf8(support::latex_path(original_path));
1338                         docstring uncodable_glyphs;
1339                         Encoding const * const enc = runparams.encoding;
1340                         if (enc) {
1341                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1342                                         docstring const glyph =
1343                                                 docstring(1, inputpath[n]);
1344                                         if (enc->latexChar(inputpath[n], true) != glyph) {
1345                                                 LYXERR0("Uncodable character '"
1346                                                         << glyph
1347                                                         << "' in input path!");
1348                                                 uncodable_glyphs += glyph;
1349                                         }
1350                                 }
1351                         }
1352
1353                         // warn user if we found uncodable glyphs.
1354                         if (!uncodable_glyphs.empty()) {
1355                                 frontend::Alert::warning(_("Uncodable character in file path"),
1356                                                 support::bformat(_("The path of your document\n"
1357                                                   "(%1$s)\n"
1358                                                   "contains glyphs that are unknown in the\n"
1359                                                   "current document encoding (namely %2$s).\n"
1360                                                   "This will likely result in incomplete output.\n\n"
1361                                                   "Choose an appropriate document encoding (such as utf8)\n"
1362                                                   "or change the file path name."), inputpath, uncodable_glyphs));
1363                         } else {
1364                                 os << "\\makeatletter\n"
1365                                    << "\\def\\input@path{{"
1366                                    << inputpath << "/}}\n"
1367                                    << "\\makeatother\n";
1368                                 d->texrow.newline();
1369                                 d->texrow.newline();
1370                                 d->texrow.newline();
1371                         }
1372                 }
1373
1374                 // get parent macros (if this buffer has a parent) which will be
1375                 // written at the document begin further down.
1376                 MacroSet parentMacros;
1377                 listParentMacros(parentMacros, features);
1378
1379                 // Write the preamble
1380                 runparams.use_babel = params().writeLaTeX(os, features,
1381                                                           d->texrow,
1382                                                           d->filename.onlyPath());
1383
1384                 runparams.use_japanese = features.isRequired("japanese");
1385
1386                 if (!output_body)
1387                         return;
1388
1389                 // make the body.
1390                 os << "\\begin{document}\n";
1391                 d->texrow.newline();
1392
1393                 // output the parent macros
1394                 MacroSet::iterator it = parentMacros.begin();
1395                 MacroSet::iterator end = parentMacros.end();
1396                 for (; it != end; ++it) {
1397                         int num_lines = (*it)->write(os, true);
1398                         d->texrow.newlines(num_lines);
1399                 }
1400                 
1401         } // output_preamble
1402
1403         d->texrow.start(paragraphs().begin()->id(), 0);
1404
1405         LYXERR(Debug::INFO, "preamble finished, now the body.");
1406
1407         // if we are doing a real file with body, even if this is the
1408         // child of some other buffer, let's cut the link here.
1409         // This happens for example if only a child document is printed.
1410         Buffer const * save_parent = 0;
1411         if (output_preamble) {
1412                 save_parent = d->parent();
1413                 d->setParent(0);
1414         }
1415
1416         // the real stuff
1417         latexParagraphs(*this, text(), os, d->texrow, runparams);
1418
1419         // Restore the parenthood if needed
1420         if (output_preamble)
1421                 d->setParent(save_parent);
1422
1423         // add this just in case after all the paragraphs
1424         os << endl;
1425         d->texrow.newline();
1426
1427         if (output_preamble) {
1428                 os << "\\end{document}\n";
1429                 d->texrow.newline();
1430                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1431         } else {
1432                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1433         }
1434         runparams_in.encoding = runparams.encoding;
1435
1436         // Just to be sure. (Asger)
1437         d->texrow.newline();
1438
1439         //for (int i = 0; i<d->texrow.rows(); i++) {
1440         // int id,pos;
1441         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1442         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1443         //}
1444
1445         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1446         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1447 }
1448
1449
1450 bool Buffer::isLatex() const
1451 {
1452         return params().documentClass().outputType() == LATEX;
1453 }
1454
1455
1456 bool Buffer::isLiterate() const
1457 {
1458         return params().documentClass().outputType() == LITERATE;
1459 }
1460
1461
1462 bool Buffer::isDocBook() const
1463 {
1464         return params().documentClass().outputType() == DOCBOOK;
1465 }
1466
1467
1468 void Buffer::makeDocBookFile(FileName const & fname,
1469                               OutputParams const & runparams,
1470                               bool const body_only) const
1471 {
1472         LYXERR(Debug::LATEX, "makeDocBookFile...");
1473
1474         ofdocstream ofs;
1475         if (!openFileWrite(ofs, fname))
1476                 return;
1477
1478         writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1479
1480         ofs.close();
1481         if (ofs.fail())
1482                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1483 }
1484
1485
1486 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1487                              OutputParams const & runparams,
1488                              bool const only_body) const
1489 {
1490         LaTeXFeatures features(*this, params(), runparams);
1491         validate(features);
1492
1493         d->texrow.reset();
1494
1495         DocumentClass const & tclass = params().documentClass();
1496         string const top_element = tclass.latexname();
1497
1498         if (!only_body) {
1499                 if (runparams.flavor == OutputParams::XML)
1500                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1501
1502                 // FIXME UNICODE
1503                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1504
1505                 // FIXME UNICODE
1506                 if (! tclass.class_header().empty())
1507                         os << from_ascii(tclass.class_header());
1508                 else if (runparams.flavor == OutputParams::XML)
1509                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1510                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1511                 else
1512                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1513
1514                 docstring preamble = from_utf8(params().preamble);
1515                 if (runparams.flavor != OutputParams::XML ) {
1516                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1517                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1518                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1519                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1520                 }
1521
1522                 string const name = runparams.nice
1523                         ? changeExtension(absFileName(), ".sgml") : fname;
1524                 preamble += features.getIncludedFiles(name);
1525                 preamble += features.getLyXSGMLEntities();
1526
1527                 if (!preamble.empty()) {
1528                         os << "\n [ " << preamble << " ]";
1529                 }
1530                 os << ">\n\n";
1531         }
1532
1533         string top = top_element;
1534         top += " lang=\"";
1535         if (runparams.flavor == OutputParams::XML)
1536                 top += params().language->code();
1537         else
1538                 top += params().language->code().substr(0, 2);
1539         top += '"';
1540
1541         if (!params().options.empty()) {
1542                 top += ' ';
1543                 top += params().options;
1544         }
1545
1546         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1547             << " file was created by LyX " << lyx_version
1548             << "\n  See http://www.lyx.org/ for more information -->\n";
1549
1550         params().documentClass().counters().reset();
1551
1552         updateMacros();
1553
1554         sgml::openTag(os, top);
1555         os << '\n';
1556         docbookParagraphs(text(), *this, os, runparams);
1557         sgml::closeTag(os, top_element);
1558 }
1559
1560
1561 void Buffer::makeLyXHTMLFile(FileName const & fname,
1562                               OutputParams const & runparams,
1563                               bool const body_only) const
1564 {
1565         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1566
1567         ofdocstream ofs;
1568         if (!openFileWrite(ofs, fname))
1569                 return;
1570
1571         writeLyXHTMLSource(ofs, runparams, body_only);
1572
1573         ofs.close();
1574         if (ofs.fail())
1575                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1576 }
1577
1578
1579 void Buffer::writeLyXHTMLSource(odocstream & os,
1580                              OutputParams const & runparams,
1581                              bool const only_body) const
1582 {
1583         LaTeXFeatures features(*this, params(), runparams);
1584         validate(features);
1585         updateBuffer(UpdateMaster, OutputUpdate);
1586         d->bibinfo_.makeCitationLabels(*this);
1587         updateMacros();
1588         updateMacroInstances();
1589
1590         if (!only_body) {
1591                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1592                    << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1593                    // FIXME Language should be set properly.
1594                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1595                    << "<head>\n"
1596                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1597                    // FIXME Presumably need to set this right
1598                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1599
1600                 docstring const & doctitle = features.htmlTitle();
1601                 os << "<title>"
1602                    << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1603                    << "</title>\n";
1604
1605                 os << "\n<!-- Text Class Preamble -->\n"
1606                    << features.getTClassHTMLPreamble()
1607                    << "\n<!-- Premable Snippets -->\n"
1608                    << from_utf8(features.getPreambleSnippets());
1609
1610                 os << "\n<!-- Layout-provided Styles -->\n";
1611                 docstring const styleinfo = features.getTClassHTMLStyles();
1612                 if (!styleinfo.empty()) {
1613                         os << "<style type='text/css'>\n"
1614                                 << styleinfo
1615                                 << "</style>\n";
1616                 }
1617                 os << "</head>\n<body>\n";
1618         }
1619
1620         XHTMLStream xs(os);
1621         params().documentClass().counters().reset();
1622         xhtmlParagraphs(text(), *this, xs, runparams);
1623         if (!only_body)
1624                 os << "</body>\n</html>\n";
1625 }
1626
1627
1628 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1629 // Other flags: -wall -v0 -x
1630 int Buffer::runChktex()
1631 {
1632         setBusy(true);
1633
1634         // get LaTeX-Filename
1635         FileName const path(temppath());
1636         string const name = addName(path.absFileName(), latexName());
1637         string const org_path = filePath();
1638
1639         PathChanger p(path); // path to LaTeX file
1640         message(_("Running chktex..."));
1641
1642         // Generate the LaTeX file if neccessary
1643         OutputParams runparams(&params().encoding());
1644         runparams.flavor = OutputParams::LATEX;
1645         runparams.nice = false;
1646         runparams.linelen = lyxrc.plaintext_linelen;
1647         makeLaTeXFile(FileName(name), org_path, runparams);
1648
1649         TeXErrors terr;
1650         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1651         int const res = chktex.run(terr); // run chktex
1652
1653         if (res == -1) {
1654                 Alert::error(_("chktex failure"),
1655                              _("Could not run chktex successfully."));
1656         } else if (res > 0) {
1657                 ErrorList & errlist = d->errorLists["ChkTeX"];
1658                 errlist.clear();
1659                 bufferErrors(terr, errlist);
1660         }
1661
1662         setBusy(false);
1663
1664         errors("ChkTeX");
1665
1666         return res;
1667 }
1668
1669
1670 void Buffer::validate(LaTeXFeatures & features) const
1671 {
1672         params().validate(features);
1673
1674         updateMacros();
1675
1676         for_each(paragraphs().begin(), paragraphs().end(),
1677                  bind(&Paragraph::validate, _1, ref(features)));
1678
1679         if (lyxerr.debugging(Debug::LATEX)) {
1680                 features.showStruct();
1681         }
1682 }
1683
1684
1685 void Buffer::getLabelList(vector<docstring> & list) const
1686 {
1687         // If this is a child document, use the master's list instead.
1688         if (parent()) {
1689                 masterBuffer()->getLabelList(list);
1690                 return;
1691         }
1692
1693         list.clear();
1694         Toc & toc = d->toc_backend.toc("label");
1695         TocIterator toc_it = toc.begin();
1696         TocIterator end = toc.end();
1697         for (; toc_it != end; ++toc_it) {
1698                 if (toc_it->depth() == 0)
1699                         list.push_back(toc_it->str());
1700         }
1701 }
1702
1703
1704 void Buffer::updateBibfilesCache(UpdateScope scope) const
1705 {
1706         // FIXME This is probably unnecssary, given where we call this.
1707         // If this is a child document, use the parent's cache instead.
1708         if (parent() && scope != UpdateChildOnly) {
1709                 masterBuffer()->updateBibfilesCache();
1710                 return;
1711         }
1712
1713         d->bibfiles_cache_.clear();
1714         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1715                 if (it->lyxCode() == BIBTEX_CODE) {
1716                         InsetBibtex const & inset =
1717                                 static_cast<InsetBibtex const &>(*it);
1718                         support::FileNameList const bibfiles = inset.getBibFiles();
1719                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1720                                 bibfiles.begin(),
1721                                 bibfiles.end());
1722                 } else if (it->lyxCode() == INCLUDE_CODE) {
1723                         InsetInclude & inset =
1724                                 static_cast<InsetInclude &>(*it);
1725                         Buffer const * const incbuf = inset.getChildBuffer();
1726                         if (!incbuf)
1727                                 continue;
1728                         support::FileNameList const & bibfiles =
1729                                         incbuf->getBibfilesCache(UpdateChildOnly);
1730                         if (!bibfiles.empty()) {
1731                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1732                                         bibfiles.begin(),
1733                                         bibfiles.end());
1734                         }
1735                 }
1736         }
1737         d->bibfile_cache_valid_ = true;
1738         d->bibinfo_cache_valid_ = false;
1739 }
1740
1741
1742 void Buffer::invalidateBibinfoCache() const
1743 {
1744         d->bibinfo_cache_valid_ = false;
1745         // also invalidate the cache for the parent buffer
1746         Buffer const * const pbuf = d->parent();
1747         if (pbuf)
1748                 pbuf->invalidateBibinfoCache();
1749 }
1750
1751
1752 void Buffer::invalidateBibfileCache() const
1753 {
1754         d->bibfile_cache_valid_ = false;
1755         d->bibinfo_cache_valid_ = false;
1756         // also invalidate the cache for the parent buffer
1757         Buffer const * const pbuf = d->parent();
1758         if (pbuf)
1759                 pbuf->invalidateBibfileCache();
1760 }
1761
1762
1763 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1764 {
1765         // FIXME This is probably unnecessary, given where we call this.
1766         // If this is a child document, use the master's cache instead.
1767         Buffer const * const pbuf = masterBuffer();
1768         if (pbuf != this && scope != UpdateChildOnly)
1769                 return pbuf->getBibfilesCache();
1770
1771         if (!d->bibfile_cache_valid_)
1772                 this->updateBibfilesCache(scope);
1773
1774         return d->bibfiles_cache_;
1775 }
1776
1777
1778 BiblioInfo const & Buffer::masterBibInfo() const
1779 {
1780         Buffer const * const tmp = masterBuffer();
1781         if (tmp != this)
1782                 return tmp->masterBibInfo();
1783         return d->bibinfo_;
1784 }
1785
1786
1787 void Buffer::checkBibInfoCache() const 
1788 {
1789         // use the master's cache
1790         Buffer const * const tmp = masterBuffer();
1791         if (tmp != this) {
1792                 tmp->checkBibInfoCache();
1793                 return;
1794         }
1795
1796         // this will also reload the cache if it is invalid 
1797         support::FileNameList const & bibfiles_cache = getBibfilesCache();
1798         
1799         // compare the cached timestamps with the actual ones.
1800         support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1801         support::FileNameList::const_iterator en = bibfiles_cache.end();
1802         for (; ei != en; ++ ei) {
1803                 time_t lastw = ei->lastModified();
1804                 time_t prevw = d->bibfile_status_[*ei];
1805                 if (lastw != prevw) {
1806                         d->bibinfo_cache_valid_ = false;
1807                         d->bibfile_status_[*ei] = lastw;
1808                 }
1809         }
1810         
1811         // if not valid, then reload the info
1812         if (!d->bibinfo_cache_valid_) {
1813                 d->bibinfo_.clear();
1814                 fillWithBibKeys(d->bibinfo_);
1815                 d->bibinfo_cache_valid_ = true;
1816         }
1817 }
1818
1819
1820 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1821 {
1822         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1823                 it->fillWithBibKeys(keys, it);
1824 }
1825
1826
1827 bool Buffer::isDepClean(string const & name) const
1828 {
1829         DepClean::const_iterator const it = d->dep_clean.find(name);
1830         if (it == d->dep_clean.end())
1831                 return true;
1832         return it->second;
1833 }
1834
1835
1836 void Buffer::markDepClean(string const & name)
1837 {
1838         d->dep_clean[name] = true;
1839 }
1840
1841
1842 bool Buffer::isExportableFormat(string const & format) const
1843 {
1844                 typedef vector<Format const *> Formats;
1845                 Formats formats;
1846                 formats = exportableFormats(true);
1847                 Formats::const_iterator fit = formats.begin();
1848                 Formats::const_iterator end = formats.end();
1849                 for (; fit != end ; ++fit) {
1850                         if ((*fit)->name() == format)
1851                                 return true;
1852                 }
1853                 return false;
1854 }
1855
1856
1857 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1858 {
1859         if (isInternal()) {
1860                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1861                 // if internal, put a switch '(cmd.action)' here.
1862                 return false;
1863         }
1864
1865         bool enable = true;
1866
1867         switch (cmd.action()) {
1868
1869                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1870                         flag.setOnOff(isReadonly());
1871                         break;
1872
1873                 // FIXME: There is need for a command-line import.
1874                 //case LFUN_BUFFER_IMPORT:
1875
1876                 case LFUN_BUFFER_AUTO_SAVE:
1877                         break;
1878
1879                 case LFUN_BUFFER_EXPORT_CUSTOM:
1880                         // FIXME: Nothing to check here?
1881                         break;
1882
1883                 case LFUN_BUFFER_EXPORT: {
1884                         docstring const arg = cmd.argument();
1885                         enable = arg == "custom" || isExportable(to_utf8(arg));
1886                         if (!enable)
1887                                 flag.message(bformat(
1888                                         _("Don't know how to export to format: %1$s"), arg));
1889                         break;
1890                 }
1891
1892                 case LFUN_BUFFER_CHKTEX:
1893                         enable = isLatex() && !lyxrc.chktex_command.empty();
1894                         break;
1895
1896                 case LFUN_BUILD_PROGRAM:
1897                         enable = isExportable("program");
1898                         break;
1899
1900                 case LFUN_BRANCH_ACTIVATE: 
1901                 case LFUN_BRANCH_DEACTIVATE: {
1902                         BranchList const & branchList = params().branchlist();
1903                         docstring const branchName = cmd.argument();
1904                         enable = !branchName.empty() && branchList.find(branchName);
1905                         break;
1906                 }
1907
1908                 case LFUN_BRANCH_ADD:
1909                 case LFUN_BRANCHES_RENAME:
1910                 case LFUN_BUFFER_PRINT:
1911                         // if no Buffer is present, then of course we won't be called!
1912                         break;
1913
1914                 case LFUN_BUFFER_LANGUAGE:
1915                         enable = !isReadonly();
1916                         break;
1917
1918                 default:
1919                         return false;
1920         }
1921         flag.setEnabled(enable);
1922         return true;
1923 }
1924
1925
1926 void Buffer::dispatch(string const & command, DispatchResult & result)
1927 {
1928         return dispatch(lyxaction.lookupFunc(command), result);
1929 }
1930
1931
1932 // NOTE We can end up here even if we have no GUI, because we are called
1933 // by LyX::exec to handled command-line requests. So we may need to check 
1934 // whether we have a GUI or not. The boolean use_gui holds this information.
1935 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1936 {
1937         if (isInternal()) {
1938                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1939                 // if internal, put a switch '(cmd.action())' here.
1940                 dr.dispatched(false);
1941                 return;
1942         }
1943         string const argument = to_utf8(func.argument());
1944         // We'll set this back to false if need be.
1945         bool dispatched = true;
1946         undo().beginUndoGroup();
1947
1948         switch (func.action()) {
1949         case LFUN_BUFFER_TOGGLE_READ_ONLY:
1950                 if (lyxvc().inUse())
1951                         lyxvc().toggleReadOnly();
1952                 else
1953                         setReadonly(!isReadonly());
1954                 break;
1955
1956         case LFUN_BUFFER_EXPORT: {
1957                 bool success = doExport(argument, false, false);
1958                 dr.setError(!success);
1959                 if (!success)
1960                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1961                                               func.argument()));
1962                 break;
1963         }
1964
1965         case LFUN_BUILD_PROGRAM:
1966                 doExport("program", true, false);
1967                 break;
1968
1969         case LFUN_BUFFER_CHKTEX:
1970                 runChktex();
1971                 break;
1972
1973         case LFUN_BUFFER_EXPORT_CUSTOM: {
1974                 string format_name;
1975                 string command = split(argument, format_name, ' ');
1976                 Format const * format = formats.getFormat(format_name);
1977                 if (!format) {
1978                         lyxerr << "Format \"" << format_name
1979                                 << "\" not recognized!"
1980                                 << endl;
1981                         break;
1982                 }
1983
1984                 // The name of the file created by the conversion process
1985                 string filename;
1986
1987                 // Output to filename
1988                 if (format->name() == "lyx") {
1989                         string const latexname = latexName(false);
1990                         filename = changeExtension(latexname,
1991                                 format->extension());
1992                         filename = addName(temppath(), filename);
1993
1994                         if (!writeFile(FileName(filename)))
1995                                 break;
1996
1997                 } else {
1998                         doExport(format_name, true, false, filename);
1999                 }
2000
2001                 // Substitute $$FName for filename
2002                 if (!contains(command, "$$FName"))
2003                         command = "( " + command + " ) < $$FName";
2004                 command = subst(command, "$$FName", filename);
2005
2006                 // Execute the command in the background
2007                 Systemcall call;
2008                 call.startscript(Systemcall::DontWait, command);
2009                 break;
2010         }
2011
2012         // FIXME: There is need for a command-line import.
2013         /*
2014         case LFUN_BUFFER_IMPORT:
2015                 doImport(argument);
2016                 break;
2017         */
2018
2019         case LFUN_BUFFER_AUTO_SAVE:
2020                 autoSave();
2021                 break;
2022
2023         case LFUN_BRANCH_ADD: {
2024                 docstring branch_name = func.argument();
2025                 if (branch_name.empty()) {
2026                         dispatched = false;
2027                         break;
2028                 }
2029                 BranchList & branch_list = params().branchlist();
2030                 vector<docstring> const branches =
2031                         getVectorFromString(branch_name, branch_list.separator());
2032                 docstring msg;
2033                 for (vector<docstring>::const_iterator it = branches.begin();
2034                      it != branches.end(); ++it) {
2035                         branch_name = *it;
2036                         Branch * branch = branch_list.find(branch_name);
2037                         if (branch) {
2038                                 LYXERR0("Branch " << branch_name << " already exists.");
2039                                 dr.setError(true);
2040                                 if (!msg.empty())
2041                                         msg += ("\n");
2042                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2043                         } else {
2044                                 branch_list.add(branch_name);
2045                                 branch = branch_list.find(branch_name);
2046                                 string const x11hexname = X11hexname(branch->color());
2047                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2048                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2049                                 dr.setError(false);
2050                                 dr.screenUpdate(Update::Force);
2051                         }
2052                 }
2053                 if (!msg.empty())
2054                         dr.setMessage(msg);
2055                 break;
2056         }
2057
2058         case LFUN_BRANCH_ACTIVATE:
2059         case LFUN_BRANCH_DEACTIVATE: {
2060                 BranchList & branchList = params().branchlist();
2061                 docstring const branchName = func.argument();
2062                 // the case without a branch name is handled elsewhere
2063                 if (branchName.empty()) {
2064                         dispatched = false;
2065                         break;
2066                 }
2067                 Branch * branch = branchList.find(branchName);
2068                 if (!branch) {
2069                         LYXERR0("Branch " << branchName << " does not exist.");
2070                         dr.setError(true);
2071                         docstring const msg = 
2072                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2073                         dr.setMessage(msg);
2074                 } else {
2075                         branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2076                         dr.setError(false);
2077                         dr.screenUpdate(Update::Force);
2078                         dr.forceBufferUpdate();
2079                 }
2080                 break;
2081         }
2082
2083         case LFUN_BRANCHES_RENAME: {
2084                 if (func.argument().empty())
2085                         break;
2086
2087                 docstring const oldname = from_utf8(func.getArg(0));
2088                 docstring const newname = from_utf8(func.getArg(1));
2089                 InsetIterator it  = inset_iterator_begin(inset());
2090                 InsetIterator const end = inset_iterator_end(inset());
2091                 bool success = false;
2092                 for (; it != end; ++it) {
2093                         if (it->lyxCode() == BRANCH_CODE) {
2094                                 InsetBranch & ins = dynamic_cast<InsetBranch &>(*it);
2095                                 if (ins.branch() == oldname) {
2096                                         undo().recordUndo(it);
2097                                         ins.rename(newname);
2098                                         success = true;
2099                                         continue;
2100                                 }
2101                         }
2102                         if (it->lyxCode() == INCLUDE_CODE) {
2103                                 // get buffer of external file
2104                                 InsetInclude const & ins =
2105                                         static_cast<InsetInclude const &>(*it);
2106                                 Buffer * child = ins.getChildBuffer();
2107                                 if (!child)
2108                                         continue;
2109                                 child->dispatch(func, dr);
2110                         }
2111                 }
2112
2113                 if (success) {
2114                         dr.screenUpdate(Update::Force);
2115                         dr.forceBufferUpdate();
2116                 }
2117                 break;
2118         }
2119
2120         case LFUN_BUFFER_PRINT: {
2121                 // we'll assume there's a problem until we succeed
2122                 dr.setError(true); 
2123                 string target = func.getArg(0);
2124                 string target_name = func.getArg(1);
2125                 string command = func.getArg(2);
2126
2127                 if (target.empty()
2128                     || target_name.empty()
2129                     || command.empty()) {
2130                         LYXERR0("Unable to parse " << func.argument());
2131                         docstring const msg = 
2132                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2133                         dr.setMessage(msg);
2134                         break;
2135                 }
2136                 if (target != "printer" && target != "file") {
2137                         LYXERR0("Unrecognized target \"" << target << '"');
2138                         docstring const msg = 
2139                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2140                         dr.setMessage(msg);
2141                         break;
2142                 }
2143
2144                 bool const update_unincluded =
2145                                 params().maintain_unincluded_children
2146                                 && !params().getIncludedChildren().empty();
2147                 if (!doExport("dvi", true, update_unincluded)) {
2148                         showPrintError(absFileName());
2149                         dr.setMessage(_("Error exporting to DVI."));
2150                         break;
2151                 }
2152
2153                 // Push directory path.
2154                 string const path = temppath();
2155                 // Prevent the compiler from optimizing away p
2156                 FileName pp(path);
2157                 PathChanger p(pp);
2158
2159                 // there are three cases here:
2160                 // 1. we print to a file
2161                 // 2. we print directly to a printer
2162                 // 3. we print using a spool command (print to file first)
2163                 Systemcall one;
2164                 int res = 0;
2165                 string const dviname = changeExtension(latexName(true), "dvi");
2166
2167                 if (target == "printer") {
2168                         if (!lyxrc.print_spool_command.empty()) {
2169                                 // case 3: print using a spool
2170                                 string const psname = changeExtension(dviname,".ps");
2171                                 command += ' ' + lyxrc.print_to_file
2172                                         + quoteName(psname)
2173                                         + ' '
2174                                         + quoteName(dviname);
2175
2176                                 string command2 = lyxrc.print_spool_command + ' ';
2177                                 if (target_name != "default") {
2178                                         command2 += lyxrc.print_spool_printerprefix
2179                                                 + target_name
2180                                                 + ' ';
2181                                 }
2182                                 command2 += quoteName(psname);
2183                                 // First run dvips.
2184                                 // If successful, then spool command
2185                                 res = one.startscript(Systemcall::Wait, command);
2186
2187                                 if (res == 0) {
2188                                         // If there's no GUI, we have to wait on this command. Otherwise,
2189                                         // LyX deletes the temporary directory, and with it the spooled
2190                                         // file, before it can be printed!!
2191                                         Systemcall::Starttype stype = use_gui ?
2192                                                 Systemcall::DontWait : Systemcall::Wait;
2193                                         res = one.startscript(stype, command2);
2194                                 }
2195                         } else {
2196                                 // case 2: print directly to a printer
2197                                 if (target_name != "default")
2198                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2199                                 // as above....
2200                                 Systemcall::Starttype stype = use_gui ?
2201                                         Systemcall::DontWait : Systemcall::Wait;
2202                                 res = one.startscript(stype, command + quoteName(dviname));
2203                         }
2204
2205                 } else {
2206                         // case 1: print to a file
2207                         FileName const filename(makeAbsPath(target_name, filePath()));
2208                         FileName const dvifile(makeAbsPath(dviname, path));
2209                         if (filename.exists()) {
2210                                 docstring text = bformat(
2211                                         _("The file %1$s already exists.\n\n"
2212                                           "Do you want to overwrite that file?"),
2213                                         makeDisplayPath(filename.absFileName()));
2214                                 if (Alert::prompt(_("Overwrite file?"),
2215                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2216                                         break;
2217                         }
2218                         command += ' ' + lyxrc.print_to_file
2219                                 + quoteName(filename.toFilesystemEncoding())
2220                                 + ' '
2221                                 + quoteName(dvifile.toFilesystemEncoding());
2222                         // as above....
2223                         Systemcall::Starttype stype = use_gui ?
2224                                 Systemcall::DontWait : Systemcall::Wait;
2225                         res = one.startscript(stype, command);
2226                 }
2227
2228                 if (res == 0) 
2229                         dr.setError(false);
2230                 else {
2231                         dr.setMessage(_("Error running external commands."));
2232                         showPrintError(absFileName());
2233                 }
2234                 break;
2235         }
2236
2237         case LFUN_BUFFER_LANGUAGE: {
2238                 Language const * oldL = params().language;
2239                 Language const * newL = languages.getLanguage(argument);
2240                 if (!newL || oldL == newL)
2241                         break;
2242                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2243                         changeLanguage(oldL, newL);
2244                         dr.forceBufferUpdate();
2245                 }
2246                 break;
2247         }
2248
2249         default:
2250                 dispatched = false;
2251                 break;
2252         }
2253         dr.dispatched(dispatched);
2254         undo().endUndoGroup();
2255 }
2256
2257
2258 void Buffer::changeLanguage(Language const * from, Language const * to)
2259 {
2260         LASSERT(from, /**/);
2261         LASSERT(to, /**/);
2262
2263         for_each(par_iterator_begin(),
2264                  par_iterator_end(),
2265                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2266 }
2267
2268
2269 bool Buffer::isMultiLingual() const
2270 {
2271         ParConstIterator end = par_iterator_end();
2272         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2273                 if (it->isMultiLingual(params()))
2274                         return true;
2275
2276         return false;
2277 }
2278
2279
2280 std::set<Language const *> Buffer::getLanguages() const
2281 {
2282         std::set<Language const *> languages;
2283         getLanguages(languages);
2284         return languages;
2285 }
2286
2287
2288 void Buffer::getLanguages(std::set<Language const *> & languages) const
2289 {
2290         ParConstIterator end = par_iterator_end();
2291         // add the buffer language, even if it's not actively used
2292         languages.insert(language());
2293         // iterate over the paragraphs
2294         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2295                 it->getLanguages(languages);
2296         // also children
2297         ListOfBuffers clist = getDescendents();
2298         ListOfBuffers::const_iterator cit = clist.begin();
2299         ListOfBuffers::const_iterator const cen = clist.end();
2300         for (; cit != cen; ++cit)
2301                 (*cit)->getLanguages(languages);
2302 }
2303
2304
2305 DocIterator Buffer::getParFromID(int const id) const
2306 {
2307         Buffer * buf = const_cast<Buffer *>(this);
2308         if (id < 0) {
2309                 // John says this is called with id == -1 from undo
2310                 lyxerr << "getParFromID(), id: " << id << endl;
2311                 return doc_iterator_end(buf);
2312         }
2313
2314         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2315                 if (it.paragraph().id() == id)
2316                         return it;
2317
2318         return doc_iterator_end(buf);
2319 }
2320
2321
2322 bool Buffer::hasParWithID(int const id) const
2323 {
2324         return !getParFromID(id).atEnd();
2325 }
2326
2327
2328 ParIterator Buffer::par_iterator_begin()
2329 {
2330         return ParIterator(doc_iterator_begin(this));
2331 }
2332
2333
2334 ParIterator Buffer::par_iterator_end()
2335 {
2336         return ParIterator(doc_iterator_end(this));
2337 }
2338
2339
2340 ParConstIterator Buffer::par_iterator_begin() const
2341 {
2342         return ParConstIterator(doc_iterator_begin(this));
2343 }
2344
2345
2346 ParConstIterator Buffer::par_iterator_end() const
2347 {
2348         return ParConstIterator(doc_iterator_end(this));
2349 }
2350
2351
2352 Language const * Buffer::language() const
2353 {
2354         return params().language;
2355 }
2356
2357
2358 docstring const Buffer::B_(string const & l10n) const
2359 {
2360         return params().B_(l10n);
2361 }
2362
2363
2364 bool Buffer::isClean() const
2365 {
2366         return d->lyx_clean;
2367 }
2368
2369
2370 bool Buffer::isExternallyModified(CheckMethod method) const
2371 {
2372         LASSERT(d->filename.exists(), /**/);
2373         // if method == timestamp, check timestamp before checksum
2374         return (method == checksum_method
2375                 || d->timestamp_ != d->filename.lastModified())
2376                 && d->checksum_ != d->filename.checksum();
2377 }
2378
2379
2380 void Buffer::saveCheckSum(FileName const & file) const
2381 {
2382         if (file.exists()) {
2383                 d->timestamp_ = file.lastModified();
2384                 d->checksum_ = file.checksum();
2385         } else {
2386                 // in the case of save to a new file.
2387                 d->timestamp_ = 0;
2388                 d->checksum_ = 0;
2389         }
2390 }
2391
2392
2393 void Buffer::markClean() const
2394 {
2395         if (!d->lyx_clean) {
2396                 d->lyx_clean = true;
2397                 updateTitles();
2398         }
2399         // if the .lyx file has been saved, we don't need an
2400         // autosave
2401         d->bak_clean = true;
2402         d->undo_.markDirty();
2403 }
2404
2405
2406 void Buffer::setUnnamed(bool flag)
2407 {
2408         d->unnamed = flag;
2409 }
2410
2411
2412 bool Buffer::isUnnamed() const
2413 {
2414         return d->unnamed;
2415 }
2416
2417
2418 /// \note
2419 /// Don't check unnamed, here: isInternal() is used in
2420 /// newBuffer(), where the unnamed flag has not been set by anyone
2421 /// yet. Also, for an internal buffer, there should be no need for
2422 /// retrieving fileName() nor for checking if it is unnamed or not.
2423 bool Buffer::isInternal() const
2424 {
2425         return fileName().extension() == "internal";
2426 }
2427
2428
2429 void Buffer::markDirty()
2430 {
2431         if (d->lyx_clean) {
2432                 d->lyx_clean = false;
2433                 updateTitles();
2434         }
2435         d->bak_clean = false;
2436
2437         DepClean::iterator it = d->dep_clean.begin();
2438         DepClean::const_iterator const end = d->dep_clean.end();
2439
2440         for (; it != end; ++it)
2441                 it->second = false;
2442 }
2443
2444
2445 FileName Buffer::fileName() const
2446 {
2447         return d->filename;
2448 }
2449
2450
2451 string Buffer::absFileName() const
2452 {
2453         return d->filename.absFileName();
2454 }
2455
2456
2457 string Buffer::filePath() const
2458 {
2459         return d->filename.onlyPath().absFileName() + "/";
2460 }
2461
2462
2463 bool Buffer::isReadonly() const
2464 {
2465         return d->read_only;
2466 }
2467
2468
2469 void Buffer::setParent(Buffer const * buffer)
2470 {
2471         // Avoids recursive include.
2472         d->setParent(buffer == this ? 0 : buffer);
2473         updateMacros();
2474 }
2475
2476
2477 Buffer const * Buffer::parent() const
2478 {
2479         return d->parent();
2480 }
2481
2482
2483 ListOfBuffers Buffer::allRelatives() const
2484 {
2485         ListOfBuffers lb = masterBuffer()->getDescendents();
2486         lb.push_front(const_cast<Buffer *>(this));
2487         return lb;
2488 }
2489
2490
2491 Buffer const * Buffer::masterBuffer() const
2492 {
2493         // FIXME Should be make sure we are not in some kind
2494         // of recursive include? A -> B -> A will crash this.
2495         Buffer const * const pbuf = d->parent();
2496         if (!pbuf)
2497                 return this;
2498
2499         return pbuf->masterBuffer();
2500 }
2501
2502
2503 bool Buffer::isChild(Buffer * child) const
2504 {
2505         return d->children_positions.find(child) != d->children_positions.end();
2506 }
2507
2508
2509 DocIterator Buffer::firstChildPosition(Buffer const * child)
2510 {
2511         Impl::BufferPositionMap::iterator it;
2512         it = d->children_positions.find(child);
2513         if (it == d->children_positions.end())
2514                 return DocIterator(this);
2515         return it->second;
2516 }
2517
2518
2519 bool Buffer::hasChildren() const
2520 {
2521         return !d->children_positions.empty();  
2522 }
2523
2524
2525 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2526 {
2527         // loop over children
2528         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2529         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2530         for (; it != end; ++it) {
2531                 Buffer * child = const_cast<Buffer *>(it->first);
2532                 // No duplicates
2533                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2534                 if (bit != clist.end())
2535                         continue;
2536                 clist.push_back(child);
2537                 if (grand_children) 
2538                         // there might be grandchildren
2539                         child->collectChildren(clist, true);
2540         }
2541 }
2542
2543
2544 ListOfBuffers Buffer::getChildren() const
2545 {
2546         ListOfBuffers v;
2547         collectChildren(v, false);
2548         return v;
2549 }
2550
2551
2552 ListOfBuffers Buffer::getDescendents() const
2553 {
2554         ListOfBuffers v;
2555         collectChildren(v, true);
2556         return v;
2557 }
2558
2559
2560 template<typename M>
2561 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2562 {
2563         if (m.empty())
2564                 return m.end();
2565
2566         typename M::const_iterator it = m.lower_bound(x);
2567         if (it == m.begin())
2568                 return m.end();
2569
2570         it--;
2571         return it;
2572 }
2573
2574
2575 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2576                                          DocIterator const & pos) const
2577 {
2578         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2579
2580         // if paragraphs have no macro context set, pos will be empty
2581         if (pos.empty())
2582                 return 0;
2583
2584         // we haven't found anything yet
2585         DocIterator bestPos = owner_->par_iterator_begin();
2586         MacroData const * bestData = 0;
2587
2588         // find macro definitions for name
2589         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2590         if (nameIt != macros.end()) {
2591                 // find last definition in front of pos or at pos itself
2592                 PositionScopeMacroMap::const_iterator it
2593                         = greatest_below(nameIt->second, pos);
2594                 if (it != nameIt->second.end()) {
2595                         while (true) {
2596                                 // scope ends behind pos?
2597                                 if (pos < it->second.first) {
2598                                         // Looks good, remember this. If there
2599                                         // is no external macro behind this,
2600                                         // we found the right one already.
2601                                         bestPos = it->first;
2602                                         bestData = &it->second.second;
2603                                         break;
2604                                 }
2605
2606                                 // try previous macro if there is one
2607                                 if (it == nameIt->second.begin())
2608                                         break;
2609                                 it--;
2610                         }
2611                 }
2612         }
2613
2614         // find macros in included files
2615         PositionScopeBufferMap::const_iterator it
2616                 = greatest_below(position_to_children, pos);
2617         if (it == position_to_children.end())
2618                 // no children before
2619                 return bestData;
2620
2621         while (true) {
2622                 // do we know something better (i.e. later) already?
2623                 if (it->first < bestPos )
2624                         break;
2625
2626                 // scope ends behind pos?
2627                 if (pos < it->second.first) {
2628                         // look for macro in external file
2629                         macro_lock = true;
2630                         MacroData const * data
2631                                 = it->second.second->getMacro(name, false);
2632                         macro_lock = false;
2633                         if (data) {
2634                                 bestPos = it->first;
2635                                 bestData = data;
2636                                 break;
2637                         }
2638                 }
2639
2640                 // try previous file if there is one
2641                 if (it == position_to_children.begin())
2642                         break;
2643                 --it;
2644         }
2645
2646         // return the best macro we have found
2647         return bestData;
2648 }
2649
2650
2651 MacroData const * Buffer::getMacro(docstring const & name,
2652         DocIterator const & pos, bool global) const
2653 {
2654         if (d->macro_lock)
2655                 return 0;
2656
2657         // query buffer macros
2658         MacroData const * data = d->getBufferMacro(name, pos);
2659         if (data != 0)
2660                 return data;
2661
2662         // If there is a master buffer, query that
2663         Buffer const * const pbuf = d->parent();
2664         if (pbuf) {
2665                 d->macro_lock = true;
2666                 MacroData const * macro = pbuf->getMacro(
2667                         name, *this, false);
2668                 d->macro_lock = false;
2669                 if (macro)
2670                         return macro;
2671         }
2672
2673         if (global) {
2674                 data = MacroTable::globalMacros().get(name);
2675                 if (data != 0)
2676                         return data;
2677         }
2678
2679         return 0;
2680 }
2681
2682
2683 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2684 {
2685         // set scope end behind the last paragraph
2686         DocIterator scope = par_iterator_begin();
2687         scope.pit() = scope.lastpit() + 1;
2688
2689         return getMacro(name, scope, global);
2690 }
2691
2692
2693 MacroData const * Buffer::getMacro(docstring const & name,
2694         Buffer const & child, bool global) const
2695 {
2696         // look where the child buffer is included first
2697         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2698         if (it == d->children_positions.end())
2699                 return 0;
2700
2701         // check for macros at the inclusion position
2702         return getMacro(name, it->second, global);
2703 }
2704
2705
2706 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2707 {
2708         pit_type const lastpit = it.lastpit();
2709
2710         // look for macros in each paragraph
2711         while (it.pit() <= lastpit) {
2712                 Paragraph & par = it.paragraph();
2713
2714                 // iterate over the insets of the current paragraph
2715                 InsetList const & insets = par.insetList();
2716                 InsetList::const_iterator iit = insets.begin();
2717                 InsetList::const_iterator end = insets.end();
2718                 for (; iit != end; ++iit) {
2719                         it.pos() = iit->pos;
2720
2721                         // is it a nested text inset?
2722                         if (iit->inset->asInsetText()) {
2723                                 // Inset needs its own scope?
2724                                 InsetText const * itext = iit->inset->asInsetText();
2725                                 bool newScope = itext->isMacroScope();
2726
2727                                 // scope which ends just behind the inset
2728                                 DocIterator insetScope = it;
2729                                 ++insetScope.pos();
2730
2731                                 // collect macros in inset
2732                                 it.push_back(CursorSlice(*iit->inset));
2733                                 updateMacros(it, newScope ? insetScope : scope);
2734                                 it.pop_back();
2735                                 continue;
2736                         }
2737                         
2738                         if (iit->inset->asInsetTabular()) {
2739                                 CursorSlice slice(*iit->inset);
2740                                 size_t const numcells = slice.nargs();
2741                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
2742                                         it.push_back(slice);
2743                                         updateMacros(it, scope);
2744                                         it.pop_back();
2745                                 }
2746                                 continue;
2747                         }
2748
2749                         // is it an external file?
2750                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2751                                 // get buffer of external file
2752                                 InsetInclude const & inset =
2753                                         static_cast<InsetInclude const &>(*iit->inset);
2754                                 macro_lock = true;
2755                                 Buffer * child = inset.getChildBuffer();
2756                                 macro_lock = false;
2757                                 if (!child)
2758                                         continue;
2759
2760                                 // register its position, but only when it is
2761                                 // included first in the buffer
2762                                 if (children_positions.find(child) ==
2763                                         children_positions.end())
2764                                                 children_positions[child] = it;
2765
2766                                 // register child with its scope
2767                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2768                                 continue;
2769                         }
2770
2771                         if (doing_export && iit->inset->asInsetMath()) {
2772                                 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2773                                 if (im->asHullInset()) {
2774                                         InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2775                                         hull->recordLocation(it);
2776                                 }
2777                         }
2778
2779                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2780                                 continue;
2781
2782                         // get macro data
2783                         MathMacroTemplate & macroTemplate =
2784                                 static_cast<MathMacroTemplate &>(*iit->inset);
2785                         MacroContext mc(owner_, it);
2786                         macroTemplate.updateToContext(mc);
2787
2788                         // valid?
2789                         bool valid = macroTemplate.validMacro();
2790                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2791                         // then the BufferView's cursor will be invalid in
2792                         // some cases which leads to crashes.
2793                         if (!valid)
2794                                 continue;
2795
2796                         // register macro
2797                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2798                         // instead of 'macroTemplate' defined above... is this correct?
2799                         macros[macroTemplate.name()][it] =
2800                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2801                 }
2802
2803                 // next paragraph
2804                 it.pit()++;
2805                 it.pos() = 0;
2806         }
2807 }
2808
2809
2810 void Buffer::updateMacros() const
2811 {
2812         if (d->macro_lock)
2813                 return;
2814
2815         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2816
2817         // start with empty table
2818         d->macros.clear();
2819         d->children_positions.clear();
2820         d->position_to_children.clear();
2821
2822         // Iterate over buffer, starting with first paragraph
2823         // The scope must be bigger than any lookup DocIterator
2824         // later. For the global lookup, lastpit+1 is used, hence
2825         // we use lastpit+2 here.
2826         DocIterator it = par_iterator_begin();
2827         DocIterator outerScope = it;
2828         outerScope.pit() = outerScope.lastpit() + 2;
2829         d->updateMacros(it, outerScope);
2830 }
2831
2832
2833 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2834 {
2835         InsetIterator it  = inset_iterator_begin(inset());
2836         InsetIterator const end = inset_iterator_end(inset());
2837         for (; it != end; ++it) {
2838                 if (it->lyxCode() == BRANCH_CODE) {
2839                         InsetBranch & br = dynamic_cast<InsetBranch &>(*it);
2840                         docstring const name = br.branch();
2841                         if (!from_master && !params().branchlist().find(name))
2842                                 result.push_back(name);
2843                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2844                                 result.push_back(name);
2845                         continue;
2846                 }
2847                 if (it->lyxCode() == INCLUDE_CODE) {
2848                         // get buffer of external file
2849                         InsetInclude const & ins =
2850                                 static_cast<InsetInclude const &>(*it);
2851                         Buffer * child = ins.getChildBuffer();
2852                         if (!child)
2853                                 continue;
2854                         child->getUsedBranches(result, true);
2855                 }
2856         }
2857         // remove duplicates
2858         result.unique();
2859 }
2860
2861
2862 void Buffer::updateMacroInstances() const
2863 {
2864         LYXERR(Debug::MACROS, "updateMacroInstances for "
2865                 << d->filename.onlyFileName());
2866         DocIterator it = doc_iterator_begin(this);
2867         it.forwardInset();
2868         DocIterator const end = doc_iterator_end(this);
2869         for (; it != end; it.forwardInset()) {
2870                 // look for MathData cells in InsetMathNest insets
2871                 InsetMath * minset = it.nextInset()->asInsetMath();
2872                 if (!minset)
2873                         continue;
2874
2875                 // update macro in all cells of the InsetMathNest
2876                 DocIterator::idx_type n = minset->nargs();
2877                 MacroContext mc = MacroContext(this, it);
2878                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2879                         MathData & data = minset->cell(i);
2880                         data.updateMacros(0, mc);
2881                 }
2882         }
2883 }
2884
2885
2886 void Buffer::listMacroNames(MacroNameSet & macros) const
2887 {
2888         if (d->macro_lock)
2889                 return;
2890
2891         d->macro_lock = true;
2892
2893         // loop over macro names
2894         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2895         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2896         for (; nameIt != nameEnd; ++nameIt)
2897                 macros.insert(nameIt->first);
2898
2899         // loop over children
2900         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2901         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2902         for (; it != end; ++it)
2903                 it->first->listMacroNames(macros);
2904
2905         // call parent
2906         Buffer const * const pbuf = d->parent();
2907         if (pbuf)
2908                 pbuf->listMacroNames(macros);
2909
2910         d->macro_lock = false;
2911 }
2912
2913
2914 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2915 {
2916         Buffer const * const pbuf = d->parent();
2917         if (!pbuf)
2918                 return;
2919
2920         MacroNameSet names;
2921         pbuf->listMacroNames(names);
2922
2923         // resolve macros
2924         MacroNameSet::iterator it = names.begin();
2925         MacroNameSet::iterator end = names.end();
2926         for (; it != end; ++it) {
2927                 // defined?
2928                 MacroData const * data =
2929                 pbuf->getMacro(*it, *this, false);
2930                 if (data) {
2931                         macros.insert(data);
2932
2933                         // we cannot access the original MathMacroTemplate anymore
2934                         // here to calls validate method. So we do its work here manually.
2935                         // FIXME: somehow make the template accessible here.
2936                         if (data->optionals() > 0)
2937                                 features.require("xargs");
2938                 }
2939         }
2940 }
2941
2942
2943 Buffer::References & Buffer::references(docstring const & label)
2944 {
2945         if (d->parent())
2946                 return const_cast<Buffer *>(masterBuffer())->references(label);
2947
2948         RefCache::iterator it = d->ref_cache_.find(label);
2949         if (it != d->ref_cache_.end())
2950                 return it->second.second;
2951
2952         static InsetLabel const * dummy_il = 0;
2953         static References const dummy_refs;
2954         it = d->ref_cache_.insert(
2955                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2956         return it->second.second;
2957 }
2958
2959
2960 Buffer::References const & Buffer::references(docstring const & label) const
2961 {
2962         return const_cast<Buffer *>(this)->references(label);
2963 }
2964
2965
2966 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2967 {
2968         masterBuffer()->d->ref_cache_[label].first = il;
2969 }
2970
2971
2972 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2973 {
2974         return masterBuffer()->d->ref_cache_[label].first;
2975 }
2976
2977
2978 void Buffer::clearReferenceCache() const
2979 {
2980         if (!d->parent())
2981                 d->ref_cache_.clear();
2982 }
2983
2984
2985 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2986         InsetCode code)
2987 {
2988         //FIXME: This does not work for child documents yet.
2989         LASSERT(code == CITE_CODE, /**/);
2990         // Check if the label 'from' appears more than once
2991         vector<docstring> labels;
2992         string paramName;
2993         checkBibInfoCache();
2994         BiblioInfo const & keys = masterBibInfo();
2995         BiblioInfo::const_iterator bit  = keys.begin();
2996         BiblioInfo::const_iterator bend = keys.end();
2997
2998         for (; bit != bend; ++bit)
2999                 // FIXME UNICODE
3000                 labels.push_back(bit->first);
3001         paramName = "key";
3002
3003         if (count(labels.begin(), labels.end(), from) > 1)
3004                 return;
3005
3006         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3007                 if (it->lyxCode() == code) {
3008                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
3009                         docstring const oldValue = inset.getParam(paramName);
3010                         if (oldValue == from)
3011                                 inset.setParam(paramName, to);
3012                 }
3013         }
3014 }
3015
3016
3017 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3018         pit_type par_end, bool full_source) const
3019 {
3020         OutputParams runparams(&params().encoding());
3021         runparams.nice = true;
3022         runparams.flavor = params().useXetex ? 
3023                 OutputParams::XETEX : OutputParams::LATEX;
3024         runparams.linelen = lyxrc.plaintext_linelen;
3025         // No side effect of file copying and image conversion
3026         runparams.dryrun = true;
3027
3028         if (full_source) {
3029                 os << "% " << _("Preview source code") << "\n\n";
3030                 d->texrow.reset();
3031                 d->texrow.newline();
3032                 d->texrow.newline();
3033                 if (isDocBook())
3034                         writeDocBookSource(os, absFileName(), runparams, false);
3035                 else
3036                         // latex or literate
3037                         writeLaTeXSource(os, string(), runparams, true, true);
3038         } else {
3039                 runparams.par_begin = par_begin;
3040                 runparams.par_end = par_end;
3041                 if (par_begin + 1 == par_end) {
3042                         os << "% "
3043                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3044                            << "\n\n";
3045                 } else {
3046                         os << "% "
3047                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3048                                         convert<docstring>(par_begin),
3049                                         convert<docstring>(par_end - 1))
3050                            << "\n\n";
3051                 }
3052                 TexRow texrow;
3053                 texrow.reset();
3054                 texrow.newline();
3055                 texrow.newline();
3056                 // output paragraphs
3057                 if (isDocBook())
3058                         docbookParagraphs(text(), *this, os, runparams);
3059                 else 
3060                         // latex or literate
3061                         latexParagraphs(*this, text(), os, texrow, runparams);
3062         }
3063 }
3064
3065
3066 ErrorList & Buffer::errorList(string const & type) const
3067 {
3068         static ErrorList emptyErrorList;
3069         map<string, ErrorList>::iterator it = d->errorLists.find(type);
3070         if (it == d->errorLists.end())
3071                 return emptyErrorList;
3072
3073         return it->second;
3074 }
3075
3076
3077 void Buffer::updateTocItem(std::string const & type,
3078         DocIterator const & dit) const
3079 {
3080         if (d->gui_)
3081                 d->gui_->updateTocItem(type, dit);
3082 }
3083
3084
3085 void Buffer::structureChanged() const
3086 {
3087         if (d->gui_)
3088                 d->gui_->structureChanged();
3089 }
3090
3091
3092 void Buffer::errors(string const & err, bool from_master) const
3093 {
3094         if (d->gui_)
3095                 d->gui_->errors(err, from_master);
3096 }
3097
3098
3099 void Buffer::message(docstring const & msg) const
3100 {
3101         if (d->gui_)
3102                 d->gui_->message(msg);
3103 }
3104
3105
3106 void Buffer::setBusy(bool on) const
3107 {
3108         if (d->gui_)
3109                 d->gui_->setBusy(on);
3110 }
3111
3112
3113 void Buffer::updateTitles() const
3114 {
3115         if (d->wa_)
3116                 d->wa_->updateTitles();
3117 }
3118
3119
3120 void Buffer::resetAutosaveTimers() const
3121 {
3122         if (d->gui_)
3123                 d->gui_->resetAutosaveTimers();
3124 }
3125
3126
3127 bool Buffer::hasGuiDelegate() const
3128 {
3129         return d->gui_;
3130 }
3131
3132
3133 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3134 {
3135         d->gui_ = gui;
3136 }
3137
3138
3139
3140 namespace {
3141
3142 class AutoSaveBuffer : public ForkedProcess {
3143 public:
3144         ///
3145         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3146                 : buffer_(buffer), fname_(fname) {}
3147         ///
3148         virtual shared_ptr<ForkedProcess> clone() const
3149         {
3150                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3151         }
3152         ///
3153         int start()
3154         {
3155                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3156                                                  from_utf8(fname_.absFileName())));
3157                 return run(DontWait);
3158         }
3159 private:
3160         ///
3161         virtual int generateChild();
3162         ///
3163         Buffer const & buffer_;
3164         FileName fname_;
3165 };
3166
3167
3168 int AutoSaveBuffer::generateChild()
3169 {
3170 #if defined(__APPLE__)
3171         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3172          *   We should use something else like threads.
3173          *
3174          * Since I do not know how to determine at run time what is the OS X
3175          * version, I just disable forking altogether for now (JMarc)
3176          */
3177         pid_t const pid = -1;
3178 #else
3179         // tmp_ret will be located (usually) in /tmp
3180         // will that be a problem?
3181         // Note that this calls ForkedCalls::fork(), so it's
3182         // ok cross-platform.
3183         pid_t const pid = fork();
3184         // If you want to debug the autosave
3185         // you should set pid to -1, and comment out the fork.
3186         if (pid != 0 && pid != -1)
3187                 return pid;
3188 #endif
3189
3190         // pid = -1 signifies that lyx was unable
3191         // to fork. But we will do the save
3192         // anyway.
3193         bool failed = false;
3194         FileName const tmp_ret = FileName::tempName("lyxauto");
3195         if (!tmp_ret.empty()) {
3196                 buffer_.writeFile(tmp_ret);
3197                 // assume successful write of tmp_ret
3198                 if (!tmp_ret.moveTo(fname_))
3199                         failed = true;
3200         } else
3201                 failed = true;
3202
3203         if (failed) {
3204                 // failed to write/rename tmp_ret so try writing direct
3205                 if (!buffer_.writeFile(fname_)) {
3206                         // It is dangerous to do this in the child,
3207                         // but safe in the parent, so...
3208                         if (pid == -1) // emit message signal.
3209                                 buffer_.message(_("Autosave failed!"));
3210                 }
3211         }
3212
3213         if (pid == 0) // we are the child so...
3214                 _exit(0);
3215
3216         return pid;
3217 }
3218
3219 } // namespace anon
3220
3221
3222 FileName Buffer::getAutosaveFileName() const
3223 {
3224         // if the document is unnamed try to save in the backup dir, else
3225         // in the default document path, and as a last try in the filePath, 
3226         // which will most often be the temporary directory
3227         string fpath;
3228         if (isUnnamed())
3229                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3230                         : lyxrc.backupdir_path;
3231         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3232                 fpath = filePath();
3233
3234         string const fname = "#" + d->filename.onlyFileName() + "#";
3235         return makeAbsPath(fname, fpath);
3236 }
3237
3238
3239 void Buffer::removeAutosaveFile() const
3240 {
3241         FileName const f = getAutosaveFileName();
3242         if (f.exists())
3243                 f.removeFile();
3244 }
3245
3246
3247 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3248 {
3249         FileName const newauto = getAutosaveFileName();
3250         oldauto.refresh();
3251         if (newauto != oldauto && oldauto.exists())
3252                 if (!oldauto.moveTo(newauto))
3253                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3254 }
3255
3256
3257 // Perfect target for a thread...
3258 void Buffer::autoSave() const
3259 {
3260         if (d->bak_clean || isReadonly()) {
3261                 // We don't save now, but we'll try again later
3262                 resetAutosaveTimers();
3263                 return;
3264         }
3265
3266         // emit message signal.
3267         message(_("Autosaving current document..."));
3268         AutoSaveBuffer autosave(*this, getAutosaveFileName());
3269         autosave.start();
3270
3271         d->bak_clean = true;
3272
3273         resetAutosaveTimers();
3274 }
3275
3276
3277 string Buffer::bufferFormat() const
3278 {
3279         string format = params().documentClass().outputFormat();
3280         if (format == "latex") {
3281                 if (params().useXetex)
3282                         return "xetex";
3283                 if (params().encoding().package() == Encoding::japanese)
3284                         return "platex";
3285         }
3286         return format;
3287 }
3288
3289
3290 string Buffer::getDefaultOutputFormat() const
3291 {
3292         if (!params().defaultOutputFormat.empty()
3293             && params().defaultOutputFormat != "default")
3294                 return params().defaultOutputFormat;
3295         typedef vector<Format const *> Formats;
3296         Formats formats = exportableFormats(true);
3297         if (isDocBook()
3298             || isLiterate()
3299             || params().useXetex
3300             || params().encoding().package() == Encoding::japanese) {
3301                 if (formats.empty())
3302                         return string();
3303                 // return the first we find
3304                 return formats.front()->name();
3305         }
3306         return lyxrc.default_view_format;
3307 }
3308
3309
3310 namespace {
3311         // helper class, to guarantee this gets reset properly
3312         class MarkAsExporting   {
3313         public:
3314                 MarkAsExporting(Buffer const * buf) : buf_(buf) 
3315                 {
3316                         LASSERT(buf_, /* */);
3317                         buf_->setExportStatus(true);
3318                 }
3319                 ~MarkAsExporting() 
3320                 {
3321                         buf_->setExportStatus(false);
3322                 }
3323         private:
3324                 Buffer const * const buf_;
3325         };
3326 }
3327
3328
3329 void Buffer::setExportStatus(bool e) const
3330 {
3331         d->doing_export = e;    
3332 }
3333
3334
3335 bool Buffer::isExporting() const
3336 {
3337         return d->doing_export;
3338 }
3339
3340
3341 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3342         bool includeall, string & result_file) const
3343 {
3344         MarkAsExporting exporting(this);
3345         string backend_format;
3346         OutputParams runparams(&params().encoding());
3347         runparams.flavor = OutputParams::LATEX;
3348         runparams.linelen = lyxrc.plaintext_linelen;
3349         runparams.includeall = includeall;
3350         vector<string> backs = backends();
3351         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3352                 // Get shortest path to format
3353                 Graph::EdgePath path;
3354                 for (vector<string>::const_iterator it = backs.begin();
3355                      it != backs.end(); ++it) {
3356                         Graph::EdgePath p = theConverters().getPath(*it, format);
3357                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3358                                 backend_format = *it;
3359                                 path = p;
3360                         }
3361                 }
3362                 if (path.empty()) {
3363                         if (!put_in_tempdir) {
3364                                 // Only show this alert if this is an export to a non-temporary
3365                                 // file (not for previewing).
3366                                 Alert::error(_("Couldn't export file"), bformat(
3367                                         _("No information for exporting the format %1$s."),
3368                                         formats.prettyName(format)));
3369                         }
3370                         return false;
3371                 }
3372                 runparams.flavor = theConverters().getFlavor(path);
3373
3374         } else {
3375                 backend_format = format;
3376                 // FIXME: Don't hardcode format names here, but use a flag
3377                 if (backend_format == "pdflatex")
3378                         runparams.flavor = OutputParams::PDFLATEX;
3379         }
3380
3381         string filename = latexName(false);
3382         filename = addName(temppath(), filename);
3383         filename = changeExtension(filename,
3384                                    formats.extension(backend_format));
3385
3386         // fix macros
3387         updateMacroInstances();
3388
3389         // Plain text backend
3390         if (backend_format == "text") {
3391                 runparams.flavor = OutputParams::TEXT;
3392                 writePlaintextFile(*this, FileName(filename), runparams);
3393         }
3394         // HTML backend
3395         else if (backend_format == "xhtml") {
3396                 runparams.flavor = OutputParams::HTML;
3397                 switch (params().html_math_output) {
3398                 case BufferParams::MathML: 
3399                         runparams.math_flavor = OutputParams::MathAsMathML; 
3400                         break;
3401                 case BufferParams::HTML: 
3402                         runparams.math_flavor = OutputParams::MathAsHTML; 
3403                         break;
3404                 case BufferParams::Images:
3405                         runparams.math_flavor = OutputParams::MathAsImages; 
3406                         break;
3407                 case BufferParams::LaTeX:
3408                         runparams.math_flavor = OutputParams::MathAsLaTeX; 
3409                         break;                                                                                  
3410                 }
3411                 
3412                 makeLyXHTMLFile(FileName(filename), runparams);
3413         }       else if (backend_format == "lyx")
3414                 writeFile(FileName(filename));
3415         // Docbook backend
3416         else if (isDocBook()) {
3417                 runparams.nice = !put_in_tempdir;
3418                 makeDocBookFile(FileName(filename), runparams);
3419         }
3420         // LaTeX backend
3421         else if (backend_format == format) {
3422                 runparams.nice = true;
3423                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3424                         return false;
3425         } else if (!lyxrc.tex_allows_spaces
3426                    && contains(filePath(), ' ')) {
3427                 Alert::error(_("File name error"),
3428                            _("The directory path to the document cannot contain spaces."));
3429                 return false;
3430         } else {
3431                 runparams.nice = false;
3432                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3433                         return false;
3434         }
3435
3436         string const error_type = (format == "program")
3437                 ? "Build" : bufferFormat();
3438         ErrorList & error_list = d->errorLists[error_type];
3439         string const ext = formats.extension(format);
3440         FileName const tmp_result_file(changeExtension(filename, ext));
3441         bool const success = theConverters().convert(this, FileName(filename),
3442                 tmp_result_file, FileName(absFileName()), backend_format, format,
3443                 error_list);
3444
3445         // Emit the signal to show the error list or copy it back to the
3446         // cloned Buffer so that it cab be emitted afterwards.
3447         if (format != backend_format) {
3448                 if (d->cloned_buffer_) {
3449                         d->cloned_buffer_->d->errorLists[error_type] = 
3450                                 d->errorLists[error_type];
3451                 } else 
3452                         errors(error_type);
3453                 // also to the children, in case of master-buffer-view
3454                 ListOfBuffers clist = getDescendents();
3455                 ListOfBuffers::const_iterator cit = clist.begin();
3456                 ListOfBuffers::const_iterator const cen = clist.end();
3457                 for (; cit != cen; ++cit) {
3458                         if (d->cloned_buffer_) {
3459                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] = 
3460                                         (*cit)->d->errorLists[error_type];
3461                         } else
3462                                 (*cit)->errors(error_type, true);
3463                 }
3464         }
3465
3466         if (d->cloned_buffer_) {
3467                 // Enable reverse dvi or pdf to work by copying back the texrow
3468                 // object to the cloned buffer.
3469                 // FIXME: There is a possibility of concurrent access to texrow
3470                 // here from the main GUI thread that should be securized.
3471                 d->cloned_buffer_->d->texrow = d->texrow;
3472                 string const error_type = bufferFormat();
3473                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3474         }
3475
3476         if (!success)
3477                 return false;
3478
3479         if (put_in_tempdir) {
3480                 result_file = tmp_result_file.absFileName();
3481                 return true;
3482         }
3483
3484         result_file = changeExtension(d->exportFileName().absFileName(), ext);
3485         // We need to copy referenced files (e. g. included graphics
3486         // if format == "dvi") to the result dir.
3487         vector<ExportedFile> const files =
3488                 runparams.exportdata->externalFiles(format);
3489         string const dest = onlyPath(result_file);
3490         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3491                                  : force_overwrite == ALL_FILES;
3492         CopyStatus status = use_force ? FORCE : SUCCESS;
3493         
3494         vector<ExportedFile>::const_iterator it = files.begin();
3495         vector<ExportedFile>::const_iterator const en = files.end();
3496         for (; it != en && status != CANCEL; ++it) {
3497                 string const fmt = formats.getFormatFromFile(it->sourceName);
3498                 status = copyFile(fmt, it->sourceName,
3499                         makeAbsPath(it->exportName, dest),
3500                         it->exportName, status == FORCE);
3501         }
3502
3503         if (status == CANCEL) {
3504                 message(_("Document export cancelled."));
3505         } else if (tmp_result_file.exists()) {
3506                 // Finally copy the main file
3507                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3508                                     : force_overwrite != NO_FILES;
3509                 if (status == SUCCESS && use_force)
3510                         status = FORCE;
3511                 status = copyFile(format, tmp_result_file,
3512                         FileName(result_file), result_file,
3513                         status == FORCE);
3514                 message(bformat(_("Document exported as %1$s "
3515                         "to file `%2$s'"),
3516                         formats.prettyName(format),
3517                         makeDisplayPath(result_file)));
3518         } else {
3519                 // This must be a dummy converter like fax (bug 1888)
3520                 message(bformat(_("Document exported as %1$s"),
3521                         formats.prettyName(format)));
3522         }
3523
3524         return true;
3525 }
3526
3527
3528 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3529                       bool includeall) const
3530 {
3531         string result_file;
3532         // (1) export with all included children (omit \includeonly)
3533         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3534                 return false;
3535         // (2) export with included children only
3536         return doExport(format, put_in_tempdir, false, result_file);
3537 }
3538
3539
3540 bool Buffer::preview(string const & format, bool includeall) const
3541 {
3542         MarkAsExporting exporting(this);
3543         string result_file;
3544         // (1) export with all included children (omit \includeonly)
3545         if (includeall && !doExport(format, true, true))
3546                 return false;
3547         // (2) export with included children only
3548         if (!doExport(format, true, false, result_file))
3549                 return false;
3550         return formats.view(*this, FileName(result_file), format);
3551 }
3552
3553
3554 bool Buffer::isExportable(string const & format) const
3555 {
3556         vector<string> backs = backends();
3557         for (vector<string>::const_iterator it = backs.begin();
3558              it != backs.end(); ++it)
3559                 if (theConverters().isReachable(*it, format))
3560                         return true;
3561         return false;
3562 }
3563
3564
3565 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3566 {
3567         vector<string> const backs = backends();
3568         vector<Format const *> result =
3569                 theConverters().getReachable(backs[0], only_viewable, true);
3570         for (vector<string>::const_iterator it = backs.begin() + 1;
3571              it != backs.end(); ++it) {
3572                 vector<Format const *>  r =
3573                         theConverters().getReachable(*it, only_viewable, false);
3574                 result.insert(result.end(), r.begin(), r.end());
3575         }
3576         return result;
3577 }
3578
3579
3580 vector<string> Buffer::backends() const
3581 {
3582         vector<string> v;
3583         v.push_back(bufferFormat());
3584         // FIXME: Don't hardcode format names here, but use a flag
3585         if (v.back() == "latex")
3586                 v.push_back("pdflatex");
3587         v.push_back("xhtml");
3588         v.push_back("text");
3589         v.push_back("lyx");
3590         return v;
3591 }
3592
3593
3594 Buffer::ReadStatus Buffer::readFromVC(FileName const & fn)
3595 {
3596         bool const found = LyXVC::file_not_found_hook(fn);
3597         if (!found)
3598                 return ReadFileNotFound;
3599         if (!fn.isReadableFile())
3600                 return ReadVCError;
3601         return ReadSuccess;
3602 }
3603
3604
3605 Buffer::ReadStatus Buffer::readEmergency(FileName const & fn)
3606 {
3607         FileName const emergencyFile(fn.absFileName() + ".emergency");
3608         if (emergencyFile.exists() 
3609                   && emergencyFile.lastModified() > fn.lastModified()) {
3610                 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3611                 docstring const text =
3612                         bformat(_("An emergency save of the document "
3613                                   "%1$s exists.\n\n"
3614                                                    "Recover emergency save?"), file);
3615
3616                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3617                                           _("&Recover"),  _("&Load Original"),
3618                                           _("&Cancel")))
3619                 {
3620                 case 0: {
3621                         // the file is not saved if we load the emergency file.
3622                         markDirty();
3623                         docstring str;
3624                         bool const res = readFile(emergencyFile);
3625                         if (res)
3626                                 str = _("Document was successfully recovered.");
3627                         else
3628                                 str = _("Document was NOT successfully recovered.");
3629                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3630                                                 makeDisplayPath(emergencyFile.absFileName()));
3631
3632                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3633                                         _("&Remove"), _("&Keep"))) {
3634                                 emergencyFile.removeFile();
3635                                 if (res)
3636                                         Alert::warning(_("Emergency file deleted"),
3637                                                 _("Do not forget to save your file now!"), true);
3638                                 }
3639                         return res ? ReadSuccess : ReadEmergencyFailure;
3640                 }
3641                 case 1:
3642                         if (!Alert::prompt(_("Delete emergency file?"),
3643                                         _("Remove emergency file now?"), 1, 1,
3644                                         _("&Remove"), _("&Keep")))
3645                                 emergencyFile.removeFile();
3646                         return ReadOriginal;
3647
3648                 default:
3649                         return ReadCancel;
3650                 }
3651         }
3652         return ReadFileNotFound;
3653 }
3654
3655
3656 Buffer::ReadStatus Buffer::readAutosave(FileName const & fn)
3657 {
3658         // Now check if autosave file is newer.
3659         FileName const autosaveFile(onlyPath(fn.absFileName()) 
3660                 + '#' + onlyFileName(fn.absFileName()) + '#');
3661         if (autosaveFile.exists() 
3662                   && autosaveFile.lastModified() > fn.lastModified()) {
3663                 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3664                 docstring const text =
3665                         bformat(_("The backup of the document "
3666                                   "%1$s is newer.\n\nLoad the "
3667                                                "backup instead?"), file);
3668                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3669                                       _("&Load backup"), _("Load &original"),
3670                                       _("&Cancel") ))
3671                 {
3672                 case 0:
3673                         // the file is not saved if we load the autosave file.
3674                         markDirty();
3675                         return readFile(autosaveFile) ? ReadSuccess
3676                                 : ReadAutosaveFailure;
3677                 case 1:
3678                         // Here we delete the autosave
3679                         autosaveFile.removeFile();
3680                         return ReadOriginal;
3681                 default:
3682                         return ReadCancel;
3683                 }
3684         }
3685         return ReadFileNotFound;
3686 }
3687
3688
3689 Buffer::ReadStatus Buffer::loadLyXFile(FileName const & fn)
3690 {
3691         if (!fn.isReadableFile()) {
3692                 ReadStatus const ret_rvc = readFromVC(fn);
3693                 if (ret_rvc != ReadSuccess)
3694                         return ret_rvc;
3695         }
3696         // InsetInfo needs to know if file is under VCS
3697         lyxvc().file_found_hook(fn);
3698
3699         ReadStatus const ret_re = readEmergency(fn);
3700         if (ret_re == ReadSuccess || ret_re == ReadCancel)
3701                 return ret_re;
3702         
3703         ReadStatus const ret_ra = readAutosave(fn);
3704         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3705                 return ret_ra;
3706
3707         if (readFile(fn))
3708                 return ReadSuccess;
3709         return ReadFailure;
3710 }
3711
3712
3713 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3714 {
3715         TeXErrors::Errors::const_iterator cit = terr.begin();
3716         TeXErrors::Errors::const_iterator end = terr.end();
3717
3718         for (; cit != end; ++cit) {
3719                 int id_start = -1;
3720                 int pos_start = -1;
3721                 int errorRow = cit->error_in_line;
3722                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3723                                                        pos_start);
3724                 int id_end = -1;
3725                 int pos_end = -1;
3726                 do {
3727                         ++errorRow;
3728                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3729                 } while (found && id_start == id_end && pos_start == pos_end);
3730
3731                 errorList.push_back(ErrorItem(cit->error_desc,
3732                         cit->error_text, id_start, pos_start, pos_end));
3733         }
3734 }
3735
3736
3737 void Buffer::setBuffersForInsets() const
3738 {
3739         inset().setBuffer(const_cast<Buffer &>(*this)); 
3740 }
3741
3742
3743 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3744 {
3745         // Use the master text class also for child documents
3746         Buffer const * const master = masterBuffer();
3747         DocumentClass const & textclass = master->params().documentClass();
3748         
3749         // do this only if we are the top-level Buffer
3750         if (master == this)
3751                 checkBibInfoCache();
3752
3753         // keep the buffers to be children in this set. If the call from the
3754         // master comes back we can see which of them were actually seen (i.e.
3755         // via an InsetInclude). The remaining ones in the set need still be updated.
3756         static std::set<Buffer const *> bufToUpdate;
3757         if (scope == UpdateMaster) {
3758                 // If this is a child document start with the master
3759                 if (master != this) {
3760                         bufToUpdate.insert(this);
3761                         master->updateBuffer(UpdateMaster, utype);
3762                         // Do this here in case the master has no gui associated with it. Then, 
3763                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3764                         if (!master->d->gui_)
3765                                 structureChanged();
3766
3767                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3768                         if (bufToUpdate.find(this) == bufToUpdate.end())
3769                                 return;
3770                 }
3771
3772                 // start over the counters in the master
3773                 textclass.counters().reset();
3774         }
3775
3776         // update will be done below for this buffer
3777         bufToUpdate.erase(this);
3778
3779         // update all caches
3780         clearReferenceCache();
3781         updateMacros();
3782
3783         Buffer & cbuf = const_cast<Buffer &>(*this);
3784
3785         LASSERT(!text().paragraphs().empty(), /**/);
3786
3787         // do the real work
3788         ParIterator parit = cbuf.par_iterator_begin();
3789         updateBuffer(parit, utype);
3790
3791         if (master != this)
3792                 // TocBackend update will be done later.
3793                 return;
3794
3795         cbuf.tocBackend().update();
3796         if (scope == UpdateMaster)
3797                 cbuf.structureChanged();
3798 }
3799
3800
3801 static depth_type getDepth(DocIterator const & it)
3802 {
3803         depth_type depth = 0;
3804         for (size_t i = 0 ; i < it.depth() ; ++i)
3805                 if (!it[i].inset().inMathed())
3806                         depth += it[i].paragraph().getDepth() + 1;
3807         // remove 1 since the outer inset does not count
3808         return depth - 1;
3809 }
3810
3811 static depth_type getItemDepth(ParIterator const & it)
3812 {
3813         Paragraph const & par = *it;
3814         LabelType const labeltype = par.layout().labeltype;
3815
3816         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3817                 return 0;
3818
3819         // this will hold the lowest depth encountered up to now.
3820         depth_type min_depth = getDepth(it);
3821         ParIterator prev_it = it;
3822         while (true) {
3823                 if (prev_it.pit())
3824                         --prev_it.top().pit();
3825                 else {
3826                         // start of nested inset: go to outer par
3827                         prev_it.pop_back();
3828                         if (prev_it.empty()) {
3829                                 // start of document: nothing to do
3830                                 return 0;
3831                         }
3832                 }
3833
3834                 // We search for the first paragraph with same label
3835                 // that is not more deeply nested.
3836                 Paragraph & prev_par = *prev_it;
3837                 depth_type const prev_depth = getDepth(prev_it);
3838                 if (labeltype == prev_par.layout().labeltype) {
3839                         if (prev_depth < min_depth)
3840                                 return prev_par.itemdepth + 1;
3841                         if (prev_depth == min_depth)
3842                                 return prev_par.itemdepth;
3843                 }
3844                 min_depth = min(min_depth, prev_depth);
3845                 // small optimization: if we are at depth 0, we won't
3846                 // find anything else
3847                 if (prev_depth == 0)
3848                         return 0;
3849         }
3850 }
3851
3852
3853 static bool needEnumCounterReset(ParIterator const & it)
3854 {
3855         Paragraph const & par = *it;
3856         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3857         depth_type const cur_depth = par.getDepth();
3858         ParIterator prev_it = it;
3859         while (prev_it.pit()) {
3860                 --prev_it.top().pit();
3861                 Paragraph const & prev_par = *prev_it;
3862                 if (prev_par.getDepth() <= cur_depth)
3863                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3864         }
3865         // start of nested inset: reset
3866         return true;
3867 }
3868
3869
3870 // set the label of a paragraph. This includes the counters.
3871 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3872 {
3873         BufferParams const & bp = owner_->masterBuffer()->params();
3874         DocumentClass const & textclass = bp.documentClass();
3875         Paragraph & par = it.paragraph();
3876         Layout const & layout = par.layout();
3877         Counters & counters = textclass.counters();
3878
3879         if (par.params().startOfAppendix()) {
3880                 // FIXME: only the counter corresponding to toplevel
3881                 // sectioning should be reset
3882                 counters.reset();
3883                 counters.appendix(true);
3884         }
3885         par.params().appendix(counters.appendix());
3886
3887         // Compute the item depth of the paragraph
3888         par.itemdepth = getItemDepth(it);
3889
3890         if (layout.margintype == MARGIN_MANUAL
3891             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3892                 if (par.params().labelWidthString().empty())
3893                         par.params().labelWidthString(par.expandLabel(layout, bp));
3894         } else {
3895                 par.params().labelWidthString(docstring());
3896         }
3897
3898         switch(layout.labeltype) {
3899         case LABEL_COUNTER:
3900                 if (layout.toclevel <= bp.secnumdepth
3901                     && (layout.latextype != LATEX_ENVIRONMENT
3902                         || it.text()->isFirstInSequence(it.pit()))) {
3903                         counters.step(layout.counter, utype);
3904                         par.params().labelString(
3905                                 par.expandLabel(layout, bp));
3906                 } else
3907                         par.params().labelString(docstring());
3908                 break;
3909
3910         case LABEL_ITEMIZE: {
3911                 // At some point of time we should do something more
3912                 // clever here, like:
3913                 //   par.params().labelString(
3914                 //    bp.user_defined_bullet(par.itemdepth).getText());
3915                 // for now, use a simple hardcoded label
3916                 docstring itemlabel;
3917                 switch (par.itemdepth) {
3918                 case 0:
3919                         itemlabel = char_type(0x2022);
3920                         break;
3921                 case 1:
3922                         itemlabel = char_type(0x2013);
3923                         break;
3924                 case 2:
3925                         itemlabel = char_type(0x2217);
3926                         break;
3927                 case 3:
3928                         itemlabel = char_type(0x2219); // or 0x00b7
3929                         break;
3930                 }
3931                 par.params().labelString(itemlabel);
3932                 break;
3933         }
3934
3935         case LABEL_ENUMERATE: {
3936                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3937
3938                 switch (par.itemdepth) {
3939                 case 2:
3940                         enumcounter += 'i';
3941                 case 1:
3942                         enumcounter += 'i';
3943                 case 0:
3944                         enumcounter += 'i';
3945                         break;
3946                 case 3:
3947                         enumcounter += "iv";
3948                         break;
3949                 default:
3950                         // not a valid enumdepth...
3951                         break;
3952                 }
3953
3954                 // Maybe we have to reset the enumeration counter.
3955                 if (needEnumCounterReset(it))
3956                         counters.reset(enumcounter);
3957                 counters.step(enumcounter, utype);
3958
3959                 string const & lang = par.getParLanguage(bp)->code();
3960                 par.params().labelString(counters.theCounter(enumcounter, lang));
3961
3962                 break;
3963         }
3964
3965         case LABEL_SENSITIVE: {
3966                 string const & type = counters.current_float();
3967                 docstring full_label;
3968                 if (type.empty())
3969                         full_label = owner_->B_("Senseless!!! ");
3970                 else {
3971                         docstring name = owner_->B_(textclass.floats().getType(type).name());
3972                         if (counters.hasCounter(from_utf8(type))) {
3973                                 string const & lang = par.getParLanguage(bp)->code();
3974                                 counters.step(from_utf8(type), utype);
3975                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3976                                                      name, 
3977                                                      counters.theCounter(from_utf8(type), lang));
3978                         } else
3979                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3980                 }
3981                 par.params().labelString(full_label);   
3982                 break;
3983         }
3984
3985         case LABEL_NO_LABEL:
3986                 par.params().labelString(docstring());
3987                 break;
3988
3989         case LABEL_MANUAL:
3990         case LABEL_TOP_ENVIRONMENT:
3991         case LABEL_CENTERED_TOP_ENVIRONMENT:
3992         case LABEL_STATIC:      
3993         case LABEL_BIBLIO:
3994                 par.params().labelString(par.expandLabel(layout, bp));
3995                 break;
3996         }
3997 }
3998
3999
4000 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4001 {
4002         LASSERT(parit.pit() == 0, /**/);
4003
4004         // Set the position of the text in the buffer to be able
4005         // to resolve macros in it.
4006         parit.text()->setMacrocontextPosition(parit);
4007
4008         depth_type maxdepth = 0;
4009         pit_type const lastpit = parit.lastpit();
4010         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4011                 // reduce depth if necessary
4012                 parit->params().depth(min(parit->params().depth(), maxdepth));
4013                 maxdepth = parit->getMaxDepthAfter();
4014
4015                 if (utype == OutputUpdate) {
4016                         // track the active counters
4017                         // we have to do this for the master buffer, since the local
4018                         // buffer isn't tracking anything.
4019                         masterBuffer()->params().documentClass().counters().
4020                                         setActiveLayout(parit->layout());
4021                 }
4022                 
4023                 // set the counter for this paragraph
4024                 d->setLabel(parit, utype);
4025
4026                 // now the insets
4027                 InsetList::const_iterator iit = parit->insetList().begin();
4028                 InsetList::const_iterator end = parit->insetList().end();
4029                 for (; iit != end; ++iit) {
4030                         parit.pos() = iit->pos;
4031                         iit->inset->updateBuffer(parit, utype);
4032                 }
4033         }
4034 }
4035
4036
4037 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4038         WordLangTuple & word_lang, docstring_list & suggestions) const
4039 {
4040         int progress = 0;
4041         WordLangTuple wl;
4042         suggestions.clear();
4043         word_lang = WordLangTuple();
4044         // OK, we start from here.
4045         DocIterator const end = doc_iterator_end(this);
4046         for (; from != end; from.forwardPos()) {
4047                 // We are only interested in text so remove the math CursorSlice.
4048                 while (from.inMathed()) {
4049                         from.pop_back();
4050                         from.pos()++;
4051                 }
4052                 // If from is at the end of the document (which is possible
4053                 // when leaving the mathed) LyX will crash later.
4054                 if (from == end)
4055                         break;
4056                 to = from;
4057                 from.paragraph().spellCheck();
4058                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4059                 if (SpellChecker::misspelled(res)) {
4060                         word_lang = wl;
4061                         break;
4062                 }
4063
4064                 // Do not increase progress when from == to, otherwise the word
4065                 // count will be wrong.
4066                 if (from != to) {
4067                         from = to;
4068                         ++progress;
4069                 }
4070         }
4071         return progress;
4072 }
4073
4074
4075 bool Buffer::reload()
4076 {
4077         setBusy(true);
4078         // c.f. bug 6587
4079         removeAutosaveFile();
4080         // e.g., read-only status could have changed due to version control
4081         d->filename.refresh();
4082         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4083
4084         bool const success = (loadLyXFile(d->filename) == ReadSuccess);
4085         if (success) {
4086                 updateBuffer();
4087                 changed(true);
4088                 updateTitles();
4089                 markClean();
4090                 saveCheckSum(d->filename);
4091                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4092         } else {
4093                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4094         }       
4095         setBusy(false);
4096         thePreviews().removeLoader(*this);
4097         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4098                 thePreviews().generateBufferPreviews(*this);
4099         errors("Parse");
4100         return success;
4101 }
4102
4103
4104 // FIXME We could do better here, but it is complicated. What would be
4105 // nice is to offer either (a) to save the child buffer to an appropriate
4106 // location, so that it would "move with the master", or else (b) to update
4107 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4108 // complicated, because the code for this lives in GuiView.
4109 void Buffer::checkChildBuffers()
4110 {
4111         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4112         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4113         for (; it != en; ++it) {
4114                 DocIterator dit = it->second;
4115                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4116                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4117                         continue;
4118                 Inset * inset = dit.nextInset();
4119                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4120                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4121                 docstring const & incfile = inset_inc->getParam("filename");
4122                 string oldloc = cbuf->absFileName();
4123                 string newloc = makeAbsPath(to_utf8(incfile),
4124                                 onlyPath(absFileName())).absFileName();
4125                 if (oldloc == newloc)
4126                         continue;
4127                 // the location of the child file is incorrect.
4128                 Alert::warning(_("Included File Invalid"),
4129                                 bformat(_("Saving this document to a new location has made the file:\n"
4130                                 "  %1$s\n"
4131                                 "inaccessible. You will need to update the included filename."),
4132                                 from_utf8(oldloc)));
4133                 cbuf->setParent(0);
4134                 inset_inc->setChildBuffer(0);
4135         }
4136         // invalidate cache of children
4137         d->children_positions.clear();
4138         d->position_to_children.clear();
4139 }
4140
4141 } // namespace lyx