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