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