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