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