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