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