]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
90685fe6bca7eb19f33c7ae5284e2ff6a04e8aac
[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 "DocIterator.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "sgml.h"
54 #include "TexRow.h"
55 #include "TexStream.h"
56 #include "Text.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
59 #include "Undo.h"
60 #include "VCBackend.h"
61 #include "version.h"
62 #include "WordList.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
99
100 #include <algorithm>
101 #include <fstream>
102 #include <iomanip>
103 #include <map>
104 #include <set>
105 #include <sstream>
106 #include <stack>
107 #include <vector>
108
109 using namespace std;
110 using namespace lyx::support;
111
112 namespace lyx {
113
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
116
117 namespace {
118
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 348;  // uwestoehr: add support for \*phantom
122
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
125
126 } // namespace anon
127
128 class BufferSet : public std::set<Buffer const *> {};
129
130 class Buffer::Impl
131 {
132 public:
133         Impl(Buffer & parent, FileName const & file, bool readonly);
134
135         ~Impl()
136         {
137                 if (wa_) {
138                         wa_->closeAll();
139                         delete wa_;
140                 }
141                 delete inset;
142         }
143
144         BufferParams params;
145         LyXVC lyxvc;
146         FileName temppath;
147         mutable TexRow texrow;
148         Buffer const * parent_buffer;
149
150         /// need to regenerate .tex?
151         DepClean dep_clean;
152
153         /// is save needed?
154         mutable bool lyx_clean;
155
156         /// is autosave needed?
157         mutable bool bak_clean;
158
159         /// is this a unnamed file (New...)?
160         bool unnamed;
161
162         /// buffer is r/o
163         bool read_only;
164
165         /// name of the file the buffer is associated with.
166         FileName filename;
167
168         /** Set to true only when the file is fully loaded.
169          *  Used to prevent the premature generation of previews
170          *  and by the citation inset.
171          */
172         bool file_fully_loaded;
173
174         ///
175         mutable TocBackend toc_backend;
176
177         /// macro tables
178         typedef pair<DocIterator, MacroData> ScopeMacro;
179         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181         /// map from the macro name to the position map,
182         /// which maps the macro definition position to the scope and the MacroData.
183         NamePositionScopeMacroMap macros;
184         bool macro_lock;
185
186         /// positions of child buffers in the buffer
187         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
188         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
189         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
190         /// position of children buffers in this buffer
191         BufferPositionMap children_positions;
192         /// map from children inclusion positions to their scope and their buffer
193         PositionScopeBufferMap position_to_children;
194
195         /// Container for all sort of Buffer dependant errors.
196         map<string, ErrorList> errorLists;
197
198         /// timestamp and checksum used to test if the file has been externally
199         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200         time_t timestamp_;
201         unsigned long checksum_;
202
203         ///
204         frontend::WorkAreaManager * wa_;
205
206         ///
207         Undo undo_;
208
209         /// A cache for the bibfiles (including bibfiles of loaded child
210         /// documents), needed for appropriate update of natbib labels.
211         mutable support::FileNameList bibfilesCache_;
212
213         // FIXME The caching mechanism could be improved. At present, we have a
214         // cache for each Buffer, that caches all the bibliography info for that
215         // Buffer. A more efficient solution would be to have a global cache per
216         // file, and then to construct the Buffer's bibinfo from that.
217         /// A cache for bibliography info
218         mutable BiblioInfo bibinfo_;
219         /// whether the bibinfo cache is valid
220         bool bibinfoCacheValid_;
221         /// Cache of timestamps of .bib files
222         map<FileName, time_t> bibfileStatus_;
223
224         mutable RefCache ref_cache_;
225
226         /// our Text that should be wrapped in an InsetText
227         InsetText * inset;
228 };
229
230
231 /// Creates the per buffer temporary directory
232 static FileName createBufferTmpDir()
233 {
234         static int count;
235         // We are in our own directory.  Why bother to mangle name?
236         // In fact I wrote this code to circumvent a problematic behaviour
237         // (bug?) of EMX mkstemp().
238         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
239                 convert<string>(count++));
240
241         if (!tmpfl.createDirectory(0777)) {
242                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
243                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
244                         from_utf8(tmpfl.absFilename())));
245         }
246         return tmpfl;
247 }
248
249
250 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
251         : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
252           read_only(readonly_), filename(file), file_fully_loaded(false),
253           toc_backend(&parent), macro_lock(false), timestamp_(0),
254           checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
255 {
256         temppath = createBufferTmpDir();
257         lyxvc.setBuffer(&parent);
258         if (use_gui)
259                 wa_ = new frontend::WorkAreaManager;
260 }
261
262
263 Buffer::Buffer(string const & file, bool readonly)
264         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
265 {
266         LYXERR(Debug::INFO, "Buffer::Buffer()");
267
268         d->inset = new InsetText(*this);
269         d->inset->setAutoBreakRows(true);
270         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
271 }
272
273
274 Buffer::~Buffer()
275 {
276         LYXERR(Debug::INFO, "Buffer::~Buffer()");
277         // here the buffer should take care that it is
278         // saved properly, before it goes into the void.
279
280         // GuiView already destroyed
281         gui_ = 0;
282
283         if (d->unnamed && d->filename.extension() == "internal") {
284                 // No need to do additional cleanups for internal buffer.
285                 delete d;
286                 return;
287         }
288
289         // loop over children
290         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
291         Impl::BufferPositionMap::iterator end = d->children_positions.end();
292         for (; it != end; ++it)
293                 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
294
295         // clear references to children in macro tables
296         d->children_positions.clear();
297         d->position_to_children.clear();
298
299         if (!d->temppath.destroyDirectory()) {
300                 Alert::warning(_("Could not remove temporary directory"),
301                         bformat(_("Could not remove the temporary directory %1$s"),
302                         from_utf8(d->temppath.absFilename())));
303         }
304
305         // Remove any previewed LaTeX snippets associated with this buffer.
306         thePreviews().removeLoader(*this);
307
308         delete d;
309 }
310
311
312 void Buffer::changed() const
313 {
314         if (d->wa_)
315                 d->wa_->redrawAll();
316 }
317
318
319 frontend::WorkAreaManager & Buffer::workAreaManager() const
320 {
321         LASSERT(d->wa_, /**/);
322         return *d->wa_;
323 }
324
325
326 Text & Buffer::text() const
327 {
328         return d->inset->text();
329 }
330
331
332 Inset & Buffer::inset() const
333 {
334         return *d->inset;
335 }
336
337
338 BufferParams & Buffer::params()
339 {
340         return d->params;
341 }
342
343
344 BufferParams const & Buffer::params() const
345 {
346         return d->params;
347 }
348
349
350 ParagraphList & Buffer::paragraphs()
351 {
352         return text().paragraphs();
353 }
354
355
356 ParagraphList const & Buffer::paragraphs() const
357 {
358         return text().paragraphs();
359 }
360
361
362 LyXVC & Buffer::lyxvc()
363 {
364         return d->lyxvc;
365 }
366
367
368 LyXVC const & Buffer::lyxvc() const
369 {
370         return d->lyxvc;
371 }
372
373
374 string const Buffer::temppath() const
375 {
376         return d->temppath.absFilename();
377 }
378
379
380 TexRow & Buffer::texrow()
381 {
382         return d->texrow;
383 }
384
385
386 TexRow const & Buffer::texrow() const
387 {
388         return d->texrow;
389 }
390
391
392 TocBackend & Buffer::tocBackend() const
393 {
394         return d->toc_backend;
395 }
396
397
398 Undo & Buffer::undo()
399 {
400         return d->undo_;
401 }
402
403
404 string Buffer::latexName(bool const no_path) const
405 {
406         FileName latex_name = makeLatexName(d->filename);
407         return no_path ? latex_name.onlyFileName()
408                 : latex_name.absFilename();
409 }
410
411
412 string Buffer::logName(LogType * type) const
413 {
414         string const filename = latexName(false);
415
416         if (filename.empty()) {
417                 if (type)
418                         *type = latexlog;
419                 return string();
420         }
421
422         string const path = temppath();
423
424         FileName const fname(addName(temppath(),
425                                      onlyFilename(changeExtension(filename,
426                                                                   ".log"))));
427         FileName const bname(
428                 addName(path, onlyFilename(
429                         changeExtension(filename,
430                                         formats.extension("literate") + ".out"))));
431
432         // If no Latex log or Build log is newer, show Build log
433
434         if (bname.exists() &&
435             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
436                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
437                 if (type)
438                         *type = buildlog;
439                 return bname.absFilename();
440         }
441         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
442         if (type)
443                         *type = latexlog;
444         return fname.absFilename();
445 }
446
447
448 void Buffer::setReadonly(bool const flag)
449 {
450         if (d->read_only != flag) {
451                 d->read_only = flag;
452                 setReadOnly(flag);
453         }
454 }
455
456
457 void Buffer::setFileName(string const & newfile)
458 {
459         d->filename = makeAbsPath(newfile);
460         setReadonly(d->filename.isReadOnly());
461         updateTitles();
462 }
463
464
465 int Buffer::readHeader(Lexer & lex)
466 {
467         int unknown_tokens = 0;
468         int line = -1;
469         int begin_header_line = -1;
470
471         // Initialize parameters that may be/go lacking in header:
472         params().branchlist().clear();
473         params().preamble.erase();
474         params().options.erase();
475         params().master.erase();
476         params().float_placement.erase();
477         params().paperwidth.erase();
478         params().paperheight.erase();
479         params().leftmargin.erase();
480         params().rightmargin.erase();
481         params().topmargin.erase();
482         params().bottommargin.erase();
483         params().headheight.erase();
484         params().headsep.erase();
485         params().footskip.erase();
486         params().columnsep.erase();
487         params().fontsCJK.erase();
488         params().listings_params.clear();
489         params().clearLayoutModules();
490         params().clearRemovedModules();
491         params().pdfoptions().clear();
492
493         for (int i = 0; i < 4; ++i) {
494                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
495                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
496         }
497
498         ErrorList & errorList = d->errorLists["Parse"];
499
500         while (lex.isOK()) {
501                 string token;
502                 lex >> token;
503
504                 if (token.empty())
505                         continue;
506
507                 if (token == "\\end_header")
508                         break;
509
510                 ++line;
511                 if (token == "\\begin_header") {
512                         begin_header_line = line;
513                         continue;
514                 }
515
516                 LYXERR(Debug::PARSER, "Handling document header token: `"
517                                       << token << '\'');
518
519                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
520                 if (!unknown.empty()) {
521                         if (unknown[0] != '\\' && token == "\\textclass") {
522                                 Alert::warning(_("Unknown document class"),
523                        bformat(_("Using the default document class, because the "
524                                               "class %1$s is unknown."), from_utf8(unknown)));
525                         } else {
526                                 ++unknown_tokens;
527                                 docstring const s = bformat(_("Unknown token: "
528                                                                         "%1$s %2$s\n"),
529                                                          from_utf8(token),
530                                                          lex.getDocString());
531                                 errorList.push_back(ErrorItem(_("Document header error"),
532                                         s, -1, 0, 0));
533                         }
534                 }
535         }
536         if (begin_header_line) {
537                 docstring const s = _("\\begin_header is missing");
538                 errorList.push_back(ErrorItem(_("Document header error"),
539                         s, -1, 0, 0));
540         }
541
542         params().makeDocumentClass();
543
544         return unknown_tokens;
545 }
546
547
548 // Uwe C. Schroeder
549 // changed to be public and have one parameter
550 // Returns true if "\end_document" is not read (Asger)
551 bool Buffer::readDocument(Lexer & lex)
552 {
553         ErrorList & errorList = d->errorLists["Parse"];
554         errorList.clear();
555
556         if (!lex.checkFor("\\begin_document")) {
557                 docstring const s = _("\\begin_document is missing");
558                 errorList.push_back(ErrorItem(_("Document header error"),
559                         s, -1, 0, 0));
560         }
561
562         // we are reading in a brand new document
563         LASSERT(paragraphs().empty(), /**/);
564
565         readHeader(lex);
566
567         if (params().outputChanges) {
568                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
569                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
570                                   LaTeXFeatures::isAvailable("xcolor");
571
572                 if (!dvipost && !xcolorulem) {
573                         Alert::warning(_("Changes not shown in LaTeX output"),
574                                        _("Changes will not be highlighted in LaTeX output, "
575                                          "because neither dvipost nor xcolor/ulem are installed.\n"
576                                          "Please install these packages or redefine "
577                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578                 } else if (!xcolorulem) {
579                         Alert::warning(_("Changes not shown in LaTeX output"),
580                                        _("Changes will not be highlighted in LaTeX output "
581                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
582                                          "Please install both packages or redefine "
583                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
584                 }
585         }
586
587         if (!params().master.empty()) {
588                 FileName const master_file = makeAbsPath(params().master,
589                            onlyPath(absFileName()));
590                 if (isLyXFilename(master_file.absFilename())) {
591                         Buffer * master = 
592                                 checkAndLoadLyXFile(master_file, true);
593                         if (master) {
594                                 // set master as master buffer, but only
595                                 // if we are a real child
596                                 if (master->isChild(this))
597                                         setParent(master);
598                                 // if the master is not fully loaded
599                                 // it is probably just loading this
600                                 // child. No warning needed then.
601                                 else if (master->isFullyLoaded())
602                                         LYXERR0("The master '"
603                                                 << params().master
604                                                 << "' assigned to this document '"
605                                                 << absFileName()
606                                                 << "' does not include "
607                                                 "this document. Ignoring the master assignment.");
608                         }
609                 }
610         }
611
612         // read main text
613         bool const res = text().read(*this, lex, errorList, d->inset);
614
615         updateMacros();
616         updateMacroInstances();
617         return res;
618 }
619
620
621 // needed to insert the selection
622 void Buffer::insertStringAsLines(ParagraphList & pars,
623         pit_type & pit, pos_type & pos,
624         Font const & fn, docstring const & str, bool autobreakrows)
625 {
626         Font font = fn;
627
628         // insert the string, don't insert doublespace
629         bool space_inserted = true;
630         for (docstring::const_iterator cit = str.begin();
631             cit != str.end(); ++cit) {
632                 Paragraph & par = pars[pit];
633                 if (*cit == '\n') {
634                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
635                                 breakParagraph(params(), pars, pit, pos,
636                                                par.layout().isEnvironment());
637                                 ++pit;
638                                 pos = 0;
639                                 space_inserted = true;
640                         } else {
641                                 continue;
642                         }
643                         // do not insert consecutive spaces if !free_spacing
644                 } else if ((*cit == ' ' || *cit == '\t') &&
645                            space_inserted && !par.isFreeSpacing()) {
646                         continue;
647                 } else if (*cit == '\t') {
648                         if (!par.isFreeSpacing()) {
649                                 // tabs are like spaces here
650                                 par.insertChar(pos, ' ', font, params().trackChanges);
651                                 ++pos;
652                                 space_inserted = true;
653                         } else {
654                                 par.insertChar(pos, *cit, font, params().trackChanges);
655                                 ++pos;
656                                 space_inserted = true;
657                         }
658                 } else if (!isPrintable(*cit)) {
659                         // Ignore unprintables
660                         continue;
661                 } else {
662                         // just insert the character
663                         par.insertChar(pos, *cit, font, params().trackChanges);
664                         ++pos;
665                         space_inserted = (*cit == ' ');
666                 }
667
668         }
669 }
670
671
672 bool Buffer::readString(string const & s)
673 {
674         params().compressed = false;
675
676         // remove dummy empty par
677         paragraphs().clear();
678         Lexer lex;
679         istringstream is(s);
680         lex.setStream(is);
681         FileName const name = FileName::tempName("Buffer_readString");
682         switch (readFile(lex, name, true)) {
683         case failure:
684                 return false;
685         case wrongversion: {
686                 // We need to call lyx2lyx, so write the input to a file
687                 ofstream os(name.toFilesystemEncoding().c_str());
688                 os << s;
689                 os.close();
690                 return readFile(name);
691         }
692         case success:
693                 break;
694         }
695
696         return true;
697 }
698
699
700 bool Buffer::readFile(FileName const & filename)
701 {
702         FileName fname(filename);
703
704         params().compressed = fname.isZippedFile();
705
706         // remove dummy empty par
707         paragraphs().clear();
708         Lexer lex;
709         lex.setFile(fname);
710         if (readFile(lex, fname) != success)
711                 return false;
712
713         return true;
714 }
715
716
717 bool Buffer::isFullyLoaded() const
718 {
719         return d->file_fully_loaded;
720 }
721
722
723 void Buffer::setFullyLoaded(bool value)
724 {
725         d->file_fully_loaded = value;
726 }
727
728
729 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
730                 bool fromstring)
731 {
732         LASSERT(!filename.empty(), /**/);
733
734         // the first (non-comment) token _must_ be...
735         if (!lex.checkFor("\\lyxformat")) {
736                 Alert::error(_("Document format failure"),
737                              bformat(_("%1$s is not a readable LyX document."),
738                                        from_utf8(filename.absFilename())));
739                 return failure;
740         }
741
742         string tmp_format;
743         lex >> tmp_format;
744         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
745         // if present remove ".," from string.
746         size_t dot = tmp_format.find_first_of(".,");
747         //lyxerr << "           dot found at " << dot << endl;
748         if (dot != string::npos)
749                         tmp_format.erase(dot, 1);
750         int const file_format = convert<int>(tmp_format);
751         //lyxerr << "format: " << file_format << endl;
752
753         // save timestamp and checksum of the original disk file, making sure
754         // to not overwrite them with those of the file created in the tempdir
755         // when it has to be converted to the current format.
756         if (!d->checksum_) {
757                 // Save the timestamp and checksum of disk file. If filename is an
758                 // emergency file, save the timestamp and checksum of the original lyx file
759                 // because isExternallyModified will check for this file. (BUG4193)
760                 string diskfile = filename.absFilename();
761                 if (suffixIs(diskfile, ".emergency"))
762                         diskfile = diskfile.substr(0, diskfile.size() - 10);
763                 saveCheckSum(FileName(diskfile));
764         }
765
766         if (file_format != LYX_FORMAT) {
767
768                 if (fromstring)
769                         // lyx2lyx would fail
770                         return wrongversion;
771
772                 FileName const tmpfile = FileName::tempName("Buffer_readFile");
773                 if (tmpfile.empty()) {
774                         Alert::error(_("Conversion failed"),
775                                      bformat(_("%1$s is from a different"
776                                               " version of LyX, but a temporary"
777                                               " file for converting it could"
778                                                             " not be created."),
779                                               from_utf8(filename.absFilename())));
780                         return failure;
781                 }
782                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
783                 if (lyx2lyx.empty()) {
784                         Alert::error(_("Conversion script not found"),
785                                      bformat(_("%1$s is from a different"
786                                                " version of LyX, but the"
787                                                " conversion script lyx2lyx"
788                                                             " could not be found."),
789                                                from_utf8(filename.absFilename())));
790                         return failure;
791                 }
792                 ostringstream command;
793                 command << os::python()
794                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
795                         << " -t " << convert<string>(LYX_FORMAT)
796                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
797                         << ' ' << quoteName(filename.toFilesystemEncoding());
798                 string const command_str = command.str();
799
800                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
801
802                 cmd_ret const ret = runCommand(command_str);
803                 if (ret.first != 0) {
804                         Alert::error(_("Conversion script failed"),
805                                      bformat(_("%1$s is from a different version"
806                                               " of LyX, but the lyx2lyx script"
807                                                             " failed to convert it."),
808                                               from_utf8(filename.absFilename())));
809                         return failure;
810                 } else {
811                         bool const ret = readFile(tmpfile);
812                         // Do stuff with tmpfile name and buffer name here.
813                         return ret ? success : failure;
814                 }
815
816         }
817
818         if (readDocument(lex)) {
819                 Alert::error(_("Document format failure"),
820                              bformat(_("%1$s ended unexpectedly, which means"
821                                                     " that it is probably corrupted."),
822                                        from_utf8(filename.absFilename())));
823         }
824
825         d->file_fully_loaded = true;
826         return success;
827 }
828
829
830 // Should probably be moved to somewhere else: BufferView? LyXView?
831 bool Buffer::save() const
832 {
833         // We don't need autosaves in the immediate future. (Asger)
834         resetAutosaveTimers();
835
836         string const encodedFilename = d->filename.toFilesystemEncoding();
837
838         FileName backupName;
839         bool madeBackup = false;
840
841         // make a backup if the file already exists
842         if (lyxrc.make_backup && fileName().exists()) {
843                 backupName = FileName(absFileName() + '~');
844                 if (!lyxrc.backupdir_path.empty()) {
845                         string const mangledName =
846                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
847                         backupName = FileName(addName(lyxrc.backupdir_path,
848                                                       mangledName));
849                 }
850                 if (fileName().copyTo(backupName)) {
851                         madeBackup = true;
852                 } else {
853                         Alert::error(_("Backup failure"),
854                                      bformat(_("Cannot create backup file %1$s.\n"
855                                                "Please check whether the directory exists and is writeable."),
856                                              from_utf8(backupName.absFilename())));
857                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
858                 }
859         }
860
861         // ask if the disk file has been externally modified (use checksum method)
862         if (fileName().exists() && isExternallyModified(checksum_method)) {
863                 docstring const file = makeDisplayPath(absFileName(), 20);
864                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
865                                                              "you want to overwrite this file?"), file);
866                 int const ret = Alert::prompt(_("Overwrite modified file?"),
867                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
868                 if (ret == 1)
869                         return false;
870         }
871
872         if (writeFile(d->filename)) {
873                 markClean();
874                 return true;
875         } else {
876                 // Saving failed, so backup is not backup
877                 if (madeBackup)
878                         backupName.moveTo(d->filename);
879                 return false;
880         }
881 }
882
883
884 bool Buffer::writeFile(FileName const & fname) const
885 {
886         if (d->read_only && fname == d->filename)
887                 return false;
888
889         bool retval = false;
890
891         docstring const str = bformat(_("Saving document %1$s..."),
892                 makeDisplayPath(fname.absFilename()));
893         message(str);
894
895         if (params().compressed) {
896                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
897                 retval = ofs && write(ofs);
898         } else {
899                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
900                 retval = ofs && write(ofs);
901         }
902
903         if (!retval) {
904                 message(str + _(" could not write file!"));
905                 return false;
906         }
907
908         removeAutosaveFile(d->filename.absFilename());
909
910         saveCheckSum(d->filename);
911         message(str + _(" done."));
912
913         return true;
914 }
915
916
917 bool Buffer::write(ostream & ofs) const
918 {
919 #ifdef HAVE_LOCALE
920         // Use the standard "C" locale for file output.
921         ofs.imbue(locale::classic());
922 #endif
923
924         // The top of the file should not be written by params().
925
926         // write out a comment in the top of the file
927         ofs << "#LyX " << lyx_version
928             << " created this file. For more info see http://www.lyx.org/\n"
929             << "\\lyxformat " << LYX_FORMAT << "\n"
930             << "\\begin_document\n";
931
932         /// For each author, set 'used' to true if there is a change
933         /// by this author in the document; otherwise set it to 'false'.
934         AuthorList::Authors::const_iterator a_it = params().authors().begin();
935         AuthorList::Authors::const_iterator a_end = params().authors().end();
936         for (; a_it != a_end; ++a_it)
937                 a_it->second.setUsed(false);
938
939         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
940         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
941         for ( ; it != end; ++it)
942                 it->checkAuthors(params().authors());
943
944         // now write out the buffer parameters.
945         ofs << "\\begin_header\n";
946         params().writeFile(ofs);
947         ofs << "\\end_header\n";
948
949         // write the text
950         ofs << "\n\\begin_body\n";
951         text().write(*this, ofs);
952         ofs << "\n\\end_body\n";
953
954         // Write marker that shows file is complete
955         ofs << "\\end_document" << endl;
956
957         // Shouldn't really be needed....
958         //ofs.close();
959
960         // how to check if close went ok?
961         // Following is an attempt... (BE 20001011)
962
963         // good() returns false if any error occured, including some
964         //        formatting error.
965         // bad()  returns true if something bad happened in the buffer,
966         //        which should include file system full errors.
967
968         bool status = true;
969         if (!ofs) {
970                 status = false;
971                 lyxerr << "File was not closed properly." << endl;
972         }
973
974         return status;
975 }
976
977
978 bool Buffer::makeLaTeXFile(FileName const & fname,
979                            string const & original_path,
980                            OutputParams const & runparams,
981                            bool output_preamble, bool output_body) const
982 {
983         string const encoding = runparams.encoding->iconvName();
984         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
985
986         ofdocstream ofs;
987         try { ofs.reset(encoding); }
988         catch (iconv_codecvt_facet_exception & e) {
989                 lyxerr << "Caught iconv exception: " << e.what() << endl;
990                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
991                         "verify that the support software for your encoding (%1$s) is "
992                         "properly installed"), from_ascii(encoding)));
993                 return false;
994         }
995         if (!openFileWrite(ofs, fname))
996                 return false;
997
998         //TexStream ts(ofs.rdbuf(), &texrow());
999         ErrorList & errorList = d->errorLists["Export"];
1000         errorList.clear();
1001         bool failed_export = false;
1002         try {
1003                 d->texrow.reset();
1004                 writeLaTeXSource(ofs, original_path,
1005                       runparams, output_preamble, output_body);
1006         }
1007         catch (EncodingException & e) {
1008                 odocstringstream ods;
1009                 ods.put(e.failed_char);
1010                 ostringstream oss;
1011                 oss << "0x" << hex << e.failed_char << dec;
1012                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1013                                           " (code point %2$s)"),
1014                                           ods.str(), from_utf8(oss.str()));
1015                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1016                                 "representable in the chosen encoding.\n"
1017                                 "Changing the document encoding to utf8 could help."),
1018                                 e.par_id, e.pos, e.pos + 1));
1019                 failed_export = true;
1020         }
1021         catch (iconv_codecvt_facet_exception & e) {
1022                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1023                         _(e.what()), -1, 0, 0));
1024                 failed_export = true;
1025         }
1026         catch (exception const & e) {
1027                 errorList.push_back(ErrorItem(_("conversion failed"),
1028                         _(e.what()), -1, 0, 0));
1029                 failed_export = true;
1030         }
1031         catch (...) {
1032                 lyxerr << "Caught some really weird exception..." << endl;
1033                 lyx_exit(1);
1034         }
1035
1036         ofs.close();
1037         if (ofs.fail()) {
1038                 failed_export = true;
1039                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1040         }
1041
1042         errors("Export");
1043         return !failed_export;
1044 }
1045
1046
1047 void Buffer::writeLaTeXSource(odocstream & os,
1048                            string const & original_path,
1049                            OutputParams const & runparams_in,
1050                            bool const output_preamble, bool const output_body) const
1051 {
1052         // The child documents, if any, shall be already loaded at this point.
1053
1054         OutputParams runparams = runparams_in;
1055
1056         // Classify the unicode characters appearing in math insets
1057         Encodings::initUnicodeMath(*this);
1058
1059         // validate the buffer.
1060         LYXERR(Debug::LATEX, "  Validating buffer...");
1061         LaTeXFeatures features(*this, params(), runparams);
1062         validate(features);
1063         LYXERR(Debug::LATEX, "  Buffer validation done.");
1064
1065         // The starting paragraph of the coming rows is the
1066         // first paragraph of the document. (Asger)
1067         if (output_preamble && runparams.nice) {
1068                 os << "%% LyX " << lyx_version << " created this file.  "
1069                         "For more info, see http://www.lyx.org/.\n"
1070                         "%% Do not edit unless you really know what "
1071                         "you are doing.\n";
1072                 d->texrow.newline();
1073                 d->texrow.newline();
1074         }
1075         LYXERR(Debug::INFO, "lyx document header finished");
1076
1077         // Don't move this behind the parent_buffer=0 code below,
1078         // because then the macros will not get the right "redefinition"
1079         // flag as they don't see the parent macros which are output before.
1080         updateMacros();
1081
1082         // fold macros if possible, still with parent buffer as the
1083         // macros will be put in the prefix anyway.
1084         updateMacroInstances();
1085
1086         // There are a few differences between nice LaTeX and usual files:
1087         // usual is \batchmode and has a
1088         // special input@path to allow the including of figures
1089         // with either \input or \includegraphics (what figinsets do).
1090         // input@path is set when the actual parameter
1091         // original_path is set. This is done for usual tex-file, but not
1092         // for nice-latex-file. (Matthias 250696)
1093         // Note that input@path is only needed for something the user does
1094         // in the preamble, included .tex files or ERT, files included by
1095         // LyX work without it.
1096         if (output_preamble) {
1097                 if (!runparams.nice) {
1098                         // code for usual, NOT nice-latex-file
1099                         os << "\\batchmode\n"; // changed
1100                         // from \nonstopmode
1101                         d->texrow.newline();
1102                 }
1103                 if (!original_path.empty()) {
1104                         // FIXME UNICODE
1105                         // We don't know the encoding of inputpath
1106                         docstring const inputpath = from_utf8(latex_path(original_path));
1107                         os << "\\makeatletter\n"
1108                            << "\\def\\input@path{{"
1109                            << inputpath << "/}}\n"
1110                            << "\\makeatother\n";
1111                         d->texrow.newline();
1112                         d->texrow.newline();
1113                         d->texrow.newline();
1114                 }
1115
1116                 // get parent macros (if this buffer has a parent) which will be
1117                 // written at the document begin further down.
1118                 MacroSet parentMacros;
1119                 listParentMacros(parentMacros, features);
1120
1121                 // Write the preamble
1122                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1123
1124                 runparams.use_japanese = features.isRequired("japanese");
1125
1126                 if (!output_body)
1127                         return;
1128
1129                 // make the body.
1130                 os << "\\begin{document}\n";
1131                 d->texrow.newline();
1132
1133                 // output the parent macros
1134                 MacroSet::iterator it = parentMacros.begin();
1135                 MacroSet::iterator end = parentMacros.end();
1136                 for (; it != end; ++it)
1137                         (*it)->write(os, true);
1138         } // output_preamble
1139
1140         d->texrow.start(paragraphs().begin()->id(), 0);
1141
1142         LYXERR(Debug::INFO, "preamble finished, now the body.");
1143
1144         // if we are doing a real file with body, even if this is the
1145         // child of some other buffer, let's cut the link here.
1146         // This happens for example if only a child document is printed.
1147         Buffer const * save_parent = 0;
1148         if (output_preamble) {
1149                 save_parent = d->parent_buffer;
1150                 d->parent_buffer = 0;
1151         }
1152
1153         // the real stuff
1154         latexParagraphs(*this, text(), os, d->texrow, runparams);
1155
1156         // Restore the parenthood if needed
1157         if (output_preamble)
1158                 d->parent_buffer = save_parent;
1159
1160         // add this just in case after all the paragraphs
1161         os << endl;
1162         d->texrow.newline();
1163
1164         if (output_preamble) {
1165                 os << "\\end{document}\n";
1166                 d->texrow.newline();
1167                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1168         } else {
1169                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1170         }
1171         runparams_in.encoding = runparams.encoding;
1172
1173         // Just to be sure. (Asger)
1174         d->texrow.newline();
1175
1176         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1177         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1178 }
1179
1180
1181 bool Buffer::isLatex() const
1182 {
1183         return params().documentClass().outputType() == LATEX;
1184 }
1185
1186
1187 bool Buffer::isLiterate() const
1188 {
1189         return params().documentClass().outputType() == LITERATE;
1190 }
1191
1192
1193 bool Buffer::isDocBook() const
1194 {
1195         return params().documentClass().outputType() == DOCBOOK;
1196 }
1197
1198
1199 void Buffer::makeDocBookFile(FileName const & fname,
1200                               OutputParams const & runparams,
1201                               bool const body_only) const
1202 {
1203         LYXERR(Debug::LATEX, "makeDocBookFile...");
1204
1205         ofdocstream ofs;
1206         if (!openFileWrite(ofs, fname))
1207                 return;
1208
1209         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1210
1211         ofs.close();
1212         if (ofs.fail())
1213                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1214 }
1215
1216
1217 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1218                              OutputParams const & runparams,
1219                              bool const only_body) const
1220 {
1221         LaTeXFeatures features(*this, params(), runparams);
1222         validate(features);
1223
1224         d->texrow.reset();
1225
1226         DocumentClass const & tclass = params().documentClass();
1227         string const top_element = tclass.latexname();
1228
1229         if (!only_body) {
1230                 if (runparams.flavor == OutputParams::XML)
1231                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1232
1233                 // FIXME UNICODE
1234                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1235
1236                 // FIXME UNICODE
1237                 if (! tclass.class_header().empty())
1238                         os << from_ascii(tclass.class_header());
1239                 else if (runparams.flavor == OutputParams::XML)
1240                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1241                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1242                 else
1243                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1244
1245                 docstring preamble = from_utf8(params().preamble);
1246                 if (runparams.flavor != OutputParams::XML ) {
1247                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1248                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1249                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1250                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1251                 }
1252
1253                 string const name = runparams.nice
1254                         ? changeExtension(absFileName(), ".sgml") : fname;
1255                 preamble += features.getIncludedFiles(name);
1256                 preamble += features.getLyXSGMLEntities();
1257
1258                 if (!preamble.empty()) {
1259                         os << "\n [ " << preamble << " ]";
1260                 }
1261                 os << ">\n\n";
1262         }
1263
1264         string top = top_element;
1265         top += " lang=\"";
1266         if (runparams.flavor == OutputParams::XML)
1267                 top += params().language->code();
1268         else
1269                 top += params().language->code().substr(0, 2);
1270         top += '"';
1271
1272         if (!params().options.empty()) {
1273                 top += ' ';
1274                 top += params().options;
1275         }
1276
1277         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1278             << " file was created by LyX " << lyx_version
1279             << "\n  See http://www.lyx.org/ for more information -->\n";
1280
1281         params().documentClass().counters().reset();
1282
1283         updateMacros();
1284
1285         sgml::openTag(os, top);
1286         os << '\n';
1287         docbookParagraphs(paragraphs(), *this, os, runparams);
1288         sgml::closeTag(os, top_element);
1289 }
1290
1291
1292 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1293 // Other flags: -wall -v0 -x
1294 int Buffer::runChktex()
1295 {
1296         setBusy(true);
1297
1298         // get LaTeX-Filename
1299         FileName const path(temppath());
1300         string const name = addName(path.absFilename(), latexName());
1301         string const org_path = filePath();
1302
1303         PathChanger p(path); // path to LaTeX file
1304         message(_("Running chktex..."));
1305
1306         // Generate the LaTeX file if neccessary
1307         OutputParams runparams(&params().encoding());
1308         runparams.flavor = OutputParams::LATEX;
1309         runparams.nice = false;
1310         makeLaTeXFile(FileName(name), org_path, runparams);
1311
1312         TeXErrors terr;
1313         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1314         int const res = chktex.run(terr); // run chktex
1315
1316         if (res == -1) {
1317                 Alert::error(_("chktex failure"),
1318                              _("Could not run chktex successfully."));
1319         } else if (res > 0) {
1320                 ErrorList & errlist = d->errorLists["ChkTeX"];
1321                 errlist.clear();
1322                 bufferErrors(terr, errlist);
1323         }
1324
1325         setBusy(false);
1326
1327         errors("ChkTeX");
1328
1329         return res;
1330 }
1331
1332
1333 void Buffer::validate(LaTeXFeatures & features) const
1334 {
1335         params().validate(features);
1336
1337         updateMacros();
1338
1339         for_each(paragraphs().begin(), paragraphs().end(),
1340                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1341
1342         if (lyxerr.debugging(Debug::LATEX)) {
1343                 features.showStruct();
1344         }
1345 }
1346
1347
1348 void Buffer::getLabelList(vector<docstring> & list) const
1349 {
1350         // If this is a child document, use the parent's list instead.
1351         if (d->parent_buffer) {
1352                 d->parent_buffer->getLabelList(list);
1353                 return;
1354         }
1355
1356         list.clear();
1357         Toc & toc = d->toc_backend.toc("label");
1358         TocIterator toc_it = toc.begin();
1359         TocIterator end = toc.end();
1360         for (; toc_it != end; ++toc_it) {
1361                 if (toc_it->depth() == 0)
1362                         list.push_back(toc_it->str());
1363         }
1364 }
1365
1366
1367 void Buffer::updateBibfilesCache() const
1368 {
1369         // If this is a child document, use the parent's cache instead.
1370         if (d->parent_buffer) {
1371                 d->parent_buffer->updateBibfilesCache();
1372                 return;
1373         }
1374
1375         d->bibfilesCache_.clear();
1376         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1377                 if (it->lyxCode() == BIBTEX_CODE) {
1378                         InsetBibtex const & inset =
1379                                 static_cast<InsetBibtex const &>(*it);
1380                         support::FileNameList const bibfiles = inset.getBibFiles();
1381                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1382                                 bibfiles.begin(),
1383                                 bibfiles.end());
1384                 } else if (it->lyxCode() == INCLUDE_CODE) {
1385                         InsetInclude & inset =
1386                                 static_cast<InsetInclude &>(*it);
1387                         inset.updateBibfilesCache();
1388                         support::FileNameList const & bibfiles =
1389                                         inset.getBibfilesCache(*this);
1390                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1391                                 bibfiles.begin(),
1392                                 bibfiles.end());
1393                 }
1394         }
1395         // the bibinfo cache is now invalid
1396         d->bibinfoCacheValid_ = false;
1397 }
1398
1399
1400 void Buffer::invalidateBibinfoCache()
1401 {
1402         d->bibinfoCacheValid_ = false;
1403 }
1404
1405
1406 support::FileNameList const & Buffer::getBibfilesCache() const
1407 {
1408         // If this is a child document, use the parent's cache instead.
1409         if (d->parent_buffer)
1410                 return d->parent_buffer->getBibfilesCache();
1411
1412         // We update the cache when first used instead of at loading time.
1413         if (d->bibfilesCache_.empty())
1414                 const_cast<Buffer *>(this)->updateBibfilesCache();
1415
1416         return d->bibfilesCache_;
1417 }
1418
1419
1420 BiblioInfo const & Buffer::masterBibInfo() const
1421 {
1422         // if this is a child document and the parent is already loaded
1423         // use the parent's list instead  [ale990412]
1424         Buffer const * const tmp = masterBuffer();
1425         LASSERT(tmp, /**/);
1426         if (tmp != this)
1427                 return tmp->masterBibInfo();
1428         return localBibInfo();
1429 }
1430
1431
1432 BiblioInfo const & Buffer::localBibInfo() const
1433 {
1434         if (d->bibinfoCacheValid_) {
1435                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1436                 // compare the cached timestamps with the actual ones.
1437                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1438                 support::FileNameList::const_iterator en = bibfilesCache.end();
1439                 for (; ei != en; ++ ei) {
1440                         time_t lastw = ei->lastModified();
1441                         if (lastw != d->bibfileStatus_[*ei]) {
1442                                 d->bibinfoCacheValid_ = false;
1443                                 d->bibfileStatus_[*ei] = lastw;
1444                                 break;
1445                         }
1446                 }
1447         }
1448
1449         if (!d->bibinfoCacheValid_) {
1450                 d->bibinfo_.clear();
1451                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1452                         it->fillWithBibKeys(d->bibinfo_, it);
1453                 d->bibinfoCacheValid_ = true;
1454         }
1455         return d->bibinfo_;
1456 }
1457
1458
1459 bool Buffer::isDepClean(string const & name) const
1460 {
1461         DepClean::const_iterator const it = d->dep_clean.find(name);
1462         if (it == d->dep_clean.end())
1463                 return true;
1464         return it->second;
1465 }
1466
1467
1468 void Buffer::markDepClean(string const & name)
1469 {
1470         d->dep_clean[name] = true;
1471 }
1472
1473
1474 bool Buffer::dispatch(string const & command, bool * result)
1475 {
1476         return dispatch(lyxaction.lookupFunc(command), result);
1477 }
1478
1479
1480 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1481 {
1482         bool dispatched = true;
1483
1484         switch (func.action) {
1485                 case LFUN_BUFFER_EXPORT: {
1486                         bool const tmp = doExport(to_utf8(func.argument()), false);
1487                         if (result)
1488                                 *result = tmp;
1489                         break;
1490                 }
1491
1492                 case LFUN_BRANCH_ACTIVATE:
1493                 case LFUN_BRANCH_DEACTIVATE: {
1494                         BranchList & branchList = params().branchlist();
1495                         docstring const branchName = func.argument();
1496                         Branch * branch = branchList.find(branchName);
1497                         if (!branch)
1498                                 LYXERR0("Branch " << branchName << " does not exist.");
1499                         else
1500                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1501                         if (result)
1502                                 *result = true;
1503                 }
1504
1505                 default:
1506                         dispatched = false;
1507         }
1508         return dispatched;
1509 }
1510
1511
1512 void Buffer::changeLanguage(Language const * from, Language const * to)
1513 {
1514         LASSERT(from, /**/);
1515         LASSERT(to, /**/);
1516
1517         for_each(par_iterator_begin(),
1518                  par_iterator_end(),
1519                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1520 }
1521
1522
1523 bool Buffer::isMultiLingual() const
1524 {
1525         ParConstIterator end = par_iterator_end();
1526         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1527                 if (it->isMultiLingual(params()))
1528                         return true;
1529
1530         return false;
1531 }
1532
1533
1534 DocIterator Buffer::getParFromID(int const id) const
1535 {
1536         Buffer * buf = const_cast<Buffer *>(this);
1537         if (id < 0) {
1538                 // John says this is called with id == -1 from undo
1539                 lyxerr << "getParFromID(), id: " << id << endl;
1540                 return doc_iterator_end(buf);
1541         }
1542
1543         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1544                 if (it.paragraph().id() == id)
1545                         return it;
1546
1547         return doc_iterator_end(buf);
1548 }
1549
1550
1551 bool Buffer::hasParWithID(int const id) const
1552 {
1553         return !getParFromID(id).atEnd();
1554 }
1555
1556
1557 ParIterator Buffer::par_iterator_begin()
1558 {
1559         return ParIterator(doc_iterator_begin(this));
1560 }
1561
1562
1563 ParIterator Buffer::par_iterator_end()
1564 {
1565         return ParIterator(doc_iterator_end(this));
1566 }
1567
1568
1569 ParConstIterator Buffer::par_iterator_begin() const
1570 {
1571         return ParConstIterator(doc_iterator_begin(this));
1572 }
1573
1574
1575 ParConstIterator Buffer::par_iterator_end() const
1576 {
1577         return ParConstIterator(doc_iterator_end(this));
1578 }
1579
1580
1581 Language const * Buffer::language() const
1582 {
1583         return params().language;
1584 }
1585
1586
1587 docstring const Buffer::B_(string const & l10n) const
1588 {
1589         return params().B_(l10n);
1590 }
1591
1592
1593 bool Buffer::isClean() const
1594 {
1595         return d->lyx_clean;
1596 }
1597
1598
1599 bool Buffer::isBakClean() const
1600 {
1601         return d->bak_clean;
1602 }
1603
1604
1605 bool Buffer::isExternallyModified(CheckMethod method) const
1606 {
1607         LASSERT(d->filename.exists(), /**/);
1608         // if method == timestamp, check timestamp before checksum
1609         return (method == checksum_method
1610                 || d->timestamp_ != d->filename.lastModified())
1611                 && d->checksum_ != d->filename.checksum();
1612 }
1613
1614
1615 void Buffer::saveCheckSum(FileName const & file) const
1616 {
1617         if (file.exists()) {
1618                 d->timestamp_ = file.lastModified();
1619                 d->checksum_ = file.checksum();
1620         } else {
1621                 // in the case of save to a new file.
1622                 d->timestamp_ = 0;
1623                 d->checksum_ = 0;
1624         }
1625 }
1626
1627
1628 void Buffer::markClean() const
1629 {
1630         if (!d->lyx_clean) {
1631                 d->lyx_clean = true;
1632                 updateTitles();
1633         }
1634         // if the .lyx file has been saved, we don't need an
1635         // autosave
1636         d->bak_clean = true;
1637 }
1638
1639
1640 void Buffer::markBakClean() const
1641 {
1642         d->bak_clean = true;
1643 }
1644
1645
1646 void Buffer::setUnnamed(bool flag)
1647 {
1648         d->unnamed = flag;
1649 }
1650
1651
1652 bool Buffer::isUnnamed() const
1653 {
1654         return d->unnamed;
1655 }
1656
1657
1658 // FIXME: this function should be moved to buffer_pimpl.C
1659 void Buffer::markDirty()
1660 {
1661         if (d->lyx_clean) {
1662                 d->lyx_clean = false;
1663                 updateTitles();
1664         }
1665         d->bak_clean = false;
1666
1667         DepClean::iterator it = d->dep_clean.begin();
1668         DepClean::const_iterator const end = d->dep_clean.end();
1669
1670         for (; it != end; ++it)
1671                 it->second = false;
1672 }
1673
1674
1675 FileName Buffer::fileName() const
1676 {
1677         return d->filename;
1678 }
1679
1680
1681 string Buffer::absFileName() const
1682 {
1683         return d->filename.absFilename();
1684 }
1685
1686
1687 string Buffer::filePath() const
1688 {
1689         return d->filename.onlyPath().absFilename() + "/";
1690 }
1691
1692
1693 bool Buffer::isReadonly() const
1694 {
1695         return d->read_only;
1696 }
1697
1698
1699 void Buffer::setParent(Buffer const * buffer)
1700 {
1701         // Avoids recursive include.
1702         d->parent_buffer = buffer == this ? 0 : buffer;
1703         updateMacros();
1704 }
1705
1706
1707 Buffer const * Buffer::parent() const
1708 {
1709         return d->parent_buffer;
1710 }
1711
1712
1713 void Buffer::collectRelatives(BufferSet & bufs) const
1714 {
1715         bufs.insert(this);
1716         if (parent())
1717                 parent()->collectRelatives(bufs);
1718
1719         // loop over children
1720         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1721         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1722         for (; it != end; ++it)
1723                 bufs.insert(const_cast<Buffer *>(it->first));
1724 }
1725
1726
1727 std::vector<Buffer const *> Buffer::allRelatives() const
1728 {
1729         BufferSet bufs;
1730         collectRelatives(bufs);
1731         BufferSet::iterator it = bufs.begin();
1732         std::vector<Buffer const *> ret;
1733         for (; it != bufs.end(); ++it)
1734                 ret.push_back(*it);
1735         return ret;
1736 }
1737
1738
1739 Buffer const * Buffer::masterBuffer() const
1740 {
1741         if (!d->parent_buffer)
1742                 return this;
1743
1744         return d->parent_buffer->masterBuffer();
1745 }
1746
1747
1748 bool Buffer::isChild(Buffer * child) const
1749 {
1750         return d->children_positions.find(child) != d->children_positions.end();
1751 }
1752
1753
1754 DocIterator Buffer::firstChildPosition(Buffer const * child)
1755 {
1756         Impl::BufferPositionMap::iterator it;
1757         it = d->children_positions.find(child);
1758         if (it == d->children_positions.end())
1759                 return DocIterator(this);
1760         return it->second;
1761 }
1762
1763
1764 template<typename M>
1765 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1766 {
1767         if (m.empty())
1768                 return m.end();
1769
1770         typename M::iterator it = m.lower_bound(x);
1771         if (it == m.begin())
1772                 return m.end();
1773
1774         it--;
1775         return it;
1776 }
1777
1778
1779 MacroData const * Buffer::getBufferMacro(docstring const & name,
1780                                          DocIterator const & pos) const
1781 {
1782         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1783
1784         // if paragraphs have no macro context set, pos will be empty
1785         if (pos.empty())
1786                 return 0;
1787
1788         // we haven't found anything yet
1789         DocIterator bestPos = par_iterator_begin();
1790         MacroData const * bestData = 0;
1791
1792         // find macro definitions for name
1793         Impl::NamePositionScopeMacroMap::iterator nameIt
1794                 = d->macros.find(name);
1795         if (nameIt != d->macros.end()) {
1796                 // find last definition in front of pos or at pos itself
1797                 Impl::PositionScopeMacroMap::const_iterator it
1798                         = greatest_below(nameIt->second, pos);
1799                 if (it != nameIt->second.end()) {
1800                         while (true) {
1801                                 // scope ends behind pos?
1802                                 if (pos < it->second.first) {
1803                                         // Looks good, remember this. If there
1804                                         // is no external macro behind this,
1805                                         // we found the right one already.
1806                                         bestPos = it->first;
1807                                         bestData = &it->second.second;
1808                                         break;
1809                                 }
1810
1811                                 // try previous macro if there is one
1812                                 if (it == nameIt->second.begin())
1813                                         break;
1814                                 it--;
1815                         }
1816                 }
1817         }
1818
1819         // find macros in included files
1820         Impl::PositionScopeBufferMap::const_iterator it
1821                 = greatest_below(d->position_to_children, pos);
1822         if (it == d->position_to_children.end())
1823                 // no children before
1824                 return bestData;
1825
1826         while (true) {
1827                 // do we know something better (i.e. later) already?
1828                 if (it->first < bestPos )
1829                         break;
1830
1831                 // scope ends behind pos?
1832                 if (pos < it->second.first) {
1833                         // look for macro in external file
1834                         d->macro_lock = true;
1835                         MacroData const * data
1836                         = it->second.second->getMacro(name, false);
1837                         d->macro_lock = false;
1838                         if (data) {
1839                                 bestPos = it->first;
1840                                 bestData = data;
1841                                 break;
1842                         }
1843                 }
1844
1845                 // try previous file if there is one
1846                 if (it == d->position_to_children.begin())
1847                         break;
1848                 --it;
1849         }
1850
1851         // return the best macro we have found
1852         return bestData;
1853 }
1854
1855
1856 MacroData const * Buffer::getMacro(docstring const & name,
1857         DocIterator const & pos, bool global) const
1858 {
1859         if (d->macro_lock)
1860                 return 0;
1861
1862         // query buffer macros
1863         MacroData const * data = getBufferMacro(name, pos);
1864         if (data != 0)
1865                 return data;
1866
1867         // If there is a master buffer, query that
1868         if (d->parent_buffer) {
1869                 d->macro_lock = true;
1870                 MacroData const * macro = d->parent_buffer->getMacro(
1871                         name, *this, false);
1872                 d->macro_lock = false;
1873                 if (macro)
1874                         return macro;
1875         }
1876
1877         if (global) {
1878                 data = MacroTable::globalMacros().get(name);
1879                 if (data != 0)
1880                         return data;
1881         }
1882
1883         return 0;
1884 }
1885
1886
1887 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1888 {
1889         // set scope end behind the last paragraph
1890         DocIterator scope = par_iterator_begin();
1891         scope.pit() = scope.lastpit() + 1;
1892
1893         return getMacro(name, scope, global);
1894 }
1895
1896
1897 MacroData const * Buffer::getMacro(docstring const & name,
1898         Buffer const & child, bool global) const
1899 {
1900         // look where the child buffer is included first
1901         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1902         if (it == d->children_positions.end())
1903                 return 0;
1904
1905         // check for macros at the inclusion position
1906         return getMacro(name, it->second, global);
1907 }
1908
1909
1910 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1911 {
1912         pit_type lastpit = it.lastpit();
1913
1914         // look for macros in each paragraph
1915         while (it.pit() <= lastpit) {
1916                 Paragraph & par = it.paragraph();
1917
1918                 // iterate over the insets of the current paragraph
1919                 InsetList const & insets = par.insetList();
1920                 InsetList::const_iterator iit = insets.begin();
1921                 InsetList::const_iterator end = insets.end();
1922                 for (; iit != end; ++iit) {
1923                         it.pos() = iit->pos;
1924
1925                         // is it a nested text inset?
1926                         if (iit->inset->asInsetText()) {
1927                                 // Inset needs its own scope?
1928                                 InsetText const * itext
1929                                 = iit->inset->asInsetText();
1930                                 bool newScope = itext->isMacroScope();
1931
1932                                 // scope which ends just behind the inset
1933                                 DocIterator insetScope = it;
1934                                 ++insetScope.pos();
1935
1936                                 // collect macros in inset
1937                                 it.push_back(CursorSlice(*iit->inset));
1938                                 updateMacros(it, newScope ? insetScope : scope);
1939                                 it.pop_back();
1940                                 continue;
1941                         }
1942
1943                         // is it an external file?
1944                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1945                                 // get buffer of external file
1946                                 InsetInclude const & inset
1947                                         = static_cast<InsetInclude const &>(*iit->inset);
1948                                 d->macro_lock = true;
1949                                 Buffer * child = inset.loadIfNeeded(*this);
1950                                 d->macro_lock = false;
1951                                 if (!child)
1952                                         continue;
1953
1954                                 // register its position, but only when it is
1955                                 // included first in the buffer
1956                                 if (d->children_positions.find(child)
1957                                         == d->children_positions.end())
1958                                         d->children_positions[child] = it;
1959
1960                                 // register child with its scope
1961                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1962                                 continue;
1963                         }
1964
1965                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1966                                 continue;
1967
1968                         // get macro data
1969                         MathMacroTemplate & macroTemplate
1970                         = static_cast<MathMacroTemplate &>(*iit->inset);
1971                         MacroContext mc(*this, it);
1972                         macroTemplate.updateToContext(mc);
1973
1974                         // valid?
1975                         bool valid = macroTemplate.validMacro();
1976                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1977                         // then the BufferView's cursor will be invalid in
1978                         // some cases which leads to crashes.
1979                         if (!valid)
1980                                 continue;
1981
1982                         // register macro
1983                         d->macros[macroTemplate.name()][it] =
1984                                 Impl::ScopeMacro(scope, MacroData(*this, it));
1985                 }
1986
1987                 // next paragraph
1988                 it.pit()++;
1989                 it.pos() = 0;
1990         }
1991 }
1992
1993
1994 void Buffer::updateMacros() const
1995 {
1996         if (d->macro_lock)
1997                 return;
1998
1999         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2000
2001         // start with empty table
2002         d->macros.clear();
2003         d->children_positions.clear();
2004         d->position_to_children.clear();
2005
2006         // Iterate over buffer, starting with first paragraph
2007         // The scope must be bigger than any lookup DocIterator
2008         // later. For the global lookup, lastpit+1 is used, hence
2009         // we use lastpit+2 here.
2010         DocIterator it = par_iterator_begin();
2011         DocIterator outerScope = it;
2012         outerScope.pit() = outerScope.lastpit() + 2;
2013         updateMacros(it, outerScope);
2014 }
2015
2016
2017 void Buffer::updateMacroInstances() const
2018 {
2019         LYXERR(Debug::MACROS, "updateMacroInstances for "
2020                 << d->filename.onlyFileName());
2021         DocIterator it = doc_iterator_begin(this);
2022         DocIterator end = doc_iterator_end(this);
2023         for (; it != end; it.forwardPos()) {
2024                 // look for MathData cells in InsetMathNest insets
2025                 Inset * inset = it.nextInset();
2026                 if (!inset)
2027                         continue;
2028
2029                 InsetMath * minset = inset->asInsetMath();
2030                 if (!minset)
2031                         continue;
2032
2033                 // update macro in all cells of the InsetMathNest
2034                 DocIterator::idx_type n = minset->nargs();
2035                 MacroContext mc = MacroContext(*this, it);
2036                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2037                         MathData & data = minset->cell(i);
2038                         data.updateMacros(0, mc);
2039                 }
2040         }
2041 }
2042
2043
2044 void Buffer::listMacroNames(MacroNameSet & macros) const
2045 {
2046         if (d->macro_lock)
2047                 return;
2048
2049         d->macro_lock = true;
2050
2051         // loop over macro names
2052         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2053         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2054         for (; nameIt != nameEnd; ++nameIt)
2055                 macros.insert(nameIt->first);
2056
2057         // loop over children
2058         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2059         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2060         for (; it != end; ++it)
2061                 it->first->listMacroNames(macros);
2062
2063         // call parent
2064         if (d->parent_buffer)
2065                 d->parent_buffer->listMacroNames(macros);
2066
2067         d->macro_lock = false;
2068 }
2069
2070
2071 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2072 {
2073         if (!d->parent_buffer)
2074                 return;
2075
2076         MacroNameSet names;
2077         d->parent_buffer->listMacroNames(names);
2078
2079         // resolve macros
2080         MacroNameSet::iterator it = names.begin();
2081         MacroNameSet::iterator end = names.end();
2082         for (; it != end; ++it) {
2083                 // defined?
2084                 MacroData const * data =
2085                 d->parent_buffer->getMacro(*it, *this, false);
2086                 if (data) {
2087                         macros.insert(data);
2088
2089                         // we cannot access the original MathMacroTemplate anymore
2090                         // here to calls validate method. So we do its work here manually.
2091                         // FIXME: somehow make the template accessible here.
2092                         if (data->optionals() > 0)
2093                                 features.require("xargs");
2094                 }
2095         }
2096 }
2097
2098
2099 Buffer::References & Buffer::references(docstring const & label)
2100 {
2101         if (d->parent_buffer)
2102                 return const_cast<Buffer *>(masterBuffer())->references(label);
2103
2104         RefCache::iterator it = d->ref_cache_.find(label);
2105         if (it != d->ref_cache_.end())
2106                 return it->second.second;
2107
2108         static InsetLabel const * dummy_il = 0;
2109         static References const dummy_refs;
2110         it = d->ref_cache_.insert(
2111                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2112         return it->second.second;
2113 }
2114
2115
2116 Buffer::References const & Buffer::references(docstring const & label) const
2117 {
2118         return const_cast<Buffer *>(this)->references(label);
2119 }
2120
2121
2122 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2123 {
2124         masterBuffer()->d->ref_cache_[label].first = il;
2125 }
2126
2127
2128 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2129 {
2130         return masterBuffer()->d->ref_cache_[label].first;
2131 }
2132
2133
2134 void Buffer::clearReferenceCache() const
2135 {
2136         if (!d->parent_buffer)
2137                 d->ref_cache_.clear();
2138 }
2139
2140
2141 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2142         InsetCode code)
2143 {
2144         //FIXME: This does not work for child documents yet.
2145         LASSERT(code == CITE_CODE, /**/);
2146         // Check if the label 'from' appears more than once
2147         vector<docstring> labels;
2148         string paramName;
2149         BiblioInfo const & keys = masterBibInfo();
2150         BiblioInfo::const_iterator bit  = keys.begin();
2151         BiblioInfo::const_iterator bend = keys.end();
2152
2153         for (; bit != bend; ++bit)
2154                 // FIXME UNICODE
2155                 labels.push_back(bit->first);
2156         paramName = "key";
2157
2158         if (count(labels.begin(), labels.end(), from) > 1)
2159                 return;
2160
2161         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2162                 if (it->lyxCode() == code) {
2163                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2164                         docstring const oldValue = inset.getParam(paramName);
2165                         if (oldValue == from)
2166                                 inset.setParam(paramName, to);
2167                 }
2168         }
2169 }
2170
2171
2172 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2173         pit_type par_end, bool full_source) const
2174 {
2175         OutputParams runparams(&params().encoding());
2176         runparams.nice = true;
2177         runparams.flavor = OutputParams::LATEX;
2178         runparams.linelen = lyxrc.plaintext_linelen;
2179         // No side effect of file copying and image conversion
2180         runparams.dryrun = true;
2181
2182         d->texrow.reset();
2183         if (full_source) {
2184                 os << "% " << _("Preview source code") << "\n\n";
2185                 d->texrow.newline();
2186                 d->texrow.newline();
2187                 if (isDocBook())
2188                         writeDocBookSource(os, absFileName(), runparams, false);
2189                 else
2190                         // latex or literate
2191                         writeLaTeXSource(os, string(), runparams, true, true);
2192         } else {
2193                 runparams.par_begin = par_begin;
2194                 runparams.par_end = par_end;
2195                 if (par_begin + 1 == par_end) {
2196                         os << "% "
2197                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2198                            << "\n\n";
2199                 } else {
2200                         os << "% "
2201                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2202                                         convert<docstring>(par_begin),
2203                                         convert<docstring>(par_end - 1))
2204                            << "\n\n";
2205                 }
2206                 d->texrow.newline();
2207                 d->texrow.newline();
2208                 // output paragraphs
2209                 if (isDocBook())
2210                         docbookParagraphs(paragraphs(), *this, os, runparams);
2211                 else 
2212                         // latex or literate
2213                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2214         }
2215 }
2216
2217
2218 ErrorList & Buffer::errorList(string const & type) const
2219 {
2220         static ErrorList emptyErrorList;
2221         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2222         if (I == d->errorLists.end())
2223                 return emptyErrorList;
2224
2225         return I->second;
2226 }
2227
2228
2229 void Buffer::updateTocItem(std::string const & type,
2230         DocIterator const & dit) const
2231 {
2232         if (gui_)
2233                 gui_->updateTocItem(type, dit);
2234 }
2235
2236
2237 void Buffer::structureChanged() const
2238 {
2239         if (gui_)
2240                 gui_->structureChanged();
2241 }
2242
2243
2244 void Buffer::errors(string const & err) const
2245 {
2246         if (gui_)
2247                 gui_->errors(err);
2248 }
2249
2250
2251 void Buffer::message(docstring const & msg) const
2252 {
2253         if (gui_)
2254                 gui_->message(msg);
2255 }
2256
2257
2258 void Buffer::setBusy(bool on) const
2259 {
2260         if (gui_)
2261                 gui_->setBusy(on);
2262 }
2263
2264
2265 void Buffer::setReadOnly(bool on) const
2266 {
2267         if (d->wa_)
2268                 d->wa_->setReadOnly(on);
2269 }
2270
2271
2272 void Buffer::updateTitles() const
2273 {
2274         if (d->wa_)
2275                 d->wa_->updateTitles();
2276 }
2277
2278
2279 void Buffer::resetAutosaveTimers() const
2280 {
2281         if (gui_)
2282                 gui_->resetAutosaveTimers();
2283 }
2284
2285
2286 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2287 {
2288         gui_ = gui;
2289 }
2290
2291
2292
2293 namespace {
2294
2295 class AutoSaveBuffer : public ForkedProcess {
2296 public:
2297         ///
2298         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2299                 : buffer_(buffer), fname_(fname) {}
2300         ///
2301         virtual boost::shared_ptr<ForkedProcess> clone() const
2302         {
2303                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2304         }
2305         ///
2306         int start()
2307         {
2308                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2309                                                  from_utf8(fname_.absFilename())));
2310                 return run(DontWait);
2311         }
2312 private:
2313         ///
2314         virtual int generateChild();
2315         ///
2316         Buffer const & buffer_;
2317         FileName fname_;
2318 };
2319
2320
2321 int AutoSaveBuffer::generateChild()
2322 {
2323         // tmp_ret will be located (usually) in /tmp
2324         // will that be a problem?
2325         // Note that this calls ForkedCalls::fork(), so it's
2326         // ok cross-platform.
2327         pid_t const pid = fork();
2328         // If you want to debug the autosave
2329         // you should set pid to -1, and comment out the fork.
2330         if (pid != 0 && pid != -1)
2331                 return pid;
2332
2333         // pid = -1 signifies that lyx was unable
2334         // to fork. But we will do the save
2335         // anyway.
2336         bool failed = false;
2337         FileName const tmp_ret = FileName::tempName("lyxauto");
2338         if (!tmp_ret.empty()) {
2339                 buffer_.writeFile(tmp_ret);
2340                 // assume successful write of tmp_ret
2341                 if (!tmp_ret.moveTo(fname_))
2342                         failed = true;
2343         } else
2344                 failed = true;
2345
2346         if (failed) {
2347                 // failed to write/rename tmp_ret so try writing direct
2348                 if (!buffer_.writeFile(fname_)) {
2349                         // It is dangerous to do this in the child,
2350                         // but safe in the parent, so...
2351                         if (pid == -1) // emit message signal.
2352                                 buffer_.message(_("Autosave failed!"));
2353                 }
2354         }
2355
2356         if (pid == 0) // we are the child so...
2357                 _exit(0);
2358
2359         return pid;
2360 }
2361
2362 } // namespace anon
2363
2364
2365 // Perfect target for a thread...
2366 void Buffer::autoSave() const
2367 {
2368         if (isBakClean() || isReadonly()) {
2369                 // We don't save now, but we'll try again later
2370                 resetAutosaveTimers();
2371                 return;
2372         }
2373
2374         // emit message signal.
2375         message(_("Autosaving current document..."));
2376
2377         // create autosave filename
2378         string fname = filePath();
2379         fname += '#';
2380         fname += d->filename.onlyFileName();
2381         fname += '#';
2382
2383         AutoSaveBuffer autosave(*this, FileName(fname));
2384         autosave.start();
2385
2386         markBakClean();
2387         resetAutosaveTimers();
2388 }
2389
2390
2391 string Buffer::bufferFormat() const
2392 {
2393         if (isDocBook())
2394                 return "docbook";
2395         if (isLiterate())
2396                 return "literate";
2397         if (params().encoding().package() == Encoding::japanese)
2398                 return "platex";
2399         return "latex";
2400 }
2401
2402
2403 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2404         string & result_file) const
2405 {
2406         string backend_format;
2407         OutputParams runparams(&params().encoding());
2408         runparams.flavor = OutputParams::LATEX;
2409         runparams.linelen = lyxrc.plaintext_linelen;
2410         vector<string> backs = backends();
2411         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2412                 // Get shortest path to format
2413                 Graph::EdgePath path;
2414                 for (vector<string>::const_iterator it = backs.begin();
2415                      it != backs.end(); ++it) {
2416                         Graph::EdgePath p = theConverters().getPath(*it, format);
2417                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2418                                 backend_format = *it;
2419                                 path = p;
2420                         }
2421                 }
2422                 if (!path.empty())
2423                         runparams.flavor = theConverters().getFlavor(path);
2424                 else {
2425                         Alert::error(_("Couldn't export file"),
2426                                 bformat(_("No information for exporting the format %1$s."),
2427                                    formats.prettyName(format)));
2428                         return false;
2429                 }
2430         } else {
2431                 backend_format = format;
2432                 // FIXME: Don't hardcode format names here, but use a flag
2433                 if (backend_format == "pdflatex")
2434                         runparams.flavor = OutputParams::PDFLATEX;
2435         }
2436
2437         string filename = latexName(false);
2438         filename = addName(temppath(), filename);
2439         filename = changeExtension(filename,
2440                                    formats.extension(backend_format));
2441
2442         // fix macros
2443         updateMacroInstances();
2444
2445         // Plain text backend
2446         if (backend_format == "text")
2447                 writePlaintextFile(*this, FileName(filename), runparams);
2448         // no backend
2449         else if (backend_format == "lyx")
2450                 writeFile(FileName(filename));
2451         // Docbook backend
2452         else if (isDocBook()) {
2453                 runparams.nice = !put_in_tempdir;
2454                 makeDocBookFile(FileName(filename), runparams);
2455         }
2456         // LaTeX backend
2457         else if (backend_format == format) {
2458                 runparams.nice = true;
2459                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2460                         return false;
2461         } else if (!lyxrc.tex_allows_spaces
2462                    && contains(filePath(), ' ')) {
2463                 Alert::error(_("File name error"),
2464                            _("The directory path to the document cannot contain spaces."));
2465                 return false;
2466         } else {
2467                 runparams.nice = false;
2468                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2469                         return false;
2470         }
2471
2472         string const error_type = (format == "program")
2473                 ? "Build" : bufferFormat();
2474         ErrorList & error_list = d->errorLists[error_type];
2475         string const ext = formats.extension(format);
2476         FileName const tmp_result_file(changeExtension(filename, ext));
2477         bool const success = theConverters().convert(this, FileName(filename),
2478                 tmp_result_file, FileName(absFileName()), backend_format, format,
2479                 error_list);
2480         // Emit the signal to show the error list.
2481         if (format != backend_format)
2482                 errors(error_type);
2483         if (!success)
2484                 return false;
2485
2486         if (put_in_tempdir) {
2487                 result_file = tmp_result_file.absFilename();
2488                 return true;
2489         }
2490
2491         result_file = changeExtension(absFileName(), ext);
2492         // We need to copy referenced files (e. g. included graphics
2493         // if format == "dvi") to the result dir.
2494         vector<ExportedFile> const files =
2495                 runparams.exportdata->externalFiles(format);
2496         string const dest = onlyPath(result_file);
2497         CopyStatus status = SUCCESS;
2498         for (vector<ExportedFile>::const_iterator it = files.begin();
2499                 it != files.end() && status != CANCEL; ++it) {
2500                 string const fmt = formats.getFormatFromFile(it->sourceName);
2501                 status = copyFile(fmt, it->sourceName,
2502                         makeAbsPath(it->exportName, dest),
2503                         it->exportName, status == FORCE);
2504         }
2505         if (status == CANCEL) {
2506                 message(_("Document export cancelled."));
2507         } else if (tmp_result_file.exists()) {
2508                 // Finally copy the main file
2509                 status = copyFile(format, tmp_result_file,
2510                         FileName(result_file), result_file,
2511                         status == FORCE);
2512                 message(bformat(_("Document exported as %1$s "
2513                         "to file `%2$s'"),
2514                         formats.prettyName(format),
2515                         makeDisplayPath(result_file)));
2516         } else {
2517                 // This must be a dummy converter like fax (bug 1888)
2518                 message(bformat(_("Document exported as %1$s"),
2519                         formats.prettyName(format)));
2520         }
2521
2522         return true;
2523 }
2524
2525
2526 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2527 {
2528         string result_file;
2529         return doExport(format, put_in_tempdir, result_file);
2530 }
2531
2532
2533 bool Buffer::preview(string const & format) const
2534 {
2535         string result_file;
2536         if (!doExport(format, true, result_file))
2537                 return false;
2538         return formats.view(*this, FileName(result_file), format);
2539 }
2540
2541
2542 bool Buffer::isExportable(string const & format) const
2543 {
2544         vector<string> backs = backends();
2545         for (vector<string>::const_iterator it = backs.begin();
2546              it != backs.end(); ++it)
2547                 if (theConverters().isReachable(*it, format))
2548                         return true;
2549         return false;
2550 }
2551
2552
2553 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2554 {
2555         vector<string> backs = backends();
2556         vector<Format const *> result =
2557                 theConverters().getReachable(backs[0], only_viewable, true);
2558         for (vector<string>::const_iterator it = backs.begin() + 1;
2559              it != backs.end(); ++it) {
2560                 vector<Format const *>  r =
2561                         theConverters().getReachable(*it, only_viewable, false);
2562                 result.insert(result.end(), r.begin(), r.end());
2563         }
2564         return result;
2565 }
2566
2567
2568 vector<string> Buffer::backends() const
2569 {
2570         vector<string> v;
2571         if (params().baseClass()->isTeXClassAvailable()) {
2572                 v.push_back(bufferFormat());
2573                 // FIXME: Don't hardcode format names here, but use a flag
2574                 if (v.back() == "latex")
2575                         v.push_back("pdflatex");
2576         }
2577         v.push_back("text");
2578         v.push_back("lyx");
2579         return v;
2580 }
2581
2582
2583 bool Buffer::readFileHelper(FileName const & s)
2584 {
2585         // File information about normal file
2586         if (!s.exists()) {
2587                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2588                 docstring text = bformat(_("The specified document\n%1$s"
2589                                                      "\ncould not be read."), file);
2590                 Alert::error(_("Could not read document"), text);
2591                 return false;
2592         }
2593
2594         // Check if emergency save file exists and is newer.
2595         FileName const e(s.absFilename() + ".emergency");
2596
2597         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2598                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2599                 docstring const text =
2600                         bformat(_("An emergency save of the document "
2601                                   "%1$s exists.\n\n"
2602                                                "Recover emergency save?"), file);
2603                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2604                                       _("&Recover"),  _("&Load Original"),
2605                                       _("&Cancel")))
2606                 {
2607                 case 0:
2608                         // the file is not saved if we load the emergency file.
2609                         markDirty();
2610                         return readFile(e);
2611                 case 1:
2612                         break;
2613                 default:
2614                         return false;
2615                 }
2616         }
2617
2618         // Now check if autosave file is newer.
2619         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2620
2621         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2622                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2623                 docstring const text =
2624                         bformat(_("The backup of the document "
2625                                   "%1$s is newer.\n\nLoad the "
2626                                                "backup instead?"), file);
2627                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2628                                       _("&Load backup"), _("Load &original"),
2629                                       _("&Cancel") ))
2630                 {
2631                 case 0:
2632                         // the file is not saved if we load the autosave file.
2633                         markDirty();
2634                         return readFile(a);
2635                 case 1:
2636                         // Here we delete the autosave
2637                         a.removeFile();
2638                         break;
2639                 default:
2640                         return false;
2641                 }
2642         }
2643         return readFile(s);
2644 }
2645
2646
2647 bool Buffer::loadLyXFile(FileName const & s)
2648 {
2649         if (s.isReadableFile()) {
2650                 if (readFileHelper(s)) {
2651                         lyxvc().file_found_hook(s);
2652                         if (!s.isWritable())
2653                                 setReadonly(true);
2654                         return true;
2655                 }
2656         } else {
2657                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2658                 // Here we probably should run
2659                 if (LyXVC::file_not_found_hook(s)) {
2660                         docstring const text =
2661                                 bformat(_("Do you want to retrieve the document"
2662                                                        " %1$s from version control?"), file);
2663                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2664                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2665
2666                         if (ret == 0) {
2667                                 // How can we know _how_ to do the checkout?
2668                                 // With the current VC support it has to be,
2669                                 // a RCS file since CVS do not have special ,v files.
2670                                 RCS::retrieve(s);
2671                                 return loadLyXFile(s);
2672                         }
2673                 }
2674         }
2675         return false;
2676 }
2677
2678
2679 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2680 {
2681         TeXErrors::Errors::const_iterator cit = terr.begin();
2682         TeXErrors::Errors::const_iterator end = terr.end();
2683
2684         for (; cit != end; ++cit) {
2685                 int id_start = -1;
2686                 int pos_start = -1;
2687                 int errorRow = cit->error_in_line;
2688                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2689                                                        pos_start);
2690                 int id_end = -1;
2691                 int pos_end = -1;
2692                 do {
2693                         ++errorRow;
2694                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2695                 } while (found && id_start == id_end && pos_start == pos_end);
2696
2697                 errorList.push_back(ErrorItem(cit->error_desc,
2698                         cit->error_text, id_start, pos_start, pos_end));
2699         }
2700 }
2701
2702
2703 void Buffer::updateLabels(bool childonly) const
2704 {
2705         // Use the master text class also for child documents
2706         Buffer const * const master = masterBuffer();
2707         DocumentClass const & textclass = master->params().documentClass();
2708
2709         // keep the buffers to be children in this set. If the call from the
2710         // master comes back we can see which of them were actually seen (i.e.
2711         // via an InsetInclude). The remaining ones in the set need still be updated.
2712         static std::set<Buffer const *> bufToUpdate;
2713         if (!childonly) {
2714                 // If this is a child document start with the master
2715                 if (master != this) {
2716                         bufToUpdate.insert(this);
2717                         master->updateLabels(false);
2718
2719                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2720                         if (bufToUpdate.find(this) == bufToUpdate.end())
2721                                 return;
2722                 }
2723
2724                 // start over the counters in the master
2725                 textclass.counters().reset();
2726         }
2727
2728         // update will be done below for this buffer
2729         bufToUpdate.erase(this);
2730
2731         // update all caches
2732         clearReferenceCache();
2733         inset().setBuffer(const_cast<Buffer &>(*this));
2734         updateMacros();
2735
2736         Buffer & cbuf = const_cast<Buffer &>(*this);
2737
2738         LASSERT(!text().paragraphs().empty(), /**/);
2739
2740         // do the real work
2741         ParIterator parit = cbuf.par_iterator_begin();
2742         updateLabels(parit);
2743
2744         if (master != this)
2745                 // TocBackend update will be done later.
2746                 return;
2747
2748         cbuf.tocBackend().update();
2749         if (!childonly)
2750                 cbuf.structureChanged();
2751 }
2752
2753
2754 static depth_type getDepth(DocIterator const & it)
2755 {
2756         depth_type depth = 0;
2757         for (size_t i = 0 ; i < it.depth() ; ++i)
2758                 if (!it[i].inset().inMathed())
2759                         depth += it[i].paragraph().getDepth() + 1;
2760         // remove 1 since the outer inset does not count
2761         return depth - 1;
2762 }
2763
2764 static depth_type getItemDepth(ParIterator const & it)
2765 {
2766         Paragraph const & par = *it;
2767         LabelType const labeltype = par.layout().labeltype;
2768
2769         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2770                 return 0;
2771
2772         // this will hold the lowest depth encountered up to now.
2773         depth_type min_depth = getDepth(it);
2774         ParIterator prev_it = it;
2775         while (true) {
2776                 if (prev_it.pit())
2777                         --prev_it.top().pit();
2778                 else {
2779                         // start of nested inset: go to outer par
2780                         prev_it.pop_back();
2781                         if (prev_it.empty()) {
2782                                 // start of document: nothing to do
2783                                 return 0;
2784                         }
2785                 }
2786
2787                 // We search for the first paragraph with same label
2788                 // that is not more deeply nested.
2789                 Paragraph & prev_par = *prev_it;
2790                 depth_type const prev_depth = getDepth(prev_it);
2791                 if (labeltype == prev_par.layout().labeltype) {
2792                         if (prev_depth < min_depth)
2793                                 return prev_par.itemdepth + 1;
2794                         if (prev_depth == min_depth)
2795                                 return prev_par.itemdepth;
2796                 }
2797                 min_depth = min(min_depth, prev_depth);
2798                 // small optimization: if we are at depth 0, we won't
2799                 // find anything else
2800                 if (prev_depth == 0)
2801                         return 0;
2802         }
2803 }
2804
2805
2806 static bool needEnumCounterReset(ParIterator const & it)
2807 {
2808         Paragraph const & par = *it;
2809         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2810         depth_type const cur_depth = par.getDepth();
2811         ParIterator prev_it = it;
2812         while (prev_it.pit()) {
2813                 --prev_it.top().pit();
2814                 Paragraph const & prev_par = *prev_it;
2815                 if (prev_par.getDepth() <= cur_depth)
2816                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
2817         }
2818         // start of nested inset: reset
2819         return true;
2820 }
2821
2822
2823 // set the label of a paragraph. This includes the counters.
2824 static void setLabel(Buffer const & buf, ParIterator & it)
2825 {
2826         BufferParams const & bp = buf.masterBuffer()->params();
2827         DocumentClass const & textclass = bp.documentClass();
2828         Paragraph & par = it.paragraph();
2829         Layout const & layout = par.layout();
2830         Counters & counters = textclass.counters();
2831
2832         if (par.params().startOfAppendix()) {
2833                 // FIXME: only the counter corresponding to toplevel
2834                 // sectionning should be reset
2835                 counters.reset();
2836                 counters.appendix(true);
2837         }
2838         par.params().appendix(counters.appendix());
2839
2840         // Compute the item depth of the paragraph
2841         par.itemdepth = getItemDepth(it);
2842
2843         if (layout.margintype == MARGIN_MANUAL) {
2844                 if (par.params().labelWidthString().empty())
2845                         par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2846         } else {
2847                 par.params().labelWidthString(docstring());
2848         }
2849
2850         switch(layout.labeltype) {
2851         case LABEL_COUNTER:
2852                 if (layout.toclevel <= bp.secnumdepth
2853                     && (layout.latextype != LATEX_ENVIRONMENT
2854                         || isFirstInSequence(it.pit(), it.plist()))) {
2855                         counters.step(layout.counter);
2856                         par.params().labelString(
2857                                 par.expandLabel(layout, bp));
2858                 } else
2859                         par.params().labelString(docstring());
2860                 break;
2861
2862         case LABEL_ITEMIZE: {
2863                 // At some point of time we should do something more
2864                 // clever here, like:
2865                 //   par.params().labelString(
2866                 //    bp.user_defined_bullet(par.itemdepth).getText());
2867                 // for now, use a simple hardcoded label
2868                 docstring itemlabel;
2869                 switch (par.itemdepth) {
2870                 case 0:
2871                         itemlabel = char_type(0x2022);
2872                         break;
2873                 case 1:
2874                         itemlabel = char_type(0x2013);
2875                         break;
2876                 case 2:
2877                         itemlabel = char_type(0x2217);
2878                         break;
2879                 case 3:
2880                         itemlabel = char_type(0x2219); // or 0x00b7
2881                         break;
2882                 }
2883                 par.params().labelString(itemlabel);
2884                 break;
2885         }
2886
2887         case LABEL_ENUMERATE: {
2888                 // FIXME: Yes I know this is a really, really! bad solution
2889                 // (Lgb)
2890                 docstring enumcounter = from_ascii("enum");
2891
2892                 switch (par.itemdepth) {
2893                 case 2:
2894                         enumcounter += 'i';
2895                 case 1:
2896                         enumcounter += 'i';
2897                 case 0:
2898                         enumcounter += 'i';
2899                         break;
2900                 case 3:
2901                         enumcounter += "iv";
2902                         break;
2903                 default:
2904                         // not a valid enumdepth...
2905                         break;
2906                 }
2907
2908                 // Maybe we have to reset the enumeration counter.
2909                 if (needEnumCounterReset(it))
2910                         counters.reset(enumcounter);
2911
2912                 counters.step(enumcounter);
2913
2914                 string format;
2915
2916                 switch (par.itemdepth) {
2917                 case 0:
2918                         format = N_("\\arabic{enumi}.");
2919                         break;
2920                 case 1:
2921                         format = N_("(\\alph{enumii})");
2922                         break;
2923                 case 2:
2924                         format = N_("\\roman{enumiii}.");
2925                         break;
2926                 case 3:
2927                         format = N_("\\Alph{enumiv}.");
2928                         break;
2929                 default:
2930                         // not a valid enumdepth...
2931                         break;
2932                 }
2933
2934                 par.params().labelString(counters.counterLabel(
2935                         par.translateIfPossible(from_ascii(format), bp)));
2936
2937                 break;
2938         }
2939
2940         case LABEL_SENSITIVE: {
2941                 string const & type = counters.current_float();
2942                 docstring full_label;
2943                 if (type.empty())
2944                         full_label = buf.B_("Senseless!!! ");
2945                 else {
2946                         docstring name = buf.B_(textclass.floats().getType(type).name());
2947                         if (counters.hasCounter(from_utf8(type))) {
2948                                 counters.step(from_utf8(type));
2949                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
2950                                                      name, 
2951                                                      counters.theCounter(from_utf8(type)));
2952                         } else
2953                                 full_label = bformat(from_ascii("%1$s #:"), name);      
2954                 }
2955                 par.params().labelString(full_label);   
2956                 break;
2957         }
2958
2959         case LABEL_NO_LABEL:
2960                 par.params().labelString(docstring());
2961                 break;
2962
2963         case LABEL_MANUAL:
2964         case LABEL_TOP_ENVIRONMENT:
2965         case LABEL_CENTERED_TOP_ENVIRONMENT:
2966         case LABEL_STATIC:      
2967         case LABEL_BIBLIO:
2968                 par.params().labelString(
2969                         par.translateIfPossible(layout.labelstring(), bp));
2970                 break;
2971         }
2972 }
2973
2974
2975 void Buffer::updateLabels(ParIterator & parit) const
2976 {
2977         LASSERT(parit.pit() == 0, /**/);
2978
2979         // set the position of the text in the buffer to be able
2980         // to resolve macros in it. This has nothing to do with
2981         // labels, but by putting it here we avoid implementing
2982         // a whole bunch of traversal routines just for this call.
2983         parit.text()->setMacrocontextPosition(parit);
2984
2985         depth_type maxdepth = 0;
2986         pit_type const lastpit = parit.lastpit();
2987         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
2988                 // reduce depth if necessary
2989                 parit->params().depth(min(parit->params().depth(), maxdepth));
2990                 maxdepth = parit->getMaxDepthAfter();
2991
2992                 // set the counter for this paragraph
2993                 setLabel(*this, parit);
2994
2995                 // Now the insets
2996                 InsetList::const_iterator iit = parit->insetList().begin();
2997                 InsetList::const_iterator end = parit->insetList().end();
2998                 for (; iit != end; ++iit) {
2999                         parit.pos() = iit->pos;
3000                         iit->inset->updateLabels(parit);
3001                 }
3002         }
3003 }
3004
3005 } // namespace lyx