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