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