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