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