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