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