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