]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Now that exceptions are allowed, handle gracefully the case where a Buffer temp direc...
[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 = 308; // Uwe: Serbian-Latin
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
1003         bool failed_export = false;
1004         try {
1005                 d->texrow.reset();
1006                 writeLaTeXSource(ofs, original_path,
1007                       runparams, output_preamble, output_body);
1008         }
1009         catch (iconv_codecvt_facet_exception & e) {
1010                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1011                 failed_export = true;
1012         }
1013         catch (exception const & e) {
1014                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1015                 failed_export = true;
1016         }
1017         catch (...) {
1018                 lyxerr << "Caught some really weird exception..." << endl;
1019                 LyX::cref().exit(1);
1020         }
1021
1022         ofs.close();
1023         if (ofs.fail()) {
1024                 failed_export = true;
1025                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1026         }
1027
1028         if (failed_export) {
1029                 Alert::error(_("Encoding error"),
1030                         _("Some characters of your document are probably not "
1031                         "representable in the chosen encoding.\n"
1032                         "Changing the document encoding to utf8 could help."));
1033                 return false;
1034         }
1035         return true;
1036 }
1037
1038
1039 void Buffer::writeLaTeXSource(odocstream & os,
1040                            string const & original_path,
1041                            OutputParams const & runparams_in,
1042                            bool const output_preamble, bool const output_body) const
1043 {
1044         OutputParams runparams = runparams_in;
1045
1046         // validate the buffer.
1047         LYXERR(Debug::LATEX, "  Validating buffer...");
1048         LaTeXFeatures features(*this, params(), runparams);
1049         validate(features);
1050         LYXERR(Debug::LATEX, "  Buffer validation done.");
1051
1052         // The starting paragraph of the coming rows is the
1053         // first paragraph of the document. (Asger)
1054         if (output_preamble && runparams.nice) {
1055                 os << "%% LyX " << lyx_version << " created this file.  "
1056                         "For more info, see http://www.lyx.org/.\n"
1057                         "%% Do not edit unless you really know what "
1058                         "you are doing.\n";
1059                 d->texrow.newline();
1060                 d->texrow.newline();
1061         }
1062         LYXERR(Debug::INFO, "lyx document header finished");
1063         // There are a few differences between nice LaTeX and usual files:
1064         // usual is \batchmode and has a
1065         // special input@path to allow the including of figures
1066         // with either \input or \includegraphics (what figinsets do).
1067         // input@path is set when the actual parameter
1068         // original_path is set. This is done for usual tex-file, but not
1069         // for nice-latex-file. (Matthias 250696)
1070         // Note that input@path is only needed for something the user does
1071         // in the preamble, included .tex files or ERT, files included by
1072         // LyX work without it.
1073         if (output_preamble) {
1074                 if (!runparams.nice) {
1075                         // code for usual, NOT nice-latex-file
1076                         os << "\\batchmode\n"; // changed
1077                         // from \nonstopmode
1078                         d->texrow.newline();
1079                 }
1080                 if (!original_path.empty()) {
1081                         // FIXME UNICODE
1082                         // We don't know the encoding of inputpath
1083                         docstring const inputpath = from_utf8(latex_path(original_path));
1084                         os << "\\makeatletter\n"
1085                            << "\\def\\input@path{{"
1086                            << inputpath << "/}}\n"
1087                            << "\\makeatother\n";
1088                         d->texrow.newline();
1089                         d->texrow.newline();
1090                         d->texrow.newline();
1091                 }
1092
1093                 // Write the preamble
1094                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1095
1096                 if (!output_body)
1097                         return;
1098
1099                 // make the body.
1100                 os << "\\begin{document}\n";
1101                 d->texrow.newline();
1102         } // output_preamble
1103
1104         d->texrow.start(paragraphs().begin()->id(), 0);
1105         
1106         LYXERR(Debug::INFO, "preamble finished, now the body.");
1107
1108         // if we are doing a real file with body, even if this is the
1109         // child of some other buffer, let's cut the link here.
1110         // This happens for example if only a child document is printed.
1111         Buffer const * save_parent = 0;
1112         if (output_preamble) {
1113                 save_parent = d->parent_buffer;
1114                 d->parent_buffer = 0;
1115         }
1116
1117         loadChildDocuments();
1118
1119         // the real stuff
1120         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1121
1122         // Restore the parenthood if needed
1123         if (output_preamble)
1124                 d->parent_buffer = save_parent;
1125
1126         // add this just in case after all the paragraphs
1127         os << endl;
1128         d->texrow.newline();
1129
1130         if (output_preamble) {
1131                 os << "\\end{document}\n";
1132                 d->texrow.newline();
1133                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1134         } else {
1135                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1136         }
1137         runparams_in.encoding = runparams.encoding;
1138
1139         // Just to be sure. (Asger)
1140         d->texrow.newline();
1141
1142         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1143         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1144 }
1145
1146
1147 bool Buffer::isLatex() const
1148 {
1149         return params().getTextClass().outputType() == LATEX;
1150 }
1151
1152
1153 bool Buffer::isLiterate() const
1154 {
1155         return params().getTextClass().outputType() == LITERATE;
1156 }
1157
1158
1159 bool Buffer::isDocBook() const
1160 {
1161         return params().getTextClass().outputType() == DOCBOOK;
1162 }
1163
1164
1165 void Buffer::makeDocBookFile(FileName const & fname,
1166                               OutputParams const & runparams,
1167                               bool const body_only) const
1168 {
1169         LYXERR(Debug::LATEX, "makeDocBookFile...");
1170
1171         //ofstream ofs;
1172         odocfstream ofs;
1173         if (!openFileWrite(ofs, fname))
1174                 return;
1175
1176         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1177
1178         ofs.close();
1179         if (ofs.fail())
1180                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1181 }
1182
1183
1184 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1185                              OutputParams const & runparams,
1186                              bool const only_body) const
1187 {
1188         LaTeXFeatures features(*this, params(), runparams);
1189         validate(features);
1190
1191         d->texrow.reset();
1192
1193         TextClass const & tclass = params().getTextClass();
1194         string const top_element = tclass.latexname();
1195
1196         if (!only_body) {
1197                 if (runparams.flavor == OutputParams::XML)
1198                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1199
1200                 // FIXME UNICODE
1201                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1202
1203                 // FIXME UNICODE
1204                 if (! tclass.class_header().empty())
1205                         os << from_ascii(tclass.class_header());
1206                 else if (runparams.flavor == OutputParams::XML)
1207                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1208                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1209                 else
1210                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1211
1212                 docstring preamble = from_utf8(params().preamble);
1213                 if (runparams.flavor != OutputParams::XML ) {
1214                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1215                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1216                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1217                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1218                 }
1219
1220                 string const name = runparams.nice
1221                         ? changeExtension(absFileName(), ".sgml") : fname;
1222                 preamble += features.getIncludedFiles(name);
1223                 preamble += features.getLyXSGMLEntities();
1224
1225                 if (!preamble.empty()) {
1226                         os << "\n [ " << preamble << " ]";
1227                 }
1228                 os << ">\n\n";
1229         }
1230
1231         string top = top_element;
1232         top += " lang=\"";
1233         if (runparams.flavor == OutputParams::XML)
1234                 top += params().language->code();
1235         else
1236                 top += params().language->code().substr(0,2);
1237         top += '"';
1238
1239         if (!params().options.empty()) {
1240                 top += ' ';
1241                 top += params().options;
1242         }
1243
1244         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1245             << " file was created by LyX " << lyx_version
1246             << "\n  See http://www.lyx.org/ for more information -->\n";
1247
1248         params().getTextClass().counters().reset();
1249
1250         loadChildDocuments();
1251
1252         sgml::openTag(os, top);
1253         os << '\n';
1254         docbookParagraphs(paragraphs(), *this, os, runparams);
1255         sgml::closeTag(os, top_element);
1256 }
1257
1258
1259 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1260 // Other flags: -wall -v0 -x
1261 int Buffer::runChktex()
1262 {
1263         setBusy(true);
1264
1265         // get LaTeX-Filename
1266         FileName const path(temppath());
1267         string const name = addName(path.absFilename(), latexName());
1268         string const org_path = filePath();
1269
1270         PathChanger p(path); // path to LaTeX file
1271         message(_("Running chktex..."));
1272
1273         // Generate the LaTeX file if neccessary
1274         OutputParams runparams(&params().encoding());
1275         runparams.flavor = OutputParams::LATEX;
1276         runparams.nice = false;
1277         makeLaTeXFile(FileName(name), org_path, runparams);
1278
1279         TeXErrors terr;
1280         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1281         int const res = chktex.run(terr); // run chktex
1282
1283         if (res == -1) {
1284                 Alert::error(_("chktex failure"),
1285                              _("Could not run chktex successfully."));
1286         } else if (res > 0) {
1287                 ErrorList & errlist = d->errorLists["ChkTeX"];
1288                 errlist.clear();
1289                 bufferErrors(terr, errlist);
1290         }
1291
1292         setBusy(false);
1293
1294         errors("ChkTeX");
1295
1296         return res;
1297 }
1298
1299
1300 void Buffer::validate(LaTeXFeatures & features) const
1301 {
1302         params().validate(features);
1303
1304         loadChildDocuments();
1305
1306         for_each(paragraphs().begin(), paragraphs().end(),
1307                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1308
1309         if (lyxerr.debugging(Debug::LATEX)) {
1310                 features.showStruct();
1311         }
1312 }
1313
1314
1315 void Buffer::getLabelList(vector<docstring> & list) const
1316 {
1317         /// if this is a child document and the parent is already loaded
1318         /// Use the parent's list instead  [ale990407]
1319         Buffer const * tmp = masterBuffer();
1320         if (!tmp) {
1321                 lyxerr << "masterBuffer() failed!" << endl;
1322                 BOOST_ASSERT(tmp);
1323         }
1324         if (tmp != this) {
1325                 tmp->getLabelList(list);
1326                 return;
1327         }
1328
1329         loadChildDocuments();
1330
1331         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1332                 it.nextInset()->getLabelList(*this, list);
1333 }
1334
1335
1336 void Buffer::updateBibfilesCache() const
1337 {
1338         // if this is a child document and the parent is already loaded
1339         // update the parent's cache instead
1340         Buffer const * tmp = masterBuffer();
1341         BOOST_ASSERT(tmp);
1342         if (tmp != this) {
1343                 tmp->updateBibfilesCache();
1344                 return;
1345         }
1346
1347         d->bibfilesCache_.clear();
1348         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1349                 if (it->lyxCode() == BIBTEX_CODE) {
1350                         InsetBibtex const & inset =
1351                                 static_cast<InsetBibtex const &>(*it);
1352                         FileNameList const bibfiles = inset.getFiles(*this);
1353                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1354                                 bibfiles.begin(),
1355                                 bibfiles.end());
1356                 } else if (it->lyxCode() == INCLUDE_CODE) {
1357                         InsetInclude & inset =
1358                                 static_cast<InsetInclude &>(*it);
1359                         inset.updateBibfilesCache(*this);
1360                         FileNameList const & bibfiles =
1361                                         inset.getBibfilesCache(*this);
1362                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1363                                 bibfiles.begin(),
1364                                 bibfiles.end());
1365                 }
1366         }
1367 }
1368
1369
1370 FileNameList const & Buffer::getBibfilesCache() const
1371 {
1372         // if this is a child document and the parent is already loaded
1373         // use the parent's cache instead
1374         Buffer const * tmp = masterBuffer();
1375         BOOST_ASSERT(tmp);
1376         if (tmp != this)
1377                 return tmp->getBibfilesCache();
1378
1379         // We update the cache when first used instead of at loading time.
1380         if (d->bibfilesCache_.empty())
1381                 const_cast<Buffer *>(this)->updateBibfilesCache();
1382
1383         return d->bibfilesCache_;
1384 }
1385
1386
1387 bool Buffer::isDepClean(string const & name) const
1388 {
1389         DepClean::const_iterator const it = d->dep_clean.find(name);
1390         if (it == d->dep_clean.end())
1391                 return true;
1392         return it->second;
1393 }
1394
1395
1396 void Buffer::markDepClean(string const & name)
1397 {
1398         d->dep_clean[name] = true;
1399 }
1400
1401
1402 bool Buffer::dispatch(string const & command, bool * result)
1403 {
1404         return dispatch(lyxaction.lookupFunc(command), result);
1405 }
1406
1407
1408 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1409 {
1410         bool dispatched = true;
1411
1412         switch (func.action) {
1413                 case LFUN_BUFFER_EXPORT: {
1414                         bool const tmp = doExport(to_utf8(func.argument()), false);
1415                         if (result)
1416                                 *result = tmp;
1417                         break;
1418                 }
1419
1420                 default:
1421                         dispatched = false;
1422         }
1423         return dispatched;
1424 }
1425
1426
1427 void Buffer::changeLanguage(Language const * from, Language const * to)
1428 {
1429         BOOST_ASSERT(from);
1430         BOOST_ASSERT(to);
1431
1432         for_each(par_iterator_begin(),
1433                  par_iterator_end(),
1434                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1435 }
1436
1437
1438 bool Buffer::isMultiLingual() const
1439 {
1440         ParConstIterator end = par_iterator_end();
1441         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1442                 if (it->isMultiLingual(params()))
1443                         return true;
1444
1445         return false;
1446 }
1447
1448
1449 ParIterator Buffer::getParFromID(int const id) const
1450 {
1451         ParConstIterator it = par_iterator_begin();
1452         ParConstIterator const end = par_iterator_end();
1453
1454         if (id < 0) {
1455                 // John says this is called with id == -1 from undo
1456                 lyxerr << "getParFromID(), id: " << id << endl;
1457                 return end;
1458         }
1459
1460         for (; it != end; ++it)
1461                 if (it->id() == id)
1462                         return it;
1463
1464         return end;
1465 }
1466
1467
1468 bool Buffer::hasParWithID(int const id) const
1469 {
1470         ParConstIterator const it = getParFromID(id);
1471         return it != par_iterator_end();
1472 }
1473
1474
1475 ParIterator Buffer::par_iterator_begin()
1476 {
1477         return lyx::par_iterator_begin(inset());
1478 }
1479
1480
1481 ParIterator Buffer::par_iterator_end()
1482 {
1483         return lyx::par_iterator_end(inset());
1484 }
1485
1486
1487 ParConstIterator Buffer::par_iterator_begin() const
1488 {
1489         return lyx::par_const_iterator_begin(inset());
1490 }
1491
1492
1493 ParConstIterator Buffer::par_iterator_end() const
1494 {
1495         return lyx::par_const_iterator_end(inset());
1496 }
1497
1498
1499 Language const * Buffer::language() const
1500 {
1501         return params().language;
1502 }
1503
1504
1505 docstring const Buffer::B_(string const & l10n) const
1506 {
1507         return params().B_(l10n);
1508 }
1509
1510
1511 bool Buffer::isClean() const
1512 {
1513         return d->lyx_clean;
1514 }
1515
1516
1517 bool Buffer::isBakClean() const
1518 {
1519         return d->bak_clean;
1520 }
1521
1522
1523 bool Buffer::isExternallyModified(CheckMethod method) const
1524 {
1525         BOOST_ASSERT(d->filename.exists());
1526         // if method == timestamp, check timestamp before checksum
1527         return (method == checksum_method 
1528                 || d->timestamp_ != d->filename.lastModified())
1529                 && d->checksum_ != d->filename.checksum();
1530 }
1531
1532
1533 void Buffer::saveCheckSum(FileName const & file) const
1534 {
1535         if (file.exists()) {
1536                 d->timestamp_ = file.lastModified();
1537                 d->checksum_ = file.checksum();
1538         } else {
1539                 // in the case of save to a new file.
1540                 d->timestamp_ = 0;
1541                 d->checksum_ = 0;
1542         }
1543 }
1544
1545
1546 void Buffer::markClean() const
1547 {
1548         if (!d->lyx_clean) {
1549                 d->lyx_clean = true;
1550                 updateTitles();
1551         }
1552         // if the .lyx file has been saved, we don't need an
1553         // autosave
1554         d->bak_clean = true;
1555 }
1556
1557
1558 void Buffer::markBakClean() const
1559 {
1560         d->bak_clean = true;
1561 }
1562
1563
1564 void Buffer::setUnnamed(bool flag)
1565 {
1566         d->unnamed = flag;
1567 }
1568
1569
1570 bool Buffer::isUnnamed() const
1571 {
1572         return d->unnamed;
1573 }
1574
1575
1576 // FIXME: this function should be moved to buffer_pimpl.C
1577 void Buffer::markDirty()
1578 {
1579         if (d->lyx_clean) {
1580                 d->lyx_clean = false;
1581                 updateTitles();
1582         }
1583         d->bak_clean = false;
1584
1585         DepClean::iterator it = d->dep_clean.begin();
1586         DepClean::const_iterator const end = d->dep_clean.end();
1587
1588         for (; it != end; ++it)
1589                 it->second = false;
1590 }
1591
1592
1593 FileName Buffer::fileName() const
1594 {
1595         return d->filename;
1596 }
1597
1598
1599 string Buffer::absFileName() const
1600 {
1601         return d->filename.absFilename();
1602 }
1603
1604
1605 string Buffer::filePath() const
1606 {
1607         return d->filename.onlyPath().absFilename();
1608 }
1609
1610
1611 bool Buffer::isReadonly() const
1612 {
1613         return d->read_only;
1614 }
1615
1616
1617 void Buffer::setParent(Buffer const * buffer)
1618 {
1619         // Avoids recursive include.
1620         d->parent_buffer = buffer == this ? 0 : buffer;
1621 }
1622
1623
1624 Buffer const * Buffer::parent()
1625 {
1626         return d->parent_buffer;
1627 }
1628
1629
1630 Buffer const * Buffer::masterBuffer() const
1631 {
1632         if (!d->parent_buffer)
1633                 return this;
1634         
1635         return d->parent_buffer->masterBuffer();
1636 }
1637
1638
1639 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1640 {
1641         Impl::PositionToMacroMap::iterator it;
1642         it = d->macros[name].upper_bound(par.macrocontextPosition());
1643         if (it != d->macros[name].end())
1644                 return true;
1645
1646         // If there is a master buffer, query that
1647         Buffer const * master = masterBuffer();
1648         if (master && master != this)
1649                 return master->hasMacro(name);
1650
1651         return MacroTable::globalMacros().has(name);
1652 }
1653
1654
1655 bool Buffer::hasMacro(docstring const & name) const
1656 {
1657         if( !d->macros[name].empty() )
1658                 return true;
1659
1660         // If there is a master buffer, query that
1661         Buffer const * master = masterBuffer();
1662         if (master && master != this)
1663                 return master->hasMacro(name);
1664
1665         return MacroTable::globalMacros().has(name);
1666 }
1667
1668
1669 MacroData const & Buffer::getMacro(docstring const & name,
1670         Paragraph const & par) const
1671 {
1672         Impl::PositionToMacroMap::iterator it;
1673         it = d->macros[name].upper_bound(par.macrocontextPosition());
1674         if( it != d->macros[name].end() )
1675                 return it->second;
1676
1677         // If there is a master buffer, query that
1678         Buffer const * master = masterBuffer();
1679         if (master && master != this)
1680                 return master->getMacro(name);
1681
1682         return MacroTable::globalMacros().get(name);
1683 }
1684
1685
1686 MacroData const & Buffer::getMacro(docstring const & name) const
1687 {
1688         Impl::PositionToMacroMap::iterator it;
1689         it = d->macros[name].begin();
1690         if( it != d->macros[name].end() )
1691                 return it->second;
1692
1693         // If there is a master buffer, query that
1694         Buffer const * master = masterBuffer();
1695         if (master && master != this)
1696                 return master->getMacro(name);
1697
1698         return MacroTable::globalMacros().get(name);
1699 }
1700
1701
1702 void Buffer::updateMacros()
1703 {
1704         // start with empty table
1705         d->macros = Impl::NameToPositionMacroMap();
1706
1707         // Iterate over buffer
1708         ParagraphList & pars = text().paragraphs();
1709         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1710                 // set position again
1711                 pars[i].setMacrocontextPosition(i);
1712
1713                 //lyxerr << "searching main par " << i
1714                 //      << " for macro definitions" << endl;
1715                 InsetList const & insets = pars[i].insetList();
1716                 InsetList::const_iterator it = insets.begin();
1717                 InsetList::const_iterator end = insets.end();
1718                 for ( ; it != end; ++it) {
1719                         if (it->inset->lyxCode() != MATHMACRO_CODE)
1720                                 continue;
1721                         
1722                         // get macro data
1723                         MathMacroTemplate const & macroTemplate
1724                         = static_cast<MathMacroTemplate const &>(*it->inset);
1725
1726                         // valid?
1727                         if (macroTemplate.validMacro()) {
1728                                 MacroData macro = macroTemplate.asMacroData();
1729
1730                                 // redefinition?
1731                                 // call hasMacro here instead of directly querying mc to
1732                                 // also take the master document into consideration
1733                                 macro.setRedefinition(hasMacro(macroTemplate.name()));
1734
1735                                 // register macro (possibly overwrite the previous one of this paragraph)
1736                                 d->macros[macroTemplate.name()][i] = macro;
1737                         }
1738                 }
1739         }
1740 }
1741
1742
1743 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1744         InsetCode code)
1745 {
1746         //FIXME: This does not work for child documents yet.
1747         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1748         // Check if the label 'from' appears more than once
1749         vector<docstring> labels;
1750
1751         string paramName;
1752         if (code == CITE_CODE) {
1753                 BiblioInfo keys;
1754                 keys.fillWithBibKeys(this);
1755                 BiblioInfo::const_iterator bit  = keys.begin();
1756                 BiblioInfo::const_iterator bend = keys.end();
1757
1758                 for (; bit != bend; ++bit)
1759                         // FIXME UNICODE
1760                         labels.push_back(bit->first);
1761                 paramName = "key";
1762         } else {
1763                 getLabelList(labels);
1764                 paramName = "reference";
1765         }
1766
1767         if (count(labels.begin(), labels.end(), from) > 1)
1768                 return;
1769
1770         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1771                 if (it->lyxCode() == code) {
1772                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1773                         docstring const oldValue = inset.getParam(paramName);
1774                         if (oldValue == from)
1775                                 inset.setParam(paramName, to);
1776                 }
1777         }
1778 }
1779
1780
1781 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1782         pit_type par_end, bool full_source)
1783 {
1784         OutputParams runparams(&params().encoding());
1785         runparams.nice = true;
1786         runparams.flavor = OutputParams::LATEX;
1787         runparams.linelen = lyxrc.plaintext_linelen;
1788         // No side effect of file copying and image conversion
1789         runparams.dryrun = true;
1790
1791         d->texrow.reset();
1792         if (full_source) {
1793                 os << "% " << _("Preview source code") << "\n\n";
1794                 d->texrow.newline();
1795                 d->texrow.newline();
1796                 if (isLatex())
1797                         writeLaTeXSource(os, filePath(), runparams, true, true);
1798                 else {
1799                         writeDocBookSource(os, absFileName(), runparams, false);
1800                 }
1801         } else {
1802                 runparams.par_begin = par_begin;
1803                 runparams.par_end = par_end;
1804                 if (par_begin + 1 == par_end)
1805                         os << "% "
1806                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1807                            << "\n\n";
1808                 else
1809                         os << "% "
1810                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1811                                         convert<docstring>(par_begin),
1812                                         convert<docstring>(par_end - 1))
1813                            << "\n\n";
1814                 d->texrow.newline();
1815                 d->texrow.newline();
1816                 // output paragraphs
1817                 if (isLatex()) {
1818                         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1819                 } else {
1820                         // DocBook
1821                         docbookParagraphs(paragraphs(), *this, os, runparams);
1822                 }
1823         }
1824 }
1825
1826
1827 ErrorList & Buffer::errorList(string const & type) const
1828 {
1829         static ErrorList emptyErrorList;
1830         map<string, ErrorList>::iterator I = d->errorLists.find(type);
1831         if (I == d->errorLists.end())
1832                 return emptyErrorList;
1833
1834         return I->second;
1835 }
1836
1837
1838 void Buffer::structureChanged() const
1839 {
1840         if (gui_)
1841                 gui_->structureChanged();
1842 }
1843
1844
1845 void Buffer::errors(string const & err) const
1846 {
1847         if (gui_)
1848                 gui_->errors(err);
1849 }
1850
1851
1852 void Buffer::message(docstring const & msg) const
1853 {
1854         if (gui_)
1855                 gui_->message(msg);
1856 }
1857
1858
1859 void Buffer::setBusy(bool on) const
1860 {
1861         if (gui_)
1862                 gui_->setBusy(on);
1863 }
1864
1865
1866 void Buffer::setReadOnly(bool on) const
1867 {
1868         if (d->wa_)
1869                 d->wa_->setReadOnly(on);
1870 }
1871
1872
1873 void Buffer::updateTitles() const
1874 {
1875         if (d->wa_)
1876                 d->wa_->updateTitles();
1877 }
1878
1879
1880 void Buffer::resetAutosaveTimers() const
1881 {
1882         if (gui_)
1883                 gui_->resetAutosaveTimers();
1884 }
1885
1886
1887 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1888 {
1889         gui_ = gui;
1890 }
1891
1892
1893
1894 namespace {
1895
1896 class AutoSaveBuffer : public ForkedProcess {
1897 public:
1898         ///
1899         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1900                 : buffer_(buffer), fname_(fname) {}
1901         ///
1902         virtual boost::shared_ptr<ForkedProcess> clone() const
1903         {
1904                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1905         }
1906         ///
1907         int start()
1908         {
1909                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
1910                                                  from_utf8(fname_.absFilename())));
1911                 return run(DontWait);
1912         }
1913 private:
1914         ///
1915         virtual int generateChild();
1916         ///
1917         Buffer const & buffer_;
1918         FileName fname_;
1919 };
1920
1921
1922 #if !defined (HAVE_FORK)
1923 # define fork() -1
1924 #endif
1925
1926 int AutoSaveBuffer::generateChild()
1927 {
1928         // tmp_ret will be located (usually) in /tmp
1929         // will that be a problem?
1930         pid_t const pid = fork();
1931         // If you want to debug the autosave
1932         // you should set pid to -1, and comment out the fork.
1933         if (pid == 0 || pid == -1) {
1934                 // pid = -1 signifies that lyx was unable
1935                 // to fork. But we will do the save
1936                 // anyway.
1937                 bool failed = false;
1938
1939                 FileName const tmp_ret = FileName::tempName("lyxauto");
1940                 if (!tmp_ret.empty()) {
1941                         buffer_.writeFile(tmp_ret);
1942                         // assume successful write of tmp_ret
1943                         if (!tmp_ret.moveTo(fname_)) {
1944                                 failed = true;
1945                                 // most likely couldn't move between
1946                                 // filesystems unless write of tmp_ret
1947                                 // failed so remove tmp file (if it
1948                                 // exists)
1949                                 tmp_ret.removeFile();
1950                         }
1951                 } else {
1952                         failed = true;
1953                 }
1954
1955                 if (failed) {
1956                         // failed to write/rename tmp_ret so try writing direct
1957                         if (!buffer_.writeFile(fname_)) {
1958                                 // It is dangerous to do this in the child,
1959                                 // but safe in the parent, so...
1960                                 if (pid == -1) // emit message signal.
1961                                         buffer_.message(_("Autosave failed!"));
1962                         }
1963                 }
1964                 if (pid == 0) { // we are the child so...
1965                         _exit(0);
1966                 }
1967         }
1968         return pid;
1969 }
1970
1971 } // namespace anon
1972
1973
1974 // Perfect target for a thread...
1975 void Buffer::autoSave() const
1976 {
1977         if (isBakClean() || isReadonly()) {
1978                 // We don't save now, but we'll try again later
1979                 resetAutosaveTimers();
1980                 return;
1981         }
1982
1983         // emit message signal.
1984         message(_("Autosaving current document..."));
1985
1986         // create autosave filename
1987         string fname = filePath();
1988         fname += '#';
1989         fname += d->filename.onlyFileName();
1990         fname += '#';
1991
1992         AutoSaveBuffer autosave(*this, FileName(fname));
1993         autosave.start();
1994
1995         markBakClean();
1996         resetAutosaveTimers();
1997 }
1998
1999
2000 void Buffer::resetChildDocuments(bool close_them) const
2001 {
2002         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2003                 if (it->lyxCode() != INCLUDE_CODE)
2004                         continue;
2005                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2006                 InsetCommandParams const & ip = inset.params();
2007
2008                 resetParentBuffer(this, ip, close_them);
2009         }
2010
2011         if (use_gui && masterBuffer() == this)
2012                 updateLabels(*this);
2013 }
2014
2015
2016 void Buffer::loadChildDocuments() const
2017 {
2018         bool parse_error = false;
2019                 
2020         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2021                 if (it->lyxCode() != INCLUDE_CODE)
2022                         continue;
2023                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2024                 InsetCommandParams const & ip = inset.params();
2025                 Buffer * child = loadIfNeeded(*this, ip);
2026                 if (!child)
2027                         continue;
2028                 parse_error |= !child->errorList("Parse").empty();
2029                 child->loadChildDocuments();
2030         }
2031
2032         if (use_gui && masterBuffer() == this)
2033                 updateLabels(*this);
2034 }
2035
2036
2037 string Buffer::bufferFormat() const
2038 {
2039         if (isDocBook())
2040                 return "docbook";
2041         if (isLiterate())
2042                 return "literate";
2043         return "latex";
2044 }
2045
2046
2047 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2048         string & result_file) const
2049 {
2050         string backend_format;
2051         OutputParams runparams(&params().encoding());
2052         runparams.flavor = OutputParams::LATEX;
2053         runparams.linelen = lyxrc.plaintext_linelen;
2054         vector<string> backs = backends();
2055         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2056                 // Get shortest path to format
2057                 Graph::EdgePath path;
2058                 for (vector<string>::const_iterator it = backs.begin();
2059                      it != backs.end(); ++it) {
2060                         Graph::EdgePath p = theConverters().getPath(*it, format);
2061                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2062                                 backend_format = *it;
2063                                 path = p;
2064                         }
2065                 }
2066                 if (!path.empty())
2067                         runparams.flavor = theConverters().getFlavor(path);
2068                 else {
2069                         Alert::error(_("Couldn't export file"),
2070                                 bformat(_("No information for exporting the format %1$s."),
2071                                    formats.prettyName(format)));
2072                         return false;
2073                 }
2074         } else {
2075                 backend_format = format;
2076                 // FIXME: Don't hardcode format names here, but use a flag
2077                 if (backend_format == "pdflatex")
2078                         runparams.flavor = OutputParams::PDFLATEX;
2079         }
2080
2081         string filename = latexName(false);
2082         filename = addName(temppath(), filename);
2083         filename = changeExtension(filename,
2084                                    formats.extension(backend_format));
2085
2086         // Plain text backend
2087         if (backend_format == "text")
2088                 writePlaintextFile(*this, FileName(filename), runparams);
2089         // no backend
2090         else if (backend_format == "lyx")
2091                 writeFile(FileName(filename));
2092         // Docbook backend
2093         else if (isDocBook()) {
2094                 runparams.nice = !put_in_tempdir;
2095                 makeDocBookFile(FileName(filename), runparams);
2096         }
2097         // LaTeX backend
2098         else if (backend_format == format) {
2099                 runparams.nice = true;
2100                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2101                         return false;
2102         } else if (!lyxrc.tex_allows_spaces
2103                    && contains(filePath(), ' ')) {
2104                 Alert::error(_("File name error"),
2105                            _("The directory path to the document cannot contain spaces."));
2106                 return false;
2107         } else {
2108                 runparams.nice = false;
2109                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2110                         return false;
2111         }
2112
2113         string const error_type = (format == "program")
2114                 ? "Build" : bufferFormat();
2115         string const ext = formats.extension(format);
2116         FileName const tmp_result_file(changeExtension(filename, ext));
2117         bool const success = theConverters().convert(this, FileName(filename),
2118                 tmp_result_file, FileName(absFileName()), backend_format, format,
2119                 errorList(error_type));
2120         // Emit the signal to show the error list.
2121         if (format != backend_format)
2122                 errors(error_type);
2123         if (!success)
2124                 return false;
2125
2126         if (put_in_tempdir)
2127                 result_file = tmp_result_file.absFilename();
2128         else {
2129                 result_file = changeExtension(absFileName(), ext);
2130                 // We need to copy referenced files (e. g. included graphics
2131                 // if format == "dvi") to the result dir.
2132                 vector<ExportedFile> const files =
2133                         runparams.exportdata->externalFiles(format);
2134                 string const dest = onlyPath(result_file);
2135                 CopyStatus status = SUCCESS;
2136                 for (vector<ExportedFile>::const_iterator it = files.begin();
2137                                 it != files.end() && status != CANCEL; ++it) {
2138                         string const fmt =
2139                                 formats.getFormatFromFile(it->sourceName);
2140                         status = copyFile(fmt, it->sourceName,
2141                                           makeAbsPath(it->exportName, dest),
2142                                           it->exportName, status == FORCE);
2143                 }
2144                 if (status == CANCEL) {
2145                         message(_("Document export cancelled."));
2146                 } else if (tmp_result_file.exists()) {
2147                         // Finally copy the main file
2148                         status = copyFile(format, tmp_result_file,
2149                                           FileName(result_file), result_file,
2150                                           status == FORCE);
2151                         message(bformat(_("Document exported as %1$s "
2152                                                                "to file `%2$s'"),
2153                                                 formats.prettyName(format),
2154                                                 makeDisplayPath(result_file)));
2155                 } else {
2156                         // This must be a dummy converter like fax (bug 1888)
2157                         message(bformat(_("Document exported as %1$s"),
2158                                                 formats.prettyName(format)));
2159                 }
2160         }
2161
2162         return true;
2163 }
2164
2165
2166 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2167 {
2168         string result_file;
2169         return doExport(format, put_in_tempdir, result_file);
2170 }
2171
2172
2173 bool Buffer::preview(string const & format) const
2174 {
2175         string result_file;
2176         if (!doExport(format, true, result_file))
2177                 return false;
2178         return formats.view(*this, FileName(result_file), format);
2179 }
2180
2181
2182 bool Buffer::isExportable(string const & format) const
2183 {
2184         vector<string> backs = backends();
2185         for (vector<string>::const_iterator it = backs.begin();
2186              it != backs.end(); ++it)
2187                 if (theConverters().isReachable(*it, format))
2188                         return true;
2189         return false;
2190 }
2191
2192
2193 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2194 {
2195         vector<string> backs = backends();
2196         vector<Format const *> result =
2197                 theConverters().getReachable(backs[0], only_viewable, true);
2198         for (vector<string>::const_iterator it = backs.begin() + 1;
2199              it != backs.end(); ++it) {
2200                 vector<Format const *>  r =
2201                         theConverters().getReachable(*it, only_viewable, false);
2202                 result.insert(result.end(), r.begin(), r.end());
2203         }
2204         return result;
2205 }
2206
2207
2208 vector<string> Buffer::backends() const
2209 {
2210         vector<string> v;
2211         if (params().getTextClass().isTeXClassAvailable()) {
2212                 v.push_back(bufferFormat());
2213                 // FIXME: Don't hardcode format names here, but use a flag
2214                 if (v.back() == "latex")
2215                         v.push_back("pdflatex");
2216         }
2217         v.push_back("text");
2218         v.push_back("lyx");
2219         return v;
2220 }
2221
2222
2223 bool Buffer::readFileHelper(FileName const & s)
2224 {
2225         // File information about normal file
2226         if (!s.exists()) {
2227                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2228                 docstring text = bformat(_("The specified document\n%1$s"
2229                                                      "\ncould not be read."), file);
2230                 Alert::error(_("Could not read document"), text);
2231                 return false;
2232         }
2233
2234         // Check if emergency save file exists and is newer.
2235         FileName const e(s.absFilename() + ".emergency");
2236
2237         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2238                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2239                 docstring const text =
2240                         bformat(_("An emergency save of the document "
2241                                   "%1$s exists.\n\n"
2242                                                "Recover emergency save?"), file);
2243                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2244                                       _("&Recover"),  _("&Load Original"),
2245                                       _("&Cancel")))
2246                 {
2247                 case 0:
2248                         // the file is not saved if we load the emergency file.
2249                         markDirty();
2250                         return readFile(e);
2251                 case 1:
2252                         break;
2253                 default:
2254                         return false;
2255                 }
2256         }
2257
2258         // Now check if autosave file is newer.
2259         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2260
2261         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2262                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2263                 docstring const text =
2264                         bformat(_("The backup of the document "
2265                                   "%1$s is newer.\n\nLoad the "
2266                                                "backup instead?"), file);
2267                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2268                                       _("&Load backup"), _("Load &original"),
2269                                       _("&Cancel") ))
2270                 {
2271                 case 0:
2272                         // the file is not saved if we load the autosave file.
2273                         markDirty();
2274                         return readFile(a);
2275                 case 1:
2276                         // Here we delete the autosave
2277                         a.removeFile();
2278                         break;
2279                 default:
2280                         return false;
2281                 }
2282         }
2283         return readFile(s);
2284 }
2285
2286
2287 bool Buffer::loadLyXFile(FileName const & s)
2288 {
2289         if (s.isReadableFile()) {
2290                 if (readFileHelper(s)) {
2291                         lyxvc().file_found_hook(s);
2292                         if (!s.isWritable())
2293                                 setReadonly(true);
2294                         return true;
2295                 }
2296         } else {
2297                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2298                 // Here we probably should run
2299                 if (LyXVC::file_not_found_hook(s)) {
2300                         docstring const text =
2301                                 bformat(_("Do you want to retrieve the document"
2302                                                        " %1$s from version control?"), file);
2303                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2304                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2305
2306                         if (ret == 0) {
2307                                 // How can we know _how_ to do the checkout?
2308                                 // With the current VC support it has to be,
2309                                 // a RCS file since CVS do not have special ,v files.
2310                                 RCS::retrieve(s);
2311                                 return loadLyXFile(s);
2312                         }
2313                 }
2314         }
2315         return false;
2316 }
2317
2318
2319 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2320 {
2321         TeXErrors::Errors::const_iterator cit = terr.begin();
2322         TeXErrors::Errors::const_iterator end = terr.end();
2323
2324         for (; cit != end; ++cit) {
2325                 int id_start = -1;
2326                 int pos_start = -1;
2327                 int errorRow = cit->error_in_line;
2328                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2329                                                        pos_start);
2330                 int id_end = -1;
2331                 int pos_end = -1;
2332                 do {
2333                         ++errorRow;
2334                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2335                 } while (found && id_start == id_end && pos_start == pos_end);
2336
2337                 errorList.push_back(ErrorItem(cit->error_desc,
2338                         cit->error_text, id_start, pos_start, pos_end));
2339         }
2340 }
2341
2342 } // namespace lyx