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