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