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