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