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