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