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