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