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