]> git.lyx.org Git - features.git/blob - src/Buffer.cpp
e5de38c4822312d9198ff5850e25c63f9feea08e
[features.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Buffer.h"
14
15 #include "Author.h"
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "Counters.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "debug.h"
24 #include "Encoding.h"
25 #include "ErrorList.h"
26 #include "Exporter.h"
27 #include "Format.h"
28 #include "FuncRequest.h"
29 #include "gettext.h"
30 #include "InsetIterator.h"
31 #include "Language.h"
32 #include "LaTeX.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
35 #include "Lexer.h"
36 #include "Text.h"
37 #include "LyX.h"
38 #include "LyXRC.h"
39 #include "LyXVC.h"
40 #include "Messages.h"
41 #include "output.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "sgml.h"
49 #include "TexRow.h"
50 #include "TocBackend.h"
51 #include "Undo.h"
52 #include "version.h"
53
54 #include "insets/InsetBibitem.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetInclude.h"
57 #include "insets/InsetText.h"
58
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MacroTable.h"
61 #include "mathed/MathSupport.h"
62
63 #include "frontends/alert.h"
64
65 #include "graphics/Previews.h"
66
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #include "support/gzstream.h"
72 #include "support/lyxlib.h"
73 #include "support/os.h"
74 #include "support/Path.h"
75 #include "support/textutils.h"
76 #include "support/convert.h"
77
78 #include <boost/bind.hpp>
79 #include <boost/filesystem/exception.hpp>
80 #include <boost/filesystem/operations.hpp>
81
82 #if defined (HAVE_UTIME_H)
83 #include <utime.h>
84 #elif defined (HAVE_SYS_UTIME_H)
85 #include <sys/utime.h>
86 #endif
87
88 #include <iomanip>
89 #include <stack>
90 #include <sstream>
91 #include <fstream>
92
93 using std::endl;
94 using std::for_each;
95 using std::make_pair;
96
97 using std::ios;
98 using std::map;
99 using std::ostream;
100 using std::ostringstream;
101 using std::ofstream;
102 using std::pair;
103 using std::stack;
104 using std::vector;
105 using std::string;
106 using std::time_t;
107
108
109 namespace lyx {
110
111 using support::addName;
112 using support::bformat;
113 using support::changeExtension;
114 using support::cmd_ret;
115 using support::createBufferTmpDir;
116 using support::destroyDir;
117 using support::FileName;
118 using support::getFormatFromContents;
119 using support::libFileSearch;
120 using support::latex_path;
121 using support::ltrim;
122 using support::makeAbsPath;
123 using support::makeDisplayPath;
124 using support::makeLatexName;
125 using support::onlyFilename;
126 using support::onlyPath;
127 using support::quoteName;
128 using support::removeAutosaveFile;
129 using support::rename;
130 using support::runCommand;
131 using support::split;
132 using support::subst;
133 using support::tempName;
134 using support::trim;
135 using support::sum;
136
137 namespace Alert = frontend::Alert;
138 namespace os = support::os;
139 namespace fs = boost::filesystem;
140
141 namespace {
142
143 int const LYX_FORMAT = 276;
144
145 } // namespace anon
146
147
148 typedef std::map<string, bool> DepClean;
149
150 class Buffer::Impl
151 {
152 public:
153         Impl(Buffer & parent, FileName const & file, bool readonly);
154
155         limited_stack<Undo> undostack;
156         limited_stack<Undo> redostack;
157         BufferParams params;
158         LyXVC lyxvc;
159         string temppath;
160         TexRow texrow;
161
162         /// need to regenerate .tex?
163         DepClean dep_clean;
164
165         /// is save needed?
166         mutable bool lyx_clean;
167
168         /// is autosave needed?
169         mutable bool bak_clean;
170
171         /// is this a unnamed file (New...)?
172         bool unnamed;
173
174         /// buffer is r/o
175         bool read_only;
176
177         /// name of the file the buffer is associated with.
178         FileName filename;
179
180         /** Set to true only when the file is fully loaded.
181          *  Used to prevent the premature generation of previews
182          *  and by the citation inset.
183          */
184         bool file_fully_loaded;
185
186         /// our Text that should be wrapped in an InsetText
187         InsetText inset;
188
189         ///
190         MacroTable macros;
191
192         ///
193         TocBackend toc_backend;
194
195         /// Container for all sort of Buffer dependant errors.
196         map<string, ErrorList> errorLists;
197
198         /// timestamp and checksum used to test if the file has been externally
199         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200         time_t timestamp_;
201         unsigned long checksum_;
202 };
203
204
205 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
206         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
207           filename(file), file_fully_loaded(false), inset(params),
208           timestamp_(0), checksum_(0), toc_backend(&parent)
209 {
210         inset.setAutoBreakRows(true);
211         lyxvc.buffer(&parent);
212         temppath = createBufferTmpDir();
213         params.filepath = onlyPath(file.absFilename());
214         // FIXME: And now do something if temppath == string(), because we
215         // assume from now on that temppath points to a valid temp dir.
216         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
217 }
218
219
220 Buffer::Buffer(string const & file, bool readonly)
221         : pimpl_(new Impl(*this, FileName(file), readonly))
222 {
223         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
224 }
225
226
227 Buffer::~Buffer()
228 {
229         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
230         // here the buffer should take care that it is
231         // saved properly, before it goes into the void.
232
233         closing();
234
235         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
236                 Alert::warning(_("Could not remove temporary directory"),
237                         bformat(_("Could not remove the temporary directory %1$s"),
238                         from_utf8(temppath())));
239         }
240
241         // Remove any previewed LaTeX snippets associated with this buffer.
242         graphics::Previews::get().removeLoader(*this);
243 }
244
245
246 Text & Buffer::text() const
247 {
248         return const_cast<Text &>(pimpl_->inset.text_);
249 }
250
251
252 Inset & Buffer::inset() const
253 {
254         return const_cast<InsetText &>(pimpl_->inset);
255 }
256
257
258 limited_stack<Undo> & Buffer::undostack()
259 {
260         return pimpl_->undostack;
261 }
262
263
264 limited_stack<Undo> const & Buffer::undostack() const
265 {
266         return pimpl_->undostack;
267 }
268
269
270 limited_stack<Undo> & Buffer::redostack()
271 {
272         return pimpl_->redostack;
273 }
274
275
276 limited_stack<Undo> const & Buffer::redostack() const
277 {
278         return pimpl_->redostack;
279 }
280
281
282 BufferParams & Buffer::params()
283 {
284         return pimpl_->params;
285 }
286
287
288 BufferParams const & Buffer::params() const
289 {
290         return pimpl_->params;
291 }
292
293
294 ParagraphList & Buffer::paragraphs()
295 {
296         return text().paragraphs();
297 }
298
299
300 ParagraphList const & Buffer::paragraphs() const
301 {
302         return text().paragraphs();
303 }
304
305
306 LyXVC & Buffer::lyxvc()
307 {
308         return pimpl_->lyxvc;
309 }
310
311
312 LyXVC const & Buffer::lyxvc() const
313 {
314         return pimpl_->lyxvc;
315 }
316
317
318 string const & Buffer::temppath() const
319 {
320         return pimpl_->temppath;
321 }
322
323
324 TexRow & Buffer::texrow()
325 {
326         return pimpl_->texrow;
327 }
328
329
330 TexRow const & Buffer::texrow() const
331 {
332         return pimpl_->texrow;
333 }
334
335
336 TocBackend & Buffer::tocBackend()
337 {
338         return pimpl_->toc_backend;
339 }
340
341
342 TocBackend const & Buffer::tocBackend() const
343 {
344         return pimpl_->toc_backend;
345 }
346
347
348 string const Buffer::getLatexName(bool const no_path) const
349 {
350         string const name = changeExtension(makeLatexName(fileName()), ".tex");
351         return no_path ? onlyFilename(name) : name;
352 }
353
354
355 pair<Buffer::LogType, string> const Buffer::getLogName() const
356 {
357         string const filename = getLatexName(false);
358
359         if (filename.empty())
360                 return make_pair(Buffer::latexlog, string());
361
362         string const path = temppath();
363
364         FileName const fname(addName(temppath(),
365                                      onlyFilename(changeExtension(filename,
366                                                                   ".log"))));
367         FileName const bname(
368                 addName(path, onlyFilename(
369                         changeExtension(filename,
370                                         formats.extension("literate") + ".out"))));
371
372         // If no Latex log or Build log is newer, show Build log
373
374         if (fs::exists(bname.toFilesystemEncoding()) &&
375             (!fs::exists(fname.toFilesystemEncoding()) ||
376              fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
377                 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
378                 return make_pair(Buffer::buildlog, bname.absFilename());
379         }
380         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
381         return make_pair(Buffer::latexlog, fname.absFilename());
382 }
383
384
385 void Buffer::setReadonly(bool const flag)
386 {
387         if (pimpl_->read_only != flag) {
388                 pimpl_->read_only = flag;
389                 readonly(flag);
390         }
391 }
392
393
394 void Buffer::setFileName(string const & newfile)
395 {
396         pimpl_->filename = makeAbsPath(newfile);
397         params().filepath = onlyPath(pimpl_->filename.absFilename());
398         setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
399         updateTitles();
400 }
401
402
403 // We'll remove this later. (Lgb)
404 namespace {
405
406 void unknownClass(string const & unknown)
407 {
408         Alert::warning(_("Unknown document class"),
409                        bformat(_("Using the default document class, because the "
410                                               "class %1$s is unknown."), from_utf8(unknown)));
411 }
412
413 } // anon
414
415
416 int Buffer::readHeader(Lexer & lex)
417 {
418         int unknown_tokens = 0;
419         int line = -1;
420         int begin_header_line = -1;
421
422         // Initialize parameters that may be/go lacking in header:
423         params().branchlist().clear();
424         params().preamble.erase();
425         params().options.erase();
426         params().float_placement.erase();
427         params().paperwidth.erase();
428         params().paperheight.erase();
429         params().leftmargin.erase();
430         params().rightmargin.erase();
431         params().topmargin.erase();
432         params().bottommargin.erase();
433         params().headheight.erase();
434         params().headsep.erase();
435         params().footskip.erase();
436         params().listings_params.clear();
437         for (int i = 0; i < 4; ++i) {
438                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
439                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
440         }
441
442         ErrorList & errorList = pimpl_->errorLists["Parse"];
443
444         while (lex.isOK()) {
445                 lex.next();
446                 string const token = lex.getString();
447
448                 if (token.empty())
449                         continue;
450
451                 if (token == "\\end_header")
452                         break;
453
454                 ++line;
455                 if (token == "\\begin_header") {
456                         begin_header_line = line;
457                         continue;
458                 }
459
460                 LYXERR(Debug::PARSER) << "Handling document header token: `"
461                                       << token << '\'' << endl;
462
463                 string unknown = params().readToken(lex, token);
464                 if (!unknown.empty()) {
465                         if (unknown[0] != '\\' && token == "\\textclass") {
466                                 unknownClass(unknown);
467                         } else {
468                                 ++unknown_tokens;
469                                 docstring const s = bformat(_("Unknown token: "
470                                                                         "%1$s %2$s\n"),
471                                                          from_utf8(token),
472                                                          lex.getDocString());
473                                 errorList.push_back(ErrorItem(_("Document header error"),
474                                         s, -1, 0, 0));
475                         }
476                 }
477         }
478         if (begin_header_line) {
479                 docstring const s = _("\\begin_header is missing");
480                 errorList.push_back(ErrorItem(_("Document header error"),
481                         s, -1, 0, 0));
482         }
483
484         return unknown_tokens;
485 }
486
487
488 // Uwe C. Schroeder
489 // changed to be public and have one parameter
490 // Returns false if "\end_document" is not read (Asger)
491 bool Buffer::readDocument(Lexer & lex)
492 {
493         ErrorList & errorList = pimpl_->errorLists["Parse"];
494         errorList.clear();
495
496         lex.next();
497         string const token = lex.getString();
498         if (token != "\\begin_document") {
499                 docstring const s = _("\\begin_document is missing");
500                 errorList.push_back(ErrorItem(_("Document header error"),
501                         s, -1, 0, 0));
502         }
503
504         // we are reading in a brand new document
505         BOOST_ASSERT(paragraphs().empty());
506
507         readHeader(lex);
508         if (!params().getTextClass().load(filePath())) {
509                 string theclass = params().getTextClass().name();
510                 Alert::error(_("Can't load document class"), bformat(
511                         _("Using the default document class, because the "
512                                      "class %1$s could not be loaded."), from_utf8(theclass)));
513                 params().textclass = 0;
514         }
515
516         if (params().outputChanges) {
517                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
518                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
519                                   LaTeXFeatures::isAvailable("xcolor");
520
521                 if (!dvipost && !xcolorsoul) {
522                         Alert::warning(_("Changes not shown in LaTeX output"),
523                                        _("Changes will not be highlighted in LaTeX output, "
524                                          "because neither dvipost nor xcolor/soul are installed.\n"
525                                          "Please install these packages or redefine "
526                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
527                 } else if (!xcolorsoul) {
528                         Alert::warning(_("Changes not shown in LaTeX output"),
529                                        _("Changes will not be highlighted in LaTeX output "
530                                          "when using pdflatex, because xcolor and soul are not installed.\n"
531                                          "Please install both packages or redefine "
532                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
533                 }
534         }
535
536         bool const res = text().read(*this, lex, errorList);
537         for_each(text().paragraphs().begin(),
538                  text().paragraphs().end(),
539                  bind(&Paragraph::setInsetOwner, _1, &inset()));
540
541         return res;
542 }
543
544
545 // needed to insert the selection
546 void Buffer::insertStringAsLines(ParagraphList & pars,
547         pit_type & pit, pos_type & pos,
548         Font const & fn, docstring const & str, bool autobreakrows)
549 {
550         Font font = fn;
551
552         // insert the string, don't insert doublespace
553         bool space_inserted = true;
554         for (docstring::const_iterator cit = str.begin();
555             cit != str.end(); ++cit) {
556                 Paragraph & par = pars[pit];
557                 if (*cit == '\n') {
558                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
559                                 breakParagraph(params(), pars, pit, pos,
560                                                par.layout()->isEnvironment());
561                                 ++pit;
562                                 pos = 0;
563                                 space_inserted = true;
564                         } else {
565                                 continue;
566                         }
567                         // do not insert consecutive spaces if !free_spacing
568                 } else if ((*cit == ' ' || *cit == '\t') &&
569                            space_inserted && !par.isFreeSpacing()) {
570                         continue;
571                 } else if (*cit == '\t') {
572                         if (!par.isFreeSpacing()) {
573                                 // tabs are like spaces here
574                                 par.insertChar(pos, ' ', font, params().trackChanges);
575                                 ++pos;
576                                 space_inserted = true;
577                         } else {
578                                 const pos_type n = 8 - pos % 8;
579                                 for (pos_type i = 0; i < n; ++i) {
580                                         par.insertChar(pos, ' ', font, params().trackChanges);
581                                         ++pos;
582                                 }
583                                 space_inserted = true;
584                         }
585                 } else if (!isPrintable(*cit)) {
586                         // Ignore unprintables
587                         continue;
588                 } else {
589                         // just insert the character
590                         par.insertChar(pos, *cit, font, params().trackChanges);
591                         ++pos;
592                         space_inserted = (*cit == ' ');
593                 }
594
595         }
596 }
597
598
599 bool Buffer::readString(std::string const & s)
600 {
601         params().compressed = false;
602
603         // remove dummy empty par
604         paragraphs().clear();
605         Lexer lex(0, 0);
606         std::istringstream is(s);
607         lex.setStream(is);
608         FileName const name(tempName());
609         switch (readFile(lex, name, true)) {
610         case failure:
611                 return false;
612         case wrongversion: {
613                 // We need to call lyx2lyx, so write the input to a file
614                 std::ofstream os(name.toFilesystemEncoding().c_str());
615                 os << s;
616                 os.close();
617                 return readFile(name);
618         }
619         case success:
620                 break;
621         }
622
623         return true;
624 }
625
626
627 bool Buffer::readFile(FileName const & filename)
628 {
629         // Check if the file is compressed.
630         string const format = getFormatFromContents(filename);
631         if (format == "gzip" || format == "zip" || format == "compress") {
632                 params().compressed = true;
633         }
634
635         // remove dummy empty par
636         paragraphs().clear();
637         Lexer lex(0, 0);
638         lex.setFile(filename);
639         if (readFile(lex, filename) != success)
640                 return false;
641
642         return true;
643 }
644
645
646 bool Buffer::fully_loaded() const
647 {
648         return pimpl_->file_fully_loaded;
649 }
650
651
652 void Buffer::fully_loaded(bool const value)
653 {
654         pimpl_->file_fully_loaded = value;
655 }
656
657
658 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
659                 bool fromstring)
660 {
661         BOOST_ASSERT(!filename.empty());
662
663         if (!lex.isOK()) {
664                 Alert::error(_("Document could not be read"),
665                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
666                 return failure;
667         }
668
669         lex.next();
670         string const token(lex.getString());
671
672         if (!lex) {
673                 Alert::error(_("Document could not be read"),
674                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
675                 return failure;
676         }
677
678         // the first token _must_ be...
679         if (token != "\\lyxformat") {
680                 lyxerr << "Token: " << token << endl;
681
682                 Alert::error(_("Document format failure"),
683                              bformat(_("%1$s is not a LyX document."),
684                                        from_utf8(filename.absFilename())));
685                 return failure;
686         }
687
688         lex.next();
689         string tmp_format = lex.getString();
690         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
691         // if present remove ".," from string.
692         string::size_type dot = tmp_format.find_first_of(".,");
693         //lyxerr << "           dot found at " << dot << endl;
694         if (dot != string::npos)
695                         tmp_format.erase(dot, 1);
696         int const file_format = convert<int>(tmp_format);
697         //lyxerr << "format: " << file_format << endl;
698
699         if (file_format != LYX_FORMAT) {
700
701                 if (fromstring)
702                         // lyx2lyx would fail
703                         return wrongversion;
704
705                 FileName const tmpfile(tempName());
706                 if (tmpfile.empty()) {
707                         Alert::error(_("Conversion failed"),
708                                      bformat(_("%1$s is from a different"
709                                               " version of LyX, but a temporary"
710                                               " file for converting it could"
711                                                             " not be created."),
712                                               from_utf8(filename.absFilename())));
713                         return failure;
714                 }
715                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
716                 if (lyx2lyx.empty()) {
717                         Alert::error(_("Conversion script not found"),
718                                      bformat(_("%1$s is from a different"
719                                                " version of LyX, but the"
720                                                " conversion script lyx2lyx"
721                                                             " could not be found."),
722                                                from_utf8(filename.absFilename())));
723                         return failure;
724                 }
725                 ostringstream command;
726                 command << os::python()
727                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
728                         << " -t " << convert<string>(LYX_FORMAT)
729                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
730                         << ' ' << quoteName(filename.toFilesystemEncoding());
731                 string const command_str = command.str();
732
733                 LYXERR(Debug::INFO) << "Running '"
734                                     << command_str << '\''
735                                     << endl;
736
737                 cmd_ret const ret = runCommand(command_str);
738                 if (ret.first != 0) {
739                         Alert::error(_("Conversion script failed"),
740                                      bformat(_("%1$s is from a different version"
741                                               " of LyX, but the lyx2lyx script"
742                                                             " failed to convert it."),
743                                               from_utf8(filename.absFilename())));
744                         return failure;
745                 } else {
746                         bool const ret = readFile(tmpfile);
747                         // Do stuff with tmpfile name and buffer name here.
748                         return ret ? success : failure;
749                 }
750
751         }
752
753         if (readDocument(lex)) {
754                 Alert::error(_("Document format failure"),
755                              bformat(_("%1$s ended unexpectedly, which means"
756                                                     " that it is probably corrupted."),
757                                        from_utf8(filename.absFilename())));
758         }
759
760         //lyxerr << "removing " << MacroTable::localMacros().size()
761         //      << " temporary macro entries" << endl;
762         //MacroTable::localMacros().clear();
763
764         pimpl_->file_fully_loaded = true;
765         // save the timestamp and checksum of disk file
766         pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
767         pimpl_->checksum_ = sum(filename);
768         return success;
769 }
770
771
772 // Should probably be moved to somewhere else: BufferView? LyXView?
773 bool Buffer::save() const
774 {
775         // We don't need autosaves in the immediate future. (Asger)
776         resetAutosaveTimers();
777
778         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
779
780         FileName backupName;
781         bool madeBackup = false;
782
783         // make a backup if the file already exists
784         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
785                 backupName = FileName(fileName() + '~');
786                 if (!lyxrc.backupdir_path.empty())
787                         backupName = FileName(addName(lyxrc.backupdir_path,
788                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
789
790                 try {
791                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
792                         madeBackup = true;
793                 } catch (fs::filesystem_error const & fe) {
794                         Alert::error(_("Backup failure"),
795                                      bformat(_("Cannot create backup file %1$s.\n"
796                                                "Please check whether the directory exists and is writeable."),
797                                              from_utf8(backupName.absFilename())));
798                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
799                 }
800         }
801
802         // ask if the disk file has been externally modified (use checksum method)
803         if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
804                 docstring const file = makeDisplayPath(fileName(), 20);
805                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
806                                                              "you want to overwrite this file?"), file);
807                 int const ret = Alert::prompt(_("Overwrite modified file?"),
808                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
809                 if (ret == 1)
810                         return false;
811         }
812
813         if (writeFile(pimpl_->filename)) {
814                 markClean();
815                 removeAutosaveFile(fileName());
816                 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
817                 pimpl_->checksum_ = sum(pimpl_->filename);
818                 return true;
819         } else {
820                 // Saving failed, so backup is not backup
821                 if (madeBackup)
822                         rename(backupName, pimpl_->filename);
823                 return false;
824         }
825 }
826
827
828 bool Buffer::writeFile(FileName const & fname) const
829 {
830         if (pimpl_->read_only && fname == pimpl_->filename)
831                 return false;
832
833         bool retval = false;
834
835         if (params().compressed) {
836                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
837                 if (!ofs)
838                         return false;
839
840                 retval = write(ofs);
841         } else {
842                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
843                 if (!ofs)
844                         return false;
845
846                 retval = write(ofs);
847         }
848
849         return retval;
850 }
851
852
853 bool Buffer::write(ostream & ofs) const
854 {
855 #ifdef HAVE_LOCALE
856         // Use the standard "C" locale for file output.
857         ofs.imbue(std::locale::classic());
858 #endif
859
860         // The top of the file should not be written by params().
861
862         // write out a comment in the top of the file
863         ofs << "#LyX " << lyx_version
864             << " created this file. For more info see http://www.lyx.org/\n"
865             << "\\lyxformat " << LYX_FORMAT << "\n"
866             << "\\begin_document\n";
867
868
869         /// For each author, set 'used' to true if there is a change
870         /// by this author in the document; otherwise set it to 'false'.
871         AuthorList::Authors::const_iterator a_it = params().authors().begin();
872         AuthorList::Authors::const_iterator a_end = params().authors().end();
873         for (; a_it != a_end; ++a_it)
874                 a_it->second.used(false);
875
876         ParIterator const end = par_iterator_end();
877         ParIterator it = par_iterator_begin();
878         for ( ; it != end; ++it)
879                 it->checkAuthors(params().authors());
880
881         // now write out the buffer parameters.
882         ofs << "\\begin_header\n";
883         params().writeFile(ofs);
884         ofs << "\\end_header\n";
885
886         // write the text
887         ofs << "\n\\begin_body\n";
888         text().write(*this, ofs);
889         ofs << "\n\\end_body\n";
890
891         // Write marker that shows file is complete
892         ofs << "\\end_document" << endl;
893
894         // Shouldn't really be needed....
895         //ofs.close();
896
897         // how to check if close went ok?
898         // Following is an attempt... (BE 20001011)
899
900         // good() returns false if any error occured, including some
901         //        formatting error.
902         // bad()  returns true if something bad happened in the buffer,
903         //        which should include file system full errors.
904
905         bool status = true;
906         if (!ofs) {
907                 status = false;
908                 lyxerr << "File was not closed properly." << endl;
909         }
910
911         return status;
912 }
913
914
915 bool Buffer::makeLaTeXFile(FileName const & fname,
916                            string const & original_path,
917                            OutputParams const & runparams,
918                            bool output_preamble, bool output_body)
919 {
920         string const encoding = runparams.encoding->iconvName();
921         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
922                 << encoding << "..." << endl;
923
924         odocfstream ofs(encoding);
925         if (!openFileWrite(ofs, fname))
926                 return false;
927
928         bool failed_export = false;
929         try {
930                 writeLaTeXSource(ofs, original_path,
931                       runparams, output_preamble, output_body);
932         }
933         catch (iconv_codecvt_facet_exception & e) {
934                 lyxerr << "Caught iconv exception: " << e.what() << endl;
935                 failed_export = true;
936         }
937         catch (std::exception  const & e) {
938                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
939                 failed_export = true;
940         }
941         catch (...) {
942                 lyxerr << "Caught some really weird exception..." << endl;
943                 LyX::cref().emergencyCleanup();
944                 abort();
945         }
946
947         ofs.close();
948         if (ofs.fail()) {
949                 failed_export = true;
950                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
951         }
952
953         if (failed_export) {
954                 Alert::error(_("Encoding error"),
955                         _("Some characters of your document are probably not "
956                         "representable in the chosen encoding.\n"
957                         "Changing the document encoding to utf8 could help."));
958                 return false;
959         }
960         return true;
961 }
962
963
964 void Buffer::writeLaTeXSource(odocstream & os,
965                            string const & original_path,
966                            OutputParams const & runparams_in,
967                            bool const output_preamble, bool const output_body)
968 {
969         OutputParams runparams = runparams_in;
970
971         // validate the buffer.
972         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
973         LaTeXFeatures features(*this, params(), runparams);
974         validate(features);
975         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
976
977         texrow().reset();
978
979         // The starting paragraph of the coming rows is the
980         // first paragraph of the document. (Asger)
981         texrow().start(paragraphs().begin()->id(), 0);
982
983         if (output_preamble && runparams.nice) {
984                 os << "%% LyX " << lyx_version << " created this file.  "
985                         "For more info, see http://www.lyx.org/.\n"
986                         "%% Do not edit unless you really know what "
987                         "you are doing.\n";
988                 texrow().newline();
989                 texrow().newline();
990         }
991         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
992         // There are a few differences between nice LaTeX and usual files:
993         // usual is \batchmode and has a
994         // special input@path to allow the including of figures
995         // with either \input or \includegraphics (what figinsets do).
996         // input@path is set when the actual parameter
997         // original_path is set. This is done for usual tex-file, but not
998         // for nice-latex-file. (Matthias 250696)
999         // Note that input@path is only needed for something the user does
1000         // in the preamble, included .tex files or ERT, files included by
1001         // LyX work without it.
1002         if (output_preamble) {
1003                 if (!runparams.nice) {
1004                         // code for usual, NOT nice-latex-file
1005                         os << "\\batchmode\n"; // changed
1006                         // from \nonstopmode
1007                         texrow().newline();
1008                 }
1009                 if (!original_path.empty()) {
1010                         // FIXME UNICODE
1011                         // We don't know the encoding of inputpath
1012                         docstring const inputpath = from_utf8(latex_path(original_path));
1013                         os << "\\makeatletter\n"
1014                            << "\\def\\input@path{{"
1015                            << inputpath << "/}}\n"
1016                            << "\\makeatother\n";
1017                         texrow().newline();
1018                         texrow().newline();
1019                         texrow().newline();
1020                 }
1021
1022                 // Write the preamble
1023                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1024
1025                 if (!output_body)
1026                         return;
1027
1028                 // make the body.
1029                 os << "\\begin{document}\n";
1030                 texrow().newline();
1031         } // output_preamble
1032         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1033
1034         if (!lyxrc.language_auto_begin &&
1035             !params().language->babel().empty()) {
1036                 // FIXME UNICODE
1037                 os << from_utf8(subst(lyxrc.language_command_begin,
1038                                            "$$lang",
1039                                            params().language->babel()))
1040                    << '\n';
1041                 texrow().newline();
1042         }
1043
1044         Encoding const & encoding = params().encoding();
1045         if (encoding.package() == Encoding::CJK) {
1046                 // Open a CJK environment, since in contrast to the encodings
1047                 // handled by inputenc the document encoding is not set in
1048                 // the preamble if it is handled by CJK.sty.
1049                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1050                    << "}{}\n";
1051                 texrow().newline();
1052         }
1053
1054         // if we are doing a real file with body, even if this is the
1055         // child of some other buffer, let's cut the link here.
1056         // This happens for example if only a child document is printed.
1057         string save_parentname;
1058         if (output_preamble) {
1059                 save_parentname = params().parentname;
1060                 params().parentname.erase();
1061         }
1062
1063         // the real stuff
1064         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1065
1066         // Restore the parenthood if needed
1067         if (output_preamble)
1068                 params().parentname = save_parentname;
1069
1070         // add this just in case after all the paragraphs
1071         os << endl;
1072         texrow().newline();
1073
1074         if (encoding.package() == Encoding::CJK) {
1075                 // Close the open CJK environment.
1076                 // latexParagraphs will have opened one even if the last text
1077                 // was not CJK.
1078                 os << "\\end{CJK}\n";
1079                 texrow().newline();
1080         }
1081
1082         if (!lyxrc.language_auto_end &&
1083             !params().language->babel().empty()) {
1084                 os << from_utf8(subst(lyxrc.language_command_end,
1085                                            "$$lang",
1086                                            params().language->babel()))
1087                    << '\n';
1088                 texrow().newline();
1089         }
1090
1091         if (output_preamble) {
1092                 os << "\\end{document}\n";
1093                 texrow().newline();
1094
1095                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1096         } else {
1097                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1098                                      << endl;
1099         }
1100         runparams_in.encoding = runparams.encoding;
1101
1102         // Just to be sure. (Asger)
1103         texrow().newline();
1104
1105         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1106         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1107                             << '.' << endl;
1108 }
1109
1110
1111 bool Buffer::isLatex() const
1112 {
1113         return params().getTextClass().outputType() == LATEX;
1114 }
1115
1116
1117 bool Buffer::isLiterate() const
1118 {
1119         return params().getTextClass().outputType() == LITERATE;
1120 }
1121
1122
1123 bool Buffer::isDocBook() const
1124 {
1125         return params().getTextClass().outputType() == DOCBOOK;
1126 }
1127
1128
1129 void Buffer::makeDocBookFile(FileName const & fname,
1130                               OutputParams const & runparams,
1131                               bool const body_only)
1132 {
1133         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1134
1135         //ofstream ofs;
1136         odocfstream ofs;
1137         if (!openFileWrite(ofs, fname))
1138                 return;
1139
1140         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1141
1142         ofs.close();
1143         if (ofs.fail())
1144                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1145 }
1146
1147
1148 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1149                              OutputParams const & runparams,
1150                              bool const only_body)
1151 {
1152         LaTeXFeatures features(*this, params(), runparams);
1153         validate(features);
1154
1155         texrow().reset();
1156
1157         TextClass const & tclass = params().getTextClass();
1158         string const top_element = tclass.latexname();
1159
1160         if (!only_body) {
1161                 if (runparams.flavor == OutputParams::XML)
1162                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1163
1164                 // FIXME UNICODE
1165                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1166
1167                 // FIXME UNICODE
1168                 if (! tclass.class_header().empty())
1169                         os << from_ascii(tclass.class_header());
1170                 else if (runparams.flavor == OutputParams::XML)
1171                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1172                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1173                 else
1174                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1175
1176                 docstring preamble = from_utf8(params().preamble);
1177                 if (runparams.flavor != OutputParams::XML ) {
1178                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1179                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1180                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1181                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1182                 }
1183
1184                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1185                          : fname;
1186                 preamble += features.getIncludedFiles(name);
1187                 preamble += features.getLyXSGMLEntities();
1188
1189                 if (!preamble.empty()) {
1190                         os << "\n [ " << preamble << " ]";
1191                 }
1192                 os << ">\n\n";
1193         }
1194
1195         string top = top_element;
1196         top += " lang=\"";
1197         if (runparams.flavor == OutputParams::XML)
1198                 top += params().language->code();
1199         else
1200                 top += params().language->code().substr(0,2);
1201         top += '"';
1202
1203         if (!params().options.empty()) {
1204                 top += ' ';
1205                 top += params().options;
1206         }
1207
1208         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1209             << " file was created by LyX " << lyx_version
1210             << "\n  See http://www.lyx.org/ for more information -->\n";
1211
1212         params().getTextClass().counters().reset();
1213
1214         sgml::openTag(os, top);
1215         os << '\n';
1216         docbookParagraphs(paragraphs(), *this, os, runparams);
1217         sgml::closeTag(os, top_element);
1218 }
1219
1220
1221 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1222 // Other flags: -wall -v0 -x
1223 int Buffer::runChktex()
1224 {
1225         busy(true);
1226
1227         // get LaTeX-Filename
1228         FileName const path(temppath());
1229         string const name = addName(path.absFilename(), getLatexName());
1230         string const org_path = filePath();
1231
1232         support::Path p(path); // path to LaTeX file
1233         message(_("Running chktex..."));
1234
1235         // Generate the LaTeX file if neccessary
1236         OutputParams runparams(&params().encoding());
1237         runparams.flavor = OutputParams::LATEX;
1238         runparams.nice = false;
1239         makeLaTeXFile(FileName(name), org_path, runparams);
1240
1241         TeXErrors terr;
1242         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1243         int const res = chktex.run(terr); // run chktex
1244
1245         if (res == -1) {
1246                 Alert::error(_("chktex failure"),
1247                              _("Could not run chktex successfully."));
1248         } else if (res > 0) {
1249                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1250                 // Clear out old errors
1251                 errorList.clear();
1252                 // Fill-in the error list with the TeX errors
1253                 bufferErrors(*this, terr, errorList);
1254         }
1255
1256         busy(false);
1257
1258         errors("ChkTeX");
1259
1260         return res;
1261 }
1262
1263
1264 void Buffer::validate(LaTeXFeatures & features) const
1265 {
1266         TextClass const & tclass = params().getTextClass();
1267
1268         if (params().outputChanges) {
1269                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1270                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1271                                   LaTeXFeatures::isAvailable("xcolor");
1272
1273                 if (features.runparams().flavor == OutputParams::LATEX) {
1274                         if (dvipost) {
1275                                 features.require("ct-dvipost");
1276                                 features.require("dvipost");
1277                         } else if (xcolorsoul) {
1278                                 features.require("ct-xcolor-soul");
1279                                 features.require("soul");
1280                                 features.require("xcolor");
1281                         } else {
1282                                 features.require("ct-none");
1283                         }
1284                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1285                         if (xcolorsoul) {
1286                                 features.require("ct-xcolor-soul");
1287                                 features.require("soul");
1288                                 features.require("xcolor");
1289                                 features.require("pdfcolmk"); // improves color handling in PDF output
1290                         } else {
1291                                 features.require("ct-none");
1292                         }
1293                 }
1294         }
1295
1296         // AMS Style is at document level
1297         if (params().use_amsmath == BufferParams::package_on
1298             || tclass.provides("amsmath"))
1299                 features.require("amsmath");
1300         if (params().use_esint == BufferParams::package_on)
1301                 features.require("esint");
1302
1303         for_each(paragraphs().begin(), paragraphs().end(),
1304                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1305
1306         // the bullet shapes are buffer level not paragraph level
1307         // so they are tested here
1308         for (int i = 0; i < 4; ++i) {
1309                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1310                         int const font = params().user_defined_bullet(i).getFont();
1311                         if (font == 0) {
1312                                 int const c = params()
1313                                         .user_defined_bullet(i)
1314                                         .getCharacter();
1315                                 if (c == 16
1316                                    || c == 17
1317                                    || c == 25
1318                                    || c == 26
1319                                    || c == 31) {
1320                                         features.require("latexsym");
1321                                 }
1322                         } else if (font == 1) {
1323                                 features.require("amssymb");
1324                         } else if ((font >= 2 && font <= 5)) {
1325                                 features.require("pifont");
1326                         }
1327                 }
1328         }
1329
1330         if (lyxerr.debugging(Debug::LATEX)) {
1331                 features.showStruct();
1332         }
1333 }
1334
1335
1336 void Buffer::getLabelList(vector<docstring> & list) const
1337 {
1338         /// if this is a child document and the parent is already loaded
1339         /// Use the parent's list instead  [ale990407]
1340         Buffer const * tmp = getMasterBuffer();
1341         if (!tmp) {
1342                 lyxerr << "getMasterBuffer() failed!" << endl;
1343                 BOOST_ASSERT(tmp);
1344         }
1345         if (tmp != this) {
1346                 tmp->getLabelList(list);
1347                 return;
1348         }
1349
1350         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1351                 it.nextInset()->getLabelList(*this, list);
1352 }
1353
1354
1355 // This is also a buffer property (ale)
1356 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1357         const
1358 {
1359         /// if this is a child document and the parent is already loaded
1360         /// use the parent's list instead  [ale990412]
1361         Buffer const * tmp = getMasterBuffer();
1362         BOOST_ASSERT(tmp);
1363         if (tmp != this) {
1364                 tmp->fillWithBibKeys(keys);
1365                 return;
1366         }
1367
1368         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1369                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1370                         InsetBibtex const & inset =
1371                                 static_cast<InsetBibtex const &>(*it);
1372                         inset.fillWithBibKeys(*this, keys);
1373                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1374                         InsetInclude const & inset =
1375                                 static_cast<InsetInclude const &>(*it);
1376                         inset.fillWithBibKeys(*this, keys);
1377                 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1378                         InsetBibitem const & inset =
1379                                 static_cast<InsetBibitem const &>(*it);
1380                         // FIXME UNICODE
1381                         string const key = to_utf8(inset.getParam("key"));
1382                         docstring const label = inset.getParam("label");
1383                         DocIterator doc_it(it); doc_it.forwardPos();
1384                         docstring const ref = doc_it.paragraph().asString(*this, false);
1385                         docstring const info = label + "TheBibliographyRef" + ref;
1386                         keys.push_back(pair<string, docstring>(key, info));
1387                 }
1388         }
1389 }
1390
1391
1392 void Buffer::updateBibfilesCache()
1393 {
1394         // if this is a child document and the parent is already loaded
1395         // update the parent's cache instead
1396         Buffer * tmp = getMasterBuffer();
1397         BOOST_ASSERT(tmp);
1398         if (tmp != this) {
1399                 tmp->updateBibfilesCache();
1400                 return;
1401         }
1402
1403         bibfilesCache_.clear();
1404         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1405                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1406                         InsetBibtex const & inset =
1407                                 static_cast<InsetBibtex const &>(*it);
1408                         vector<FileName> const bibfiles = inset.getFiles(*this);
1409                         bibfilesCache_.insert(bibfilesCache_.end(),
1410                                 bibfiles.begin(),
1411                                 bibfiles.end());
1412                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1413                         InsetInclude & inset =
1414                                 static_cast<InsetInclude &>(*it);
1415                         inset.updateBibfilesCache(*this);
1416                         vector<FileName> const & bibfiles =
1417                                         inset.getBibfilesCache(*this);
1418                         bibfilesCache_.insert(bibfilesCache_.end(),
1419                                 bibfiles.begin(),
1420                                 bibfiles.end());
1421                 }
1422         }
1423 }
1424
1425
1426 vector<FileName> const & Buffer::getBibfilesCache() const
1427 {
1428         // if this is a child document and the parent is already loaded
1429         // use the parent's cache instead
1430         Buffer const * tmp = getMasterBuffer();
1431         BOOST_ASSERT(tmp);
1432         if (tmp != this)
1433                 return tmp->getBibfilesCache();
1434
1435         // We update the cache when first used instead of at loading time.
1436         if (bibfilesCache_.empty())
1437                 const_cast<Buffer *>(this)->updateBibfilesCache();
1438
1439         return bibfilesCache_;
1440 }
1441
1442
1443 bool Buffer::isDepClean(string const & name) const
1444 {
1445         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1446         if (it == pimpl_->dep_clean.end())
1447                 return true;
1448         return it->second;
1449 }
1450
1451
1452 void Buffer::markDepClean(string const & name)
1453 {
1454         pimpl_->dep_clean[name] = true;
1455 }
1456
1457
1458 bool Buffer::dispatch(string const & command, bool * result)
1459 {
1460         return dispatch(lyxaction.lookupFunc(command), result);
1461 }
1462
1463
1464 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1465 {
1466         bool dispatched = true;
1467
1468         switch (func.action) {
1469                 case LFUN_BUFFER_EXPORT: {
1470                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1471                         if (result)
1472                                 *result = tmp;
1473                         break;
1474                 }
1475
1476                 default:
1477                         dispatched = false;
1478         }
1479         return dispatched;
1480 }
1481
1482
1483 void Buffer::changeLanguage(Language const * from, Language const * to)
1484 {
1485         BOOST_ASSERT(from);
1486         BOOST_ASSERT(to);
1487
1488         for_each(par_iterator_begin(),
1489                  par_iterator_end(),
1490                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1491
1492         text().current_font.setLanguage(to);
1493         text().real_current_font.setLanguage(to);
1494 }
1495
1496
1497 bool Buffer::isMultiLingual() const
1498 {
1499         ParConstIterator end = par_iterator_end();
1500         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1501                 if (it->isMultiLingual(params()))
1502                         return true;
1503
1504         return false;
1505 }
1506
1507
1508 ParIterator Buffer::getParFromID(int const id) const
1509 {
1510         ParConstIterator it = par_iterator_begin();
1511         ParConstIterator const end = par_iterator_end();
1512
1513         if (id < 0) {
1514                 // John says this is called with id == -1 from undo
1515                 lyxerr << "getParFromID(), id: " << id << endl;
1516                 return end;
1517         }
1518
1519         for (; it != end; ++it)
1520                 if (it->id() == id)
1521                         return it;
1522
1523         return end;
1524 }
1525
1526
1527 bool Buffer::hasParWithID(int const id) const
1528 {
1529         ParConstIterator const it = getParFromID(id);
1530         return it != par_iterator_end();
1531 }
1532
1533
1534 ParIterator Buffer::par_iterator_begin()
1535 {
1536         return lyx::par_iterator_begin(inset());
1537 }
1538
1539
1540 ParIterator Buffer::par_iterator_end()
1541 {
1542         return lyx::par_iterator_end(inset());
1543 }
1544
1545
1546 ParConstIterator Buffer::par_iterator_begin() const
1547 {
1548         return lyx::par_const_iterator_begin(inset());
1549 }
1550
1551
1552 ParConstIterator Buffer::par_iterator_end() const
1553 {
1554         return lyx::par_const_iterator_end(inset());
1555 }
1556
1557
1558 Language const * Buffer::getLanguage() const
1559 {
1560         return params().language;
1561 }
1562
1563
1564 docstring const Buffer::B_(string const & l10n) const
1565 {
1566         return params().B_(l10n);
1567 }
1568
1569
1570 bool Buffer::isClean() const
1571 {
1572         return pimpl_->lyx_clean;
1573 }
1574
1575
1576 bool Buffer::isBakClean() const
1577 {
1578         return pimpl_->bak_clean;
1579 }
1580
1581
1582 bool Buffer::isExternallyModified(CheckMethod method) const
1583 {
1584         BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1585         // if method == timestamp, check timestamp before checksum
1586         return (method == checksum_method 
1587                 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1588                 && pimpl_->checksum_ != sum(pimpl_->filename);
1589 }
1590
1591
1592 void Buffer::markClean() const
1593 {
1594         if (!pimpl_->lyx_clean) {
1595                 pimpl_->lyx_clean = true;
1596                 updateTitles();
1597         }
1598         // if the .lyx file has been saved, we don't need an
1599         // autosave
1600         pimpl_->bak_clean = true;
1601 }
1602
1603
1604 void Buffer::markBakClean()
1605 {
1606         pimpl_->bak_clean = true;
1607 }
1608
1609
1610 void Buffer::setUnnamed(bool flag)
1611 {
1612         pimpl_->unnamed = flag;
1613 }
1614
1615
1616 bool Buffer::isUnnamed() const
1617 {
1618         return pimpl_->unnamed;
1619 }
1620
1621
1622 #ifdef WITH_WARNINGS
1623 #warning this function should be moved to buffer_pimpl.C
1624 #endif
1625 void Buffer::markDirty()
1626 {
1627         if (pimpl_->lyx_clean) {
1628                 pimpl_->lyx_clean = false;
1629                 updateTitles();
1630         }
1631         pimpl_->bak_clean = false;
1632
1633         DepClean::iterator it = pimpl_->dep_clean.begin();
1634         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1635
1636         for (; it != end; ++it)
1637                 it->second = false;
1638 }
1639
1640
1641 string const Buffer::fileName() const
1642 {
1643         return pimpl_->filename.absFilename();
1644 }
1645
1646
1647 string const & Buffer::filePath() const
1648 {
1649         return params().filepath;
1650 }
1651
1652
1653 bool Buffer::isReadonly() const
1654 {
1655         return pimpl_->read_only;
1656 }
1657
1658
1659 void Buffer::setParentName(string const & name)
1660 {
1661         if (name == pimpl_->filename.absFilename())
1662                 // Avoids recursive include.
1663                 params().parentname.clear();
1664         else
1665                 params().parentname = name;
1666 }
1667
1668
1669 Buffer const * Buffer::getMasterBuffer() const
1670 {
1671         if (!params().parentname.empty()
1672             && theBufferList().exists(params().parentname)) {
1673                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1674                 //We need to check if the parent is us...
1675                 //FIXME RECURSIVE INCLUDE
1676                 //This is not sufficient, since recursive includes could be downstream.
1677                 if (buf && buf != this)
1678                         return buf->getMasterBuffer();
1679         }
1680
1681         return this;
1682 }
1683
1684
1685 Buffer * Buffer::getMasterBuffer()
1686 {
1687         if (!params().parentname.empty()
1688             && theBufferList().exists(params().parentname)) {
1689                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1690                 if (buf)
1691                         return buf->getMasterBuffer();
1692         }
1693
1694         return this;
1695 }
1696
1697
1698 MacroData const & Buffer::getMacro(docstring const & name) const
1699 {
1700         return pimpl_->macros.get(name);
1701 }
1702
1703
1704 bool Buffer::hasMacro(docstring const & name) const
1705 {
1706         return pimpl_->macros.has(name);
1707 }
1708
1709
1710 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1711 {
1712         MacroTable::globalMacros().insert(name, data);
1713         pimpl_->macros.insert(name, data);
1714 }
1715
1716
1717 void Buffer::buildMacros()
1718 {
1719         // Start with global table.
1720         pimpl_->macros = MacroTable::globalMacros();
1721
1722         // Now add our own.
1723         ParagraphList const & pars = text().paragraphs();
1724         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1725                 //lyxerr << "searching main par " << i
1726                 //      << " for macro definitions" << std::endl;
1727                 InsetList const & insets = pars[i].insetlist;
1728                 InsetList::const_iterator it = insets.begin();
1729                 InsetList::const_iterator end = insets.end();
1730                 for ( ; it != end; ++it) {
1731                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1732                         if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1733                                 MathMacroTemplate const & mac
1734                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1735                                 insertMacro(mac.name(), mac.asMacroData());
1736                         }
1737                 }
1738         }
1739 }
1740
1741
1742 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1743 {
1744         cursor_ = cur;
1745         anchor_ = anc;
1746 }
1747
1748
1749 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1750         Inset::Code code)
1751 {
1752         //FIXME: This does not work for child documents yet.
1753         BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1754         // Check if the label 'from' appears more than once
1755         vector<docstring> labels;
1756
1757         if (code == Inset::CITE_CODE) {
1758                 vector<pair<string, docstring> > keys;
1759                 fillWithBibKeys(keys);
1760                 vector<pair<string, docstring> >::const_iterator bit  = keys.begin();
1761                 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1762
1763                 for (; bit != bend; ++bit)
1764                         // FIXME UNICODE
1765                         labels.push_back(from_utf8(bit->first));
1766         } else
1767                 getLabelList(labels);
1768
1769         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1770                 return;
1771
1772         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1773                 if (it->lyxCode() == code) {
1774                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1775                         inset.replaceContents(to_utf8(from), to_utf8(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         if (full_source) {
1792                 os << "% " << _("Preview source code") << "\n\n";
1793                 if (isLatex())
1794                         writeLaTeXSource(os, filePath(), runparams, true, true);
1795                 else {
1796                         writeDocBookSource(os, fileName(), runparams, false);
1797                 }
1798         } else {
1799                 runparams.par_begin = par_begin;
1800                 runparams.par_end = par_end;
1801                 if (par_begin + 1 == par_end)
1802                         os << "% "
1803                            << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1804                            << "\n\n";
1805                 else
1806                         os << "% "
1807                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1808                                         convert<docstring>(par_begin),
1809                                         convert<docstring>(par_end - 1))
1810                            << "\n\n";
1811                 // output paragraphs
1812                 if (isLatex()) {
1813                         texrow().reset();
1814                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1815                 } else {
1816                         // DocBook
1817                         docbookParagraphs(paragraphs(), *this, os, runparams);
1818                 }
1819         }
1820 }
1821
1822
1823 ErrorList const & Buffer::errorList(string const & type) const
1824 {
1825         static ErrorList const emptyErrorList;
1826         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1827         if (I == pimpl_->errorLists.end())
1828                 return emptyErrorList;
1829
1830         return I->second;
1831 }
1832
1833
1834 ErrorList & Buffer::errorList(string const & type)
1835 {
1836         return pimpl_->errorLists[type];
1837 }
1838
1839
1840 } // namespace lyx