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