]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
gcc compile fix: vector::insert() requires an iterator, not a const_iterator.
[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 = 340; //jamatos: add plain layout
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         // Classify the unicode characters appearing in math insets
1026         Encodings::initUnicodeMath(*this);
1027
1028         // validate the buffer.
1029         LYXERR(Debug::LATEX, "  Validating buffer...");
1030         LaTeXFeatures features(*this, params(), runparams);
1031         validate(features);
1032         LYXERR(Debug::LATEX, "  Buffer validation done.");
1033
1034         // The starting paragraph of the coming rows is the
1035         // first paragraph of the document. (Asger)
1036         if (output_preamble && runparams.nice) {
1037                 os << "%% LyX " << lyx_version << " created this file.  "
1038                         "For more info, see http://www.lyx.org/.\n"
1039                         "%% Do not edit unless you really know what "
1040                         "you are doing.\n";
1041                 d->texrow.newline();
1042                 d->texrow.newline();
1043         }
1044         LYXERR(Debug::INFO, "lyx document header finished");
1045
1046         // Don't move this behind the parent_buffer=0 code below,
1047         // because then the macros will not get the right "redefinition"
1048         // flag as they don't see the parent macros which are output before.
1049         updateMacros();
1050
1051         // fold macros if possible, still with parent buffer as the
1052         // macros will be put in the prefix anyway.
1053         updateMacroInstances();
1054
1055         // There are a few differences between nice LaTeX and usual files:
1056         // usual is \batchmode and has a
1057         // special input@path to allow the including of figures
1058         // with either \input or \includegraphics (what figinsets do).
1059         // input@path is set when the actual parameter
1060         // original_path is set. This is done for usual tex-file, but not
1061         // for nice-latex-file. (Matthias 250696)
1062         // Note that input@path is only needed for something the user does
1063         // in the preamble, included .tex files or ERT, files included by
1064         // LyX work without it.
1065         if (output_preamble) {
1066                 if (!runparams.nice) {
1067                         // code for usual, NOT nice-latex-file
1068                         os << "\\batchmode\n"; // changed
1069                         // from \nonstopmode
1070                         d->texrow.newline();
1071                 }
1072                 if (!original_path.empty()) {
1073                         // FIXME UNICODE
1074                         // We don't know the encoding of inputpath
1075                         docstring const inputpath = from_utf8(latex_path(original_path));
1076                         os << "\\makeatletter\n"
1077                            << "\\def\\input@path{{"
1078                            << inputpath << "/}}\n"
1079                            << "\\makeatother\n";
1080                         d->texrow.newline();
1081                         d->texrow.newline();
1082                         d->texrow.newline();
1083                 }
1084
1085                 // get parent macros (if this buffer has a parent) which will be
1086                 // written at the document begin further down.
1087                 MacroSet parentMacros;
1088                 listParentMacros(parentMacros, features);
1089
1090                 // Write the preamble
1091                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1092
1093                 runparams.use_japanese = features.isRequired("japanese");
1094
1095                 if (!output_body)
1096                         return;
1097
1098                 // make the body.
1099                 os << "\\begin{document}\n";
1100                 d->texrow.newline();
1101
1102                 // output the parent macros
1103                 MacroSet::iterator it = parentMacros.begin();
1104                 MacroSet::iterator end = parentMacros.end();
1105                 for (; it != end; ++it)
1106                         (*it)->write(os, true);
1107         } // output_preamble
1108
1109         d->texrow.start(paragraphs().begin()->id(), 0);
1110
1111         LYXERR(Debug::INFO, "preamble finished, now the body.");
1112
1113         // if we are doing a real file with body, even if this is the
1114         // child of some other buffer, let's cut the link here.
1115         // This happens for example if only a child document is printed.
1116         Buffer const * save_parent = 0;
1117         if (output_preamble) {
1118                 save_parent = d->parent_buffer;
1119                 d->parent_buffer = 0;
1120         }
1121
1122         // the real stuff
1123         latexParagraphs(*this, text(), os, d->texrow, runparams);
1124
1125         // Restore the parenthood if needed
1126         if (output_preamble)
1127                 d->parent_buffer = save_parent;
1128
1129         // add this just in case after all the paragraphs
1130         os << endl;
1131         d->texrow.newline();
1132
1133         if (output_preamble) {
1134                 os << "\\end{document}\n";
1135                 d->texrow.newline();
1136                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1137         } else {
1138                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1139         }
1140         runparams_in.encoding = runparams.encoding;
1141
1142         // Just to be sure. (Asger)
1143         d->texrow.newline();
1144
1145         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1146         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1147 }
1148
1149
1150 bool Buffer::isLatex() const
1151 {
1152         return params().documentClass().outputType() == LATEX;
1153 }
1154
1155
1156 bool Buffer::isLiterate() const
1157 {
1158         return params().documentClass().outputType() == LITERATE;
1159 }
1160
1161
1162 bool Buffer::isDocBook() const
1163 {
1164         return params().documentClass().outputType() == DOCBOOK;
1165 }
1166
1167
1168 void Buffer::makeDocBookFile(FileName const & fname,
1169                               OutputParams const & runparams,
1170                               bool const body_only) const
1171 {
1172         LYXERR(Debug::LATEX, "makeDocBookFile...");
1173
1174         odocfstream ofs;
1175         if (!openFileWrite(ofs, fname))
1176                 return;
1177
1178         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1179
1180         ofs.close();
1181         if (ofs.fail())
1182                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1183 }
1184
1185
1186 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1187                              OutputParams const & runparams,
1188                              bool const only_body) const
1189 {
1190         LaTeXFeatures features(*this, params(), runparams);
1191         validate(features);
1192
1193         d->texrow.reset();
1194
1195         DocumentClass const & tclass = params().documentClass();
1196         string const top_element = tclass.latexname();
1197
1198         if (!only_body) {
1199                 if (runparams.flavor == OutputParams::XML)
1200                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1201
1202                 // FIXME UNICODE
1203                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1204
1205                 // FIXME UNICODE
1206                 if (! tclass.class_header().empty())
1207                         os << from_ascii(tclass.class_header());
1208                 else if (runparams.flavor == OutputParams::XML)
1209                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1210                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1211                 else
1212                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1213
1214                 docstring preamble = from_utf8(params().preamble);
1215                 if (runparams.flavor != OutputParams::XML ) {
1216                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1217                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1218                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1219                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1220                 }
1221
1222                 string const name = runparams.nice
1223                         ? changeExtension(absFileName(), ".sgml") : fname;
1224                 preamble += features.getIncludedFiles(name);
1225                 preamble += features.getLyXSGMLEntities();
1226
1227                 if (!preamble.empty()) {
1228                         os << "\n [ " << preamble << " ]";
1229                 }
1230                 os << ">\n\n";
1231         }
1232
1233         string top = top_element;
1234         top += " lang=\"";
1235         if (runparams.flavor == OutputParams::XML)
1236                 top += params().language->code();
1237         else
1238                 top += params().language->code().substr(0, 2);
1239         top += '"';
1240
1241         if (!params().options.empty()) {
1242                 top += ' ';
1243                 top += params().options;
1244         }
1245
1246         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1247             << " file was created by LyX " << lyx_version
1248             << "\n  See http://www.lyx.org/ for more information -->\n";
1249
1250         params().documentClass().counters().reset();
1251
1252         updateMacros();
1253
1254         sgml::openTag(os, top);
1255         os << '\n';
1256         docbookParagraphs(paragraphs(), *this, os, runparams);
1257         sgml::closeTag(os, top_element);
1258 }
1259
1260
1261 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1262 // Other flags: -wall -v0 -x
1263 int Buffer::runChktex()
1264 {
1265         setBusy(true);
1266
1267         // get LaTeX-Filename
1268         FileName const path(temppath());
1269         string const name = addName(path.absFilename(), latexName());
1270         string const org_path = filePath();
1271
1272         PathChanger p(path); // path to LaTeX file
1273         message(_("Running chktex..."));
1274
1275         // Generate the LaTeX file if neccessary
1276         OutputParams runparams(&params().encoding());
1277         runparams.flavor = OutputParams::LATEX;
1278         runparams.nice = false;
1279         makeLaTeXFile(FileName(name), org_path, runparams);
1280
1281         TeXErrors terr;
1282         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1283         int const res = chktex.run(terr); // run chktex
1284
1285         if (res == -1) {
1286                 Alert::error(_("chktex failure"),
1287                              _("Could not run chktex successfully."));
1288         } else if (res > 0) {
1289                 ErrorList & errlist = d->errorLists["ChkTeX"];
1290                 errlist.clear();
1291                 bufferErrors(terr, errlist);
1292         }
1293
1294         setBusy(false);
1295
1296         errors("ChkTeX");
1297
1298         return res;
1299 }
1300
1301
1302 void Buffer::validate(LaTeXFeatures & features) const
1303 {
1304         params().validate(features);
1305
1306         updateMacros();
1307
1308         for_each(paragraphs().begin(), paragraphs().end(),
1309                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1310
1311         if (lyxerr.debugging(Debug::LATEX)) {
1312                 features.showStruct();
1313         }
1314 }
1315
1316
1317 void Buffer::getLabelList(vector<docstring> & list) const
1318 {
1319         // If this is a child document, use the parent's list instead.
1320         if (d->parent_buffer) {
1321                 d->parent_buffer->getLabelList(list);
1322                 return;
1323         }
1324
1325         list.clear();
1326         Toc & toc = d->toc_backend.toc("label");
1327         TocIterator toc_it = toc.begin();
1328         TocIterator end = toc.end();
1329         for (; toc_it != end; ++toc_it) {
1330                 if (toc_it->depth() == 0)
1331                         list.push_back(toc_it->str());
1332         }
1333 }
1334
1335
1336 void Buffer::updateBibfilesCache() const
1337 {
1338         // If this is a child document, use the parent's cache instead.
1339         if (d->parent_buffer) {
1340                 d->parent_buffer->updateBibfilesCache();
1341                 return;
1342         }
1343
1344         d->bibfilesCache_.clear();
1345         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1346                 if (it->lyxCode() == BIBTEX_CODE) {
1347                         InsetBibtex const & inset =
1348                                 static_cast<InsetBibtex const &>(*it);
1349                         support::FileNameList const bibfiles = inset.getBibFiles();
1350                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1351                                 bibfiles.begin(),
1352                                 bibfiles.end());
1353                 } else if (it->lyxCode() == INCLUDE_CODE) {
1354                         InsetInclude & inset =
1355                                 static_cast<InsetInclude &>(*it);
1356                         inset.updateBibfilesCache();
1357                         support::FileNameList const & bibfiles =
1358                                         inset.getBibfilesCache(*this);
1359                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1360                                 bibfiles.begin(),
1361                                 bibfiles.end());
1362                 }
1363         }
1364         // the bibinfo cache is now invalid
1365         d->bibinfoCacheValid_ = false;
1366 }
1367
1368
1369 void Buffer::invalidateBibinfoCache()
1370 {
1371         d->bibinfoCacheValid_ = false;
1372 }
1373
1374
1375 support::FileNameList const & Buffer::getBibfilesCache() const
1376 {
1377         // If this is a child document, use the parent's cache instead.
1378         if (d->parent_buffer)
1379                 return d->parent_buffer->getBibfilesCache();
1380
1381         // We update the cache when first used instead of at loading time.
1382         if (d->bibfilesCache_.empty())
1383                 const_cast<Buffer *>(this)->updateBibfilesCache();
1384
1385         return d->bibfilesCache_;
1386 }
1387
1388
1389 BiblioInfo const & Buffer::masterBibInfo() const
1390 {
1391         // if this is a child document and the parent is already loaded
1392         // use the parent's list instead  [ale990412]
1393         Buffer const * const tmp = masterBuffer();
1394         LASSERT(tmp, /**/);
1395         if (tmp != this)
1396                 return tmp->masterBibInfo();
1397         return localBibInfo();
1398 }
1399
1400
1401 BiblioInfo const & Buffer::localBibInfo() const
1402 {
1403         if (d->bibinfoCacheValid_) {
1404                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1405                 // compare the cached timestamps with the actual ones.
1406                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1407                 support::FileNameList::const_iterator en = bibfilesCache.end();
1408                 for (; ei != en; ++ ei) {
1409                         time_t lastw = ei->lastModified();
1410                         if (lastw != d->bibfileStatus_[*ei]) {
1411                                 d->bibinfoCacheValid_ = false;
1412                                 d->bibfileStatus_[*ei] = lastw;
1413                                 break;
1414                         }
1415                 }
1416         }
1417
1418         if (!d->bibinfoCacheValid_) {
1419                 d->bibinfo_.clear();
1420                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1421                         it->fillWithBibKeys(d->bibinfo_, it);
1422                 d->bibinfoCacheValid_ = true;
1423         }
1424         return d->bibinfo_;
1425 }
1426
1427
1428 bool Buffer::isDepClean(string const & name) const
1429 {
1430         DepClean::const_iterator const it = d->dep_clean.find(name);
1431         if (it == d->dep_clean.end())
1432                 return true;
1433         return it->second;
1434 }
1435
1436
1437 void Buffer::markDepClean(string const & name)
1438 {
1439         d->dep_clean[name] = true;
1440 }
1441
1442
1443 bool Buffer::dispatch(string const & command, bool * result)
1444 {
1445         return dispatch(lyxaction.lookupFunc(command), result);
1446 }
1447
1448
1449 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1450 {
1451         bool dispatched = true;
1452
1453         switch (func.action) {
1454                 case LFUN_BUFFER_EXPORT: {
1455                         bool const tmp = doExport(to_utf8(func.argument()), false);
1456                         if (result)
1457                                 *result = tmp;
1458                         break;
1459                 }
1460
1461                 case LFUN_BRANCH_ACTIVATE:
1462                 case LFUN_BRANCH_DEACTIVATE: {
1463                         BranchList & branchList = params().branchlist();
1464                         docstring const branchName = func.argument();
1465                         Branch * branch = branchList.find(branchName);
1466                         if (!branch)
1467                                 LYXERR0("Branch " << branchName << " does not exist.");
1468                         else
1469                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1470                         if (result)
1471                                 *result = true;
1472                 }
1473
1474                 default:
1475                         dispatched = false;
1476         }
1477         return dispatched;
1478 }
1479
1480
1481 void Buffer::changeLanguage(Language const * from, Language const * to)
1482 {
1483         LASSERT(from, /**/);
1484         LASSERT(to, /**/);
1485
1486         for_each(par_iterator_begin(),
1487                  par_iterator_end(),
1488                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1489 }
1490
1491
1492 bool Buffer::isMultiLingual() const
1493 {
1494         ParConstIterator end = par_iterator_end();
1495         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1496                 if (it->isMultiLingual(params()))
1497                         return true;
1498
1499         return false;
1500 }
1501
1502
1503 DocIterator Buffer::getParFromID(int const id) const
1504 {
1505         if (id < 0) {
1506                 // John says this is called with id == -1 from undo
1507                 lyxerr << "getParFromID(), id: " << id << endl;
1508                 return doc_iterator_end(inset());
1509         }
1510
1511         for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1512                 if (it.paragraph().id() == id)
1513                         return it;
1514
1515         return doc_iterator_end(inset());
1516 }
1517
1518
1519 bool Buffer::hasParWithID(int const id) const
1520 {
1521         return !getParFromID(id).atEnd();
1522 }
1523
1524
1525 ParIterator Buffer::par_iterator_begin()
1526 {
1527         return ParIterator(doc_iterator_begin(inset()));
1528 }
1529
1530
1531 ParIterator Buffer::par_iterator_end()
1532 {
1533         return ParIterator(doc_iterator_end(inset()));
1534 }
1535
1536
1537 ParConstIterator Buffer::par_iterator_begin() const
1538 {
1539         return lyx::par_const_iterator_begin(inset());
1540 }
1541
1542
1543 ParConstIterator Buffer::par_iterator_end() const
1544 {
1545         return lyx::par_const_iterator_end(inset());
1546 }
1547
1548
1549 Language const * Buffer::language() const
1550 {
1551         return params().language;
1552 }
1553
1554
1555 docstring const Buffer::B_(string const & l10n) const
1556 {
1557         return params().B_(l10n);
1558 }
1559
1560
1561 bool Buffer::isClean() const
1562 {
1563         return d->lyx_clean;
1564 }
1565
1566
1567 bool Buffer::isBakClean() const
1568 {
1569         return d->bak_clean;
1570 }
1571
1572
1573 bool Buffer::isExternallyModified(CheckMethod method) const
1574 {
1575         LASSERT(d->filename.exists(), /**/);
1576         // if method == timestamp, check timestamp before checksum
1577         return (method == checksum_method
1578                 || d->timestamp_ != d->filename.lastModified())
1579                 && d->checksum_ != d->filename.checksum();
1580 }
1581
1582
1583 void Buffer::saveCheckSum(FileName const & file) const
1584 {
1585         if (file.exists()) {
1586                 d->timestamp_ = file.lastModified();
1587                 d->checksum_ = file.checksum();
1588         } else {
1589                 // in the case of save to a new file.
1590                 d->timestamp_ = 0;
1591                 d->checksum_ = 0;
1592         }
1593 }
1594
1595
1596 void Buffer::markClean() const
1597 {
1598         if (!d->lyx_clean) {
1599                 d->lyx_clean = true;
1600                 updateTitles();
1601         }
1602         // if the .lyx file has been saved, we don't need an
1603         // autosave
1604         d->bak_clean = true;
1605 }
1606
1607
1608 void Buffer::markBakClean() const
1609 {
1610         d->bak_clean = true;
1611 }
1612
1613
1614 void Buffer::setUnnamed(bool flag)
1615 {
1616         d->unnamed = flag;
1617 }
1618
1619
1620 bool Buffer::isUnnamed() const
1621 {
1622         return d->unnamed;
1623 }
1624
1625
1626 // FIXME: this function should be moved to buffer_pimpl.C
1627 void Buffer::markDirty()
1628 {
1629         if (d->lyx_clean) {
1630                 d->lyx_clean = false;
1631                 updateTitles();
1632         }
1633         d->bak_clean = false;
1634
1635         DepClean::iterator it = d->dep_clean.begin();
1636         DepClean::const_iterator const end = d->dep_clean.end();
1637
1638         for (; it != end; ++it)
1639                 it->second = false;
1640 }
1641
1642
1643 FileName Buffer::fileName() const
1644 {
1645         return d->filename;
1646 }
1647
1648
1649 string Buffer::absFileName() const
1650 {
1651         return d->filename.absFilename();
1652 }
1653
1654
1655 string Buffer::filePath() const
1656 {
1657         return d->filename.onlyPath().absFilename() + "/";
1658 }
1659
1660
1661 bool Buffer::isReadonly() const
1662 {
1663         return d->read_only;
1664 }
1665
1666
1667 void Buffer::setParent(Buffer const * buffer)
1668 {
1669         // Avoids recursive include.
1670         d->parent_buffer = buffer == this ? 0 : buffer;
1671         updateMacros();
1672 }
1673
1674
1675 Buffer const * Buffer::parent()
1676 {
1677         return d->parent_buffer;
1678 }
1679
1680
1681 Buffer const * Buffer::masterBuffer() const
1682 {
1683         if (!d->parent_buffer)
1684                 return this;
1685
1686         return d->parent_buffer->masterBuffer();
1687 }
1688
1689
1690 bool Buffer::isChild(Buffer * child) const
1691 {
1692         return d->children_positions.find(child) != d->children_positions.end();
1693 }
1694
1695
1696 template<typename M>
1697 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1698 {
1699         if (m.empty())
1700                 return m.end();
1701
1702         typename M::iterator it = m.lower_bound(x);
1703         if (it == m.begin())
1704                 return m.end();
1705
1706         it--;
1707         return it;
1708 }
1709
1710
1711 MacroData const * Buffer::getBufferMacro(docstring const & name,
1712                                          DocIterator const & pos) const
1713 {
1714         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1715
1716         // if paragraphs have no macro context set, pos will be empty
1717         if (pos.empty())
1718                 return 0;
1719
1720         // we haven't found anything yet
1721         DocIterator bestPos = par_iterator_begin();
1722         MacroData const * bestData = 0;
1723
1724         // find macro definitions for name
1725         Impl::NamePositionScopeMacroMap::iterator nameIt
1726         = d->macros.find(name);
1727         if (nameIt != d->macros.end()) {
1728                 // find last definition in front of pos or at pos itself
1729                 Impl::PositionScopeMacroMap::const_iterator it
1730                 = greatest_below(nameIt->second, pos);
1731                 if (it != nameIt->second.end()) {
1732                         while (true) {
1733                                 // scope ends behind pos?
1734                                 if (pos < it->second.first) {
1735                                         // Looks good, remember this. If there
1736                                         // is no external macro behind this,
1737                                         // we found the right one already.
1738                                         bestPos = it->first;
1739                                         bestData = &it->second.second;
1740                                         break;
1741                                 }
1742
1743                                 // try previous macro if there is one
1744                                 if (it == nameIt->second.begin())
1745                                         break;
1746                                 it--;
1747                         }
1748                 }
1749         }
1750
1751         // find macros in included files
1752         Impl::PositionScopeBufferMap::const_iterator it
1753         = greatest_below(d->position_to_children, pos);
1754         if (it == d->position_to_children.end())
1755                 // no children before
1756                 return bestData;
1757
1758         while (true) {
1759                 // do we know something better (i.e. later) already?
1760                 if (it->first < bestPos )
1761                         break;
1762
1763                 // scope ends behind pos?
1764                 if (pos < it->second.first) {
1765                         // look for macro in external file
1766                         d->macro_lock = true;
1767                         MacroData const * data
1768                         = it->second.second->getMacro(name, false);
1769                         d->macro_lock = false;
1770                         if (data) {
1771                                 bestPos = it->first;
1772                                 bestData = data;
1773                                 break;
1774                         }
1775                 }
1776
1777                 // try previous file if there is one
1778                 if (it == d->position_to_children.begin())
1779                         break;
1780                 --it;
1781         }
1782
1783         // return the best macro we have found
1784         return bestData;
1785 }
1786
1787
1788 MacroData const * Buffer::getMacro(docstring const & name,
1789         DocIterator const & pos, bool global) const
1790 {
1791         if (d->macro_lock)
1792                 return 0;
1793
1794         // query buffer macros
1795         MacroData const * data = getBufferMacro(name, pos);
1796         if (data != 0)
1797                 return data;
1798
1799         // If there is a master buffer, query that
1800         if (d->parent_buffer) {
1801                 d->macro_lock = true;
1802                 MacroData const * macro = d->parent_buffer->getMacro(
1803                         name, *this, false);
1804                 d->macro_lock = false;
1805                 if (macro)
1806                         return macro;
1807         }
1808
1809         if (global) {
1810                 data = MacroTable::globalMacros().get(name);
1811                 if (data != 0)
1812                         return data;
1813         }
1814
1815         return 0;
1816 }
1817
1818
1819 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1820 {
1821         // set scope end behind the last paragraph
1822         DocIterator scope = par_iterator_begin();
1823         scope.pit() = scope.lastpit() + 1;
1824
1825         return getMacro(name, scope, global);
1826 }
1827
1828
1829 MacroData const * Buffer::getMacro(docstring const & name,
1830         Buffer const & child, bool global) const
1831 {
1832         // look where the child buffer is included first
1833         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1834         if (it == d->children_positions.end())
1835                 return 0;
1836
1837         // check for macros at the inclusion position
1838         return getMacro(name, it->second, global);
1839 }
1840
1841
1842 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1843 {
1844         pit_type lastpit = it.lastpit();
1845
1846         // look for macros in each paragraph
1847         while (it.pit() <= lastpit) {
1848                 Paragraph & par = it.paragraph();
1849
1850                 // iterate over the insets of the current paragraph
1851                 InsetList const & insets = par.insetList();
1852                 InsetList::const_iterator iit = insets.begin();
1853                 InsetList::const_iterator end = insets.end();
1854                 for (; iit != end; ++iit) {
1855                         it.pos() = iit->pos;
1856
1857                         // is it a nested text inset?
1858                         if (iit->inset->asInsetText()) {
1859                                 // Inset needs its own scope?
1860                                 InsetText const * itext
1861                                 = iit->inset->asInsetText();
1862                                 bool newScope = itext->isMacroScope();
1863
1864                                 // scope which ends just behind the inset
1865                                 DocIterator insetScope = it;
1866                                 ++insetScope.pos();
1867
1868                                 // collect macros in inset
1869                                 it.push_back(CursorSlice(*iit->inset));
1870                                 updateMacros(it, newScope ? insetScope : scope);
1871                                 it.pop_back();
1872                                 continue;
1873                         }
1874
1875                         // is it an external file?
1876                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1877                                 // get buffer of external file
1878                                 InsetCommand const & inset
1879                                         = static_cast<InsetCommand const &>(*iit->inset);
1880                                 InsetCommandParams const & ip = inset.params();
1881                                 d->macro_lock = true;
1882                                 Buffer * child = loadIfNeeded(*this, ip);
1883                                 d->macro_lock = false;
1884                                 if (!child)
1885                                         continue;
1886
1887                                 // register its position, but only when it is
1888                                 // included first in the buffer
1889                                 if (d->children_positions.find(child)
1890                                         == d->children_positions.end())
1891                                         d->children_positions[child] = it;
1892
1893                                 // register child with its scope
1894                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1895                                 continue;
1896                         }
1897
1898                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1899                                 continue;
1900
1901                         // get macro data
1902                         MathMacroTemplate & macroTemplate
1903                         = static_cast<MathMacroTemplate &>(*iit->inset);
1904                         MacroContext mc(*this, it);
1905                         macroTemplate.updateToContext(mc);
1906
1907                         // valid?
1908                         bool valid = macroTemplate.validMacro();
1909                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1910                         // then the BufferView's cursor will be invalid in
1911                         // some cases which leads to crashes.
1912                         if (!valid)
1913                                 continue;
1914
1915                         // register macro
1916                         d->macros[macroTemplate.name()][it] =
1917                                 Impl::ScopeMacro(scope, MacroData(*this, it));
1918                 }
1919
1920                 // next paragraph
1921                 it.pit()++;
1922                 it.pos() = 0;
1923         }
1924 }
1925
1926
1927 void Buffer::updateMacros() const
1928 {
1929         if (d->macro_lock)
1930                 return;
1931
1932         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1933
1934         // start with empty table
1935         d->macros.clear();
1936         d->children_positions.clear();
1937         d->position_to_children.clear();
1938
1939         // Iterate over buffer, starting with first paragraph
1940         // The scope must be bigger than any lookup DocIterator
1941         // later. For the global lookup, lastpit+1 is used, hence
1942         // we use lastpit+2 here.
1943         DocIterator it = par_iterator_begin();
1944         DocIterator outerScope = it;
1945         outerScope.pit() = outerScope.lastpit() + 2;
1946         updateMacros(it, outerScope);
1947 }
1948
1949
1950 void Buffer::updateMacroInstances() const
1951 {
1952         LYXERR(Debug::MACROS, "updateMacroInstances for "
1953                 << d->filename.onlyFileName());
1954         DocIterator it = doc_iterator_begin(inset());
1955         DocIterator end = doc_iterator_end(inset());
1956         for (; it != end; it.forwardPos()) {
1957                 // look for MathData cells in InsetMathNest insets
1958                 Inset * inset = it.nextInset();
1959                 if (!inset)
1960                         continue;
1961
1962                 InsetMath * minset = inset->asInsetMath();
1963                 if (!minset)
1964                         continue;
1965
1966                 // update macro in all cells of the InsetMathNest
1967                 DocIterator::idx_type n = minset->nargs();
1968                 MacroContext mc = MacroContext(*this, it);
1969                 for (DocIterator::idx_type i = 0; i < n; ++i) {
1970                         MathData & data = minset->cell(i);
1971                         data.updateMacros(0, mc);
1972                 }
1973         }
1974 }
1975
1976
1977 void Buffer::listMacroNames(MacroNameSet & macros) const
1978 {
1979         if (d->macro_lock)
1980                 return;
1981
1982         d->macro_lock = true;
1983
1984         // loop over macro names
1985         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1986         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1987         for (; nameIt != nameEnd; ++nameIt)
1988                 macros.insert(nameIt->first);
1989
1990         // loop over children
1991         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1992         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1993         for (; it != end; ++it)
1994                 it->first->listMacroNames(macros);
1995
1996         // call parent
1997         if (d->parent_buffer)
1998                 d->parent_buffer->listMacroNames(macros);
1999
2000         d->macro_lock = false;
2001 }
2002
2003
2004 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2005 {
2006         if (!d->parent_buffer)
2007                 return;
2008
2009         MacroNameSet names;
2010         d->parent_buffer->listMacroNames(names);
2011
2012         // resolve macros
2013         MacroNameSet::iterator it = names.begin();
2014         MacroNameSet::iterator end = names.end();
2015         for (; it != end; ++it) {
2016                 // defined?
2017                 MacroData const * data =
2018                 d->parent_buffer->getMacro(*it, *this, false);
2019                 if (data) {
2020                         macros.insert(data);
2021
2022                         // we cannot access the original MathMacroTemplate anymore
2023                         // here to calls validate method. So we do its work here manually.
2024                         // FIXME: somehow make the template accessible here.
2025                         if (data->optionals() > 0)
2026                                 features.require("xargs");
2027                 }
2028         }
2029 }
2030
2031
2032 Buffer::References & Buffer::references(docstring const & label)
2033 {
2034         if (d->parent_buffer)
2035                 return const_cast<Buffer *>(masterBuffer())->references(label);
2036
2037         RefCache::iterator it = d->ref_cache_.find(label);
2038         if (it != d->ref_cache_.end())
2039                 return it->second.second;
2040
2041         static InsetLabel const * dummy_il = 0;
2042         static References const dummy_refs;
2043         it = d->ref_cache_.insert(
2044                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2045         return it->second.second;
2046 }
2047
2048
2049 Buffer::References const & Buffer::references(docstring const & label) const
2050 {
2051         return const_cast<Buffer *>(this)->references(label);
2052 }
2053
2054
2055 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2056 {
2057         masterBuffer()->d->ref_cache_[label].first = il;
2058 }
2059
2060
2061 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2062 {
2063         return masterBuffer()->d->ref_cache_[label].first;
2064 }
2065
2066
2067 void Buffer::clearReferenceCache() const
2068 {
2069         if (!d->parent_buffer)
2070                 d->ref_cache_.clear();
2071 }
2072
2073
2074 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2075         InsetCode code)
2076 {
2077         //FIXME: This does not work for child documents yet.
2078         LASSERT(code == CITE_CODE, /**/);
2079         // Check if the label 'from' appears more than once
2080         vector<docstring> labels;
2081         string paramName;
2082         BiblioInfo const & keys = masterBibInfo();
2083         BiblioInfo::const_iterator bit  = keys.begin();
2084         BiblioInfo::const_iterator bend = keys.end();
2085
2086         for (; bit != bend; ++bit)
2087                 // FIXME UNICODE
2088                 labels.push_back(bit->first);
2089         paramName = "key";
2090
2091         if (count(labels.begin(), labels.end(), from) > 1)
2092                 return;
2093
2094         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2095                 if (it->lyxCode() == code) {
2096                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2097                         docstring const oldValue = inset.getParam(paramName);
2098                         if (oldValue == from)
2099                                 inset.setParam(paramName, to);
2100                 }
2101         }
2102 }
2103
2104
2105 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2106         pit_type par_end, bool full_source) const
2107 {
2108         OutputParams runparams(&params().encoding());
2109         runparams.nice = true;
2110         runparams.flavor = OutputParams::LATEX;
2111         runparams.linelen = lyxrc.plaintext_linelen;
2112         // No side effect of file copying and image conversion
2113         runparams.dryrun = true;
2114
2115         d->texrow.reset();
2116         if (full_source) {
2117                 os << "% " << _("Preview source code") << "\n\n";
2118                 d->texrow.newline();
2119                 d->texrow.newline();
2120                 if (isLatex())
2121                         writeLaTeXSource(os, filePath(), runparams, true, true);
2122                 else
2123                         writeDocBookSource(os, absFileName(), runparams, false);
2124         } else {
2125                 runparams.par_begin = par_begin;
2126                 runparams.par_end = par_end;
2127                 if (par_begin + 1 == par_end) {
2128                         os << "% "
2129                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2130                            << "\n\n";
2131                 } else {
2132                         os << "% "
2133                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2134                                         convert<docstring>(par_begin),
2135                                         convert<docstring>(par_end - 1))
2136                            << "\n\n";
2137                 }
2138                 d->texrow.newline();
2139                 d->texrow.newline();
2140                 // output paragraphs
2141                 if (isLatex())
2142                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2143                 else
2144                         // DocBook
2145                         docbookParagraphs(paragraphs(), *this, os, runparams);
2146         }
2147 }
2148
2149
2150 ErrorList & Buffer::errorList(string const & type) const
2151 {
2152         static ErrorList emptyErrorList;
2153         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2154         if (I == d->errorLists.end())
2155                 return emptyErrorList;
2156
2157         return I->second;
2158 }
2159
2160
2161 void Buffer::updateTocItem(std::string const & type,
2162         DocIterator const & dit) const
2163 {
2164         if (gui_)
2165                 gui_->updateTocItem(type, dit);
2166 }
2167
2168
2169 void Buffer::structureChanged() const
2170 {
2171         if (gui_)
2172                 gui_->structureChanged();
2173 }
2174
2175
2176 void Buffer::errors(string const & err) const
2177 {
2178         if (gui_)
2179                 gui_->errors(err);
2180 }
2181
2182
2183 void Buffer::message(docstring const & msg) const
2184 {
2185         if (gui_)
2186                 gui_->message(msg);
2187 }
2188
2189
2190 void Buffer::setBusy(bool on) const
2191 {
2192         if (gui_)
2193                 gui_->setBusy(on);
2194 }
2195
2196
2197 void Buffer::setReadOnly(bool on) const
2198 {
2199         if (d->wa_)
2200                 d->wa_->setReadOnly(on);
2201 }
2202
2203
2204 void Buffer::updateTitles() const
2205 {
2206         if (d->wa_)
2207                 d->wa_->updateTitles();
2208 }
2209
2210
2211 void Buffer::resetAutosaveTimers() const
2212 {
2213         if (gui_)
2214                 gui_->resetAutosaveTimers();
2215 }
2216
2217
2218 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2219 {
2220         gui_ = gui;
2221 }
2222
2223
2224
2225 namespace {
2226
2227 class AutoSaveBuffer : public ForkedProcess {
2228 public:
2229         ///
2230         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2231                 : buffer_(buffer), fname_(fname) {}
2232         ///
2233         virtual boost::shared_ptr<ForkedProcess> clone() const
2234         {
2235                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2236         }
2237         ///
2238         int start()
2239         {
2240                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2241                                                  from_utf8(fname_.absFilename())));
2242                 return run(DontWait);
2243         }
2244 private:
2245         ///
2246         virtual int generateChild();
2247         ///
2248         Buffer const & buffer_;
2249         FileName fname_;
2250 };
2251
2252
2253 int AutoSaveBuffer::generateChild()
2254 {
2255         // tmp_ret will be located (usually) in /tmp
2256         // will that be a problem?
2257         // Note that this calls ForkedCalls::fork(), so it's
2258         // ok cross-platform.
2259         pid_t const pid = fork();
2260         // If you want to debug the autosave
2261         // you should set pid to -1, and comment out the fork.
2262         if (pid != 0 && pid != -1)
2263                 return pid;
2264
2265         // pid = -1 signifies that lyx was unable
2266         // to fork. But we will do the save
2267         // anyway.
2268         bool failed = false;
2269         FileName const tmp_ret = FileName::tempName("lyxauto");
2270         if (!tmp_ret.empty()) {
2271                 buffer_.writeFile(tmp_ret);
2272                 // assume successful write of tmp_ret
2273                 if (!tmp_ret.moveTo(fname_))
2274                         failed = true;
2275         } else
2276                 failed = true;
2277
2278         if (failed) {
2279                 // failed to write/rename tmp_ret so try writing direct
2280                 if (!buffer_.writeFile(fname_)) {
2281                         // It is dangerous to do this in the child,
2282                         // but safe in the parent, so...
2283                         if (pid == -1) // emit message signal.
2284                                 buffer_.message(_("Autosave failed!"));
2285                 }
2286         }
2287
2288         if (pid == 0) // we are the child so...
2289                 _exit(0);
2290
2291         return pid;
2292 }
2293
2294 } // namespace anon
2295
2296
2297 // Perfect target for a thread...
2298 void Buffer::autoSave() const
2299 {
2300         if (isBakClean() || isReadonly()) {
2301                 // We don't save now, but we'll try again later
2302                 resetAutosaveTimers();
2303                 return;
2304         }
2305
2306         // emit message signal.
2307         message(_("Autosaving current document..."));
2308
2309         // create autosave filename
2310         string fname = filePath();
2311         fname += '#';
2312         fname += d->filename.onlyFileName();
2313         fname += '#';
2314
2315         AutoSaveBuffer autosave(*this, FileName(fname));
2316         autosave.start();
2317
2318         markBakClean();
2319         resetAutosaveTimers();
2320 }
2321
2322
2323 string Buffer::bufferFormat() const
2324 {
2325         if (isDocBook())
2326                 return "docbook";
2327         if (isLiterate())
2328                 return "literate";
2329         if (params().encoding().package() == Encoding::japanese)
2330                 return "platex";
2331         return "latex";
2332 }
2333
2334
2335 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2336         string & result_file) const
2337 {
2338         string backend_format;
2339         OutputParams runparams(&params().encoding());
2340         runparams.flavor = OutputParams::LATEX;
2341         runparams.linelen = lyxrc.plaintext_linelen;
2342         vector<string> backs = backends();
2343         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2344                 // Get shortest path to format
2345                 Graph::EdgePath path;
2346                 for (vector<string>::const_iterator it = backs.begin();
2347                      it != backs.end(); ++it) {
2348                         Graph::EdgePath p = theConverters().getPath(*it, format);
2349                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2350                                 backend_format = *it;
2351                                 path = p;
2352                         }
2353                 }
2354                 if (!path.empty())
2355                         runparams.flavor = theConverters().getFlavor(path);
2356                 else {
2357                         Alert::error(_("Couldn't export file"),
2358                                 bformat(_("No information for exporting the format %1$s."),
2359                                    formats.prettyName(format)));
2360                         return false;
2361                 }
2362         } else {
2363                 backend_format = format;
2364                 // FIXME: Don't hardcode format names here, but use a flag
2365                 if (backend_format == "pdflatex")
2366                         runparams.flavor = OutputParams::PDFLATEX;
2367         }
2368
2369         string filename = latexName(false);
2370         filename = addName(temppath(), filename);
2371         filename = changeExtension(filename,
2372                                    formats.extension(backend_format));
2373
2374         // fix macros
2375         updateMacroInstances();
2376
2377         // Plain text backend
2378         if (backend_format == "text")
2379                 writePlaintextFile(*this, FileName(filename), runparams);
2380         // no backend
2381         else if (backend_format == "lyx")
2382                 writeFile(FileName(filename));
2383         // Docbook backend
2384         else if (isDocBook()) {
2385                 runparams.nice = !put_in_tempdir;
2386                 makeDocBookFile(FileName(filename), runparams);
2387         }
2388         // LaTeX backend
2389         else if (backend_format == format) {
2390                 runparams.nice = true;
2391                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2392                         return false;
2393         } else if (!lyxrc.tex_allows_spaces
2394                    && contains(filePath(), ' ')) {
2395                 Alert::error(_("File name error"),
2396                            _("The directory path to the document cannot contain spaces."));
2397                 return false;
2398         } else {
2399                 runparams.nice = false;
2400                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2401                         return false;
2402         }
2403
2404         string const error_type = (format == "program")
2405                 ? "Build" : bufferFormat();
2406         ErrorList & error_list = d->errorLists[error_type];
2407         string const ext = formats.extension(format);
2408         FileName const tmp_result_file(changeExtension(filename, ext));
2409         bool const success = theConverters().convert(this, FileName(filename),
2410                 tmp_result_file, FileName(absFileName()), backend_format, format,
2411                 error_list);
2412         // Emit the signal to show the error list.
2413         if (format != backend_format)
2414                 errors(error_type);
2415         if (!success)
2416                 return false;
2417
2418         if (put_in_tempdir) {
2419                 result_file = tmp_result_file.absFilename();
2420                 return true;
2421         }
2422
2423         result_file = changeExtension(absFileName(), ext);
2424         // We need to copy referenced files (e. g. included graphics
2425         // if format == "dvi") to the result dir.
2426         vector<ExportedFile> const files =
2427                 runparams.exportdata->externalFiles(format);
2428         string const dest = onlyPath(result_file);
2429         CopyStatus status = SUCCESS;
2430         for (vector<ExportedFile>::const_iterator it = files.begin();
2431                 it != files.end() && status != CANCEL; ++it) {
2432                 string const fmt = formats.getFormatFromFile(it->sourceName);
2433                 status = copyFile(fmt, it->sourceName,
2434                         makeAbsPath(it->exportName, dest),
2435                         it->exportName, status == FORCE);
2436         }
2437         if (status == CANCEL) {
2438                 message(_("Document export cancelled."));
2439         } else if (tmp_result_file.exists()) {
2440                 // Finally copy the main file
2441                 status = copyFile(format, tmp_result_file,
2442                         FileName(result_file), result_file,
2443                         status == FORCE);
2444                 message(bformat(_("Document exported as %1$s "
2445                         "to file `%2$s'"),
2446                         formats.prettyName(format),
2447                         makeDisplayPath(result_file)));
2448         } else {
2449                 // This must be a dummy converter like fax (bug 1888)
2450                 message(bformat(_("Document exported as %1$s"),
2451                         formats.prettyName(format)));
2452         }
2453
2454         return true;
2455 }
2456
2457
2458 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2459 {
2460         string result_file;
2461         return doExport(format, put_in_tempdir, result_file);
2462 }
2463
2464
2465 bool Buffer::preview(string const & format) const
2466 {
2467         string result_file;
2468         if (!doExport(format, true, result_file))
2469                 return false;
2470         return formats.view(*this, FileName(result_file), format);
2471 }
2472
2473
2474 bool Buffer::isExportable(string const & format) const
2475 {
2476         vector<string> backs = backends();
2477         for (vector<string>::const_iterator it = backs.begin();
2478              it != backs.end(); ++it)
2479                 if (theConverters().isReachable(*it, format))
2480                         return true;
2481         return false;
2482 }
2483
2484
2485 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2486 {
2487         vector<string> backs = backends();
2488         vector<Format const *> result =
2489                 theConverters().getReachable(backs[0], only_viewable, true);
2490         for (vector<string>::const_iterator it = backs.begin() + 1;
2491              it != backs.end(); ++it) {
2492                 vector<Format const *>  r =
2493                         theConverters().getReachable(*it, only_viewable, false);
2494                 result.insert(result.end(), r.begin(), r.end());
2495         }
2496         return result;
2497 }
2498
2499
2500 vector<string> Buffer::backends() const
2501 {
2502         vector<string> v;
2503         if (params().baseClass()->isTeXClassAvailable()) {
2504                 v.push_back(bufferFormat());
2505                 // FIXME: Don't hardcode format names here, but use a flag
2506                 if (v.back() == "latex")
2507                         v.push_back("pdflatex");
2508         }
2509         v.push_back("text");
2510         v.push_back("lyx");
2511         return v;
2512 }
2513
2514
2515 bool Buffer::readFileHelper(FileName const & s)
2516 {
2517         // File information about normal file
2518         if (!s.exists()) {
2519                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2520                 docstring text = bformat(_("The specified document\n%1$s"
2521                                                      "\ncould not be read."), file);
2522                 Alert::error(_("Could not read document"), text);
2523                 return false;
2524         }
2525
2526         // Check if emergency save file exists and is newer.
2527         FileName const e(s.absFilename() + ".emergency");
2528
2529         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2530                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2531                 docstring const text =
2532                         bformat(_("An emergency save of the document "
2533                                   "%1$s exists.\n\n"
2534                                                "Recover emergency save?"), file);
2535                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2536                                       _("&Recover"),  _("&Load Original"),
2537                                       _("&Cancel")))
2538                 {
2539                 case 0:
2540                         // the file is not saved if we load the emergency file.
2541                         markDirty();
2542                         return readFile(e);
2543                 case 1:
2544                         break;
2545                 default:
2546                         return false;
2547                 }
2548         }
2549
2550         // Now check if autosave file is newer.
2551         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2552
2553         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2554                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2555                 docstring const text =
2556                         bformat(_("The backup of the document "
2557                                   "%1$s is newer.\n\nLoad the "
2558                                                "backup instead?"), file);
2559                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2560                                       _("&Load backup"), _("Load &original"),
2561                                       _("&Cancel") ))
2562                 {
2563                 case 0:
2564                         // the file is not saved if we load the autosave file.
2565                         markDirty();
2566                         return readFile(a);
2567                 case 1:
2568                         // Here we delete the autosave
2569                         a.removeFile();
2570                         break;
2571                 default:
2572                         return false;
2573                 }
2574         }
2575         return readFile(s);
2576 }
2577
2578
2579 bool Buffer::loadLyXFile(FileName const & s)
2580 {
2581         if (s.isReadableFile()) {
2582                 if (readFileHelper(s)) {
2583                         lyxvc().file_found_hook(s);
2584                         if (!s.isWritable())
2585                                 setReadonly(true);
2586                         return true;
2587                 }
2588         } else {
2589                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2590                 // Here we probably should run
2591                 if (LyXVC::file_not_found_hook(s)) {
2592                         docstring const text =
2593                                 bformat(_("Do you want to retrieve the document"
2594                                                        " %1$s from version control?"), file);
2595                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2596                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2597
2598                         if (ret == 0) {
2599                                 // How can we know _how_ to do the checkout?
2600                                 // With the current VC support it has to be,
2601                                 // a RCS file since CVS do not have special ,v files.
2602                                 RCS::retrieve(s);
2603                                 return loadLyXFile(s);
2604                         }
2605                 }
2606         }
2607         return false;
2608 }
2609
2610
2611 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2612 {
2613         TeXErrors::Errors::const_iterator cit = terr.begin();
2614         TeXErrors::Errors::const_iterator end = terr.end();
2615
2616         for (; cit != end; ++cit) {
2617                 int id_start = -1;
2618                 int pos_start = -1;
2619                 int errorRow = cit->error_in_line;
2620                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2621                                                        pos_start);
2622                 int id_end = -1;
2623                 int pos_end = -1;
2624                 do {
2625                         ++errorRow;
2626                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2627                 } while (found && id_start == id_end && pos_start == pos_end);
2628
2629                 errorList.push_back(ErrorItem(cit->error_desc,
2630                         cit->error_text, id_start, pos_start, pos_end));
2631         }
2632 }
2633
2634
2635 } // namespace lyx