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