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