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