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