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