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