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