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