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