]> git.lyx.org Git - lyx.git/blob - src/buffer.C
use more unicode in math
[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 void Buffer::makeLaTeXFile(string const & fname,
816                            string const & original_path,
817                            OutputParams const & runparams,
818                            bool output_preamble, bool output_body)
819 {
820         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
821
822         // FIXME UNICODE
823         // This creates an utf8 encoded file, but the inputenc commands
824         // specify other encodings
825         odocfstream ofs;
826         if (!openFileWrite(ofs, fname))
827                 return;
828
829         writeLaTeXSource(ofs, original_path,
830                       runparams, output_preamble, output_body);
831
832         ofs.close();
833         if (ofs.fail())
834                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
835 }
836
837
838 void Buffer::writeLaTeXSource(odocstream & os,
839                            string const & original_path,
840                            OutputParams const & runparams_in,
841                            bool const output_preamble, bool const output_body)
842 {
843         OutputParams runparams = runparams_in;
844
845         // validate the buffer.
846         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
847         LaTeXFeatures features(*this, params(), runparams);
848         validate(features);
849         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
850
851         texrow().reset();
852
853         // The starting paragraph of the coming rows is the
854         // first paragraph of the document. (Asger)
855         texrow().start(paragraphs().begin()->id(), 0);
856
857         if (output_preamble && runparams.nice) {
858                 os << "%% LyX " << lyx_version << " created this file.  "
859                         "For more info, see http://www.lyx.org/.\n"
860                         "%% Do not edit unless you really know what "
861                         "you are doing.\n";
862                 texrow().newline();
863                 texrow().newline();
864         }
865         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
866         // There are a few differences between nice LaTeX and usual files:
867         // usual is \batchmode and has a
868         // special input@path to allow the including of figures
869         // with either \input or \includegraphics (what figinsets do).
870         // input@path is set when the actual parameter
871         // original_path is set. This is done for usual tex-file, but not
872         // for nice-latex-file. (Matthias 250696)
873         // Note that input@path is only needed for something the user does
874         // in the preamble, included .tex files or ERT, files included by
875         // LyX work without it.
876         if (output_preamble) {
877                 if (!runparams.nice) {
878                         // code for usual, NOT nice-latex-file
879                         os << "\\batchmode\n"; // changed
880                         // from \nonstopmode
881                         texrow().newline();
882                 }
883                 if (!original_path.empty()) {
884                         // FIXME UNICODE
885                         // We don't know the encoding of inputpath
886                         docstring const inputpath = from_utf8(latex_path(original_path));
887                         os << "\\makeatletter\n"
888                            << "\\def\\input@path{{"
889                            << inputpath << "/}}\n"
890                            << "\\makeatother\n";
891                         texrow().newline();
892                         texrow().newline();
893                         texrow().newline();
894                 }
895
896                 // Write the preamble
897                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
898
899                 if (!output_body)
900                         return;
901
902                 // make the body.
903                 os << "\\begin{document}\n";
904                 texrow().newline();
905         } // output_preamble
906         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
907
908         if (!lyxrc.language_auto_begin) {
909                 // FIXME UNICODE
910                 os << from_utf8(subst(lyxrc.language_command_begin,
911                                            "$$lang",
912                                            params().language->babel()))
913                    << '\n';
914                 texrow().newline();
915         }
916
917         // if we are doing a real file with body, even if this is the
918         // child of some other buffer, let's cut the link here.
919         // This happens for example if only a child document is printed.
920         string save_parentname;
921         if (output_preamble) {
922                 save_parentname = params().parentname;
923                 params().parentname.erase();
924         }
925
926         // the real stuff
927         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
928
929         // Restore the parenthood if needed
930         if (output_preamble)
931                 params().parentname = save_parentname;
932
933         // add this just in case after all the paragraphs
934         os << endl;
935         texrow().newline();
936
937         if (!lyxrc.language_auto_end) {
938                 os << from_utf8(subst(lyxrc.language_command_end,
939                                            "$$lang",
940                                            params().language->babel()))
941                    << '\n';
942                 texrow().newline();
943         }
944
945         if (output_preamble) {
946                 os << "\\end{document}\n";
947                 texrow().newline();
948
949                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
950         } else {
951                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
952                                      << endl;
953         }
954
955         // Just to be sure. (Asger)
956         texrow().newline();
957
958         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
959         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
960                             << '.' << endl;
961 }
962
963
964 bool Buffer::isLatex() const
965 {
966         return params().getLyXTextClass().outputType() == LATEX;
967 }
968
969
970 bool Buffer::isLiterate() const
971 {
972         return params().getLyXTextClass().outputType() == LITERATE;
973 }
974
975
976 bool Buffer::isDocBook() const
977 {
978         return params().getLyXTextClass().outputType() == DOCBOOK;
979 }
980
981
982 void Buffer::makeDocBookFile(string const & fname,
983                               OutputParams const & runparams,
984                               bool const body_only)
985 {
986         lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
987
988         //ofstream ofs;
989         odocfstream ofs;
990         if (!openFileWrite(ofs, fname))
991                 return;
992
993         writeDocBookSource(ofs, fname, runparams, body_only);
994
995         ofs.close();
996         if (ofs.fail())
997                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
998 }
999
1000
1001 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1002                              OutputParams const & runparams,
1003                              bool const only_body)
1004 {
1005         LaTeXFeatures features(*this, params(), runparams);
1006         validate(features);
1007
1008         texrow().reset();
1009
1010         LyXTextClass const & tclass = params().getLyXTextClass();
1011         string const top_element = tclass.latexname();
1012
1013         if (!only_body) {
1014                 if (runparams.flavor == OutputParams::XML)
1015                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1016
1017                 // FIXME UNICODE
1018                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1019
1020                 // FIXME UNICODE
1021                 if (! tclass.class_header().empty())
1022                         os << from_ascii(tclass.class_header());
1023                 else if (runparams.flavor == OutputParams::XML)
1024                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1025                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1026                 else
1027                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1028
1029                 docstring preamble = from_utf8(params().preamble);
1030                 if (runparams.flavor != OutputParams::XML ) {
1031                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1032                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1033                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1034                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1035                 }
1036
1037                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1038                          : fname;
1039                 preamble += features.getIncludedFiles(name);
1040                 preamble += features.getLyXSGMLEntities();
1041
1042                 if (!preamble.empty()) {
1043                         os << "\n [ " << preamble << " ]";
1044                 }
1045                 os << ">\n\n";
1046         }
1047
1048         string top = top_element;
1049         top += " lang=\"";
1050         if (runparams.flavor == OutputParams::XML)
1051                 top += params().language->code();
1052         else
1053                 top += params().language->code().substr(0,2);
1054         top += '"';
1055
1056         if (!params().options.empty()) {
1057                 top += ' ';
1058                 top += params().options;
1059         }
1060
1061         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1062             << " file was created by LyX " << lyx_version
1063             << "\n  See http://www.lyx.org/ for more information -->\n";
1064
1065         params().getLyXTextClass().counters().reset();
1066
1067         sgml::openTag(os, top);
1068         os << '\n';
1069         docbookParagraphs(paragraphs(), *this, os, runparams);
1070         sgml::closeTag(os, top_element);
1071 }
1072
1073
1074 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1075 // Other flags: -wall -v0 -x
1076 int Buffer::runChktex()
1077 {
1078         busy(true);
1079
1080         // get LaTeX-Filename
1081         string const name = getLatexName();
1082         string const path = temppath();
1083         string const org_path = filePath();
1084
1085         support::Path p(path); // path to LaTeX file
1086         message(_("Running chktex..."));
1087
1088         // Generate the LaTeX file if neccessary
1089         OutputParams runparams;
1090         runparams.flavor = OutputParams::LATEX;
1091         runparams.nice = false;
1092         makeLaTeXFile(name, org_path, runparams);
1093
1094         TeXErrors terr;
1095         Chktex chktex(lyxrc.chktex_command, name, filePath());
1096         int const res = chktex.run(terr); // run chktex
1097
1098         if (res == -1) {
1099                 Alert::error(_("chktex failure"),
1100                              _("Could not run chktex successfully."));
1101         } else if (res > 0) {
1102                 // Fill-in the error list with the TeX errors
1103                 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1104         }
1105
1106         busy(false);
1107
1108         errors("ChkTeX");
1109
1110         return res;
1111 }
1112
1113
1114 void Buffer::validate(LaTeXFeatures & features) const
1115 {
1116         LyXTextClass const & tclass = params().getLyXTextClass();
1117
1118         if (features.isAvailable("dvipost") && params().outputChanges)
1119                 features.require("dvipost");
1120
1121         // AMS Style is at document level
1122         if (params().use_amsmath == BufferParams::AMS_ON
1123             || tclass.provides(LyXTextClass::amsmath))
1124                 features.require("amsmath");
1125
1126         for_each(paragraphs().begin(), paragraphs().end(),
1127                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1128
1129         // the bullet shapes are buffer level not paragraph level
1130         // so they are tested here
1131         for (int i = 0; i < 4; ++i) {
1132                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1133                         int const font = params().user_defined_bullet(i).getFont();
1134                         if (font == 0) {
1135                                 int const c = params()
1136                                         .user_defined_bullet(i)
1137                                         .getCharacter();
1138                                 if (c == 16
1139                                    || c == 17
1140                                    || c == 25
1141                                    || c == 26
1142                                    || c == 31) {
1143                                         features.require("latexsym");
1144                                 }
1145                         } else if (font == 1) {
1146                                 features.require("amssymb");
1147                         } else if ((font >= 2 && font <= 5)) {
1148                                 features.require("pifont");
1149                         }
1150                 }
1151         }
1152
1153         if (lyxerr.debugging(Debug::LATEX)) {
1154                 features.showStruct();
1155         }
1156 }
1157
1158
1159 void Buffer::getLabelList(vector<docstring> & list) const
1160 {
1161         /// if this is a child document and the parent is already loaded
1162         /// Use the parent's list instead  [ale990407]
1163         Buffer const * tmp = getMasterBuffer();
1164         if (!tmp) {
1165                 lyxerr << "getMasterBuffer() failed!" << endl;
1166                 BOOST_ASSERT(tmp);
1167         }
1168         if (tmp != this) {
1169                 tmp->getLabelList(list);
1170                 return;
1171         }
1172
1173         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1174                 it.nextInset()->getLabelList(*this, list);
1175 }
1176
1177
1178 // This is also a buffer property (ale)
1179 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1180         const
1181 {
1182         /// if this is a child document and the parent is already loaded
1183         /// use the parent's list instead  [ale990412]
1184         Buffer const * tmp = getMasterBuffer();
1185         BOOST_ASSERT(tmp);
1186         if (tmp != this) {
1187                 tmp->fillWithBibKeys(keys);
1188                 return;
1189         }
1190
1191         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1192                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1193                         InsetBibtex const & inset =
1194                                 dynamic_cast<InsetBibtex const &>(*it);
1195                         inset.fillWithBibKeys(*this, keys);
1196                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1197                         InsetInclude const & inset =
1198                                 dynamic_cast<InsetInclude const &>(*it);
1199                         inset.fillWithBibKeys(*this, keys);
1200                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1201                         InsetBibitem const & inset =
1202                                 dynamic_cast<InsetBibitem const &>(*it);
1203                         string const key = inset.getContents();
1204                         string const opt = inset.getOptions();
1205                         string const ref; // = pit->asString(this, false);
1206                         string const info = opt + "TheBibliographyRef" + ref;
1207                         keys.push_back(pair<string, string>(key, info));
1208                 }
1209         }
1210 }
1211
1212
1213 void Buffer::updateBibfilesCache()
1214 {
1215         // if this is a child document and the parent is already loaded
1216         // update the parent's cache instead
1217         Buffer * tmp = getMasterBuffer();
1218         BOOST_ASSERT(tmp);
1219         if (tmp != this) {
1220                 tmp->updateBibfilesCache();
1221                 return;
1222         }
1223
1224         bibfilesCache_.clear();
1225         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1226                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1227                         InsetBibtex const & inset =
1228                                 dynamic_cast<InsetBibtex const &>(*it);
1229                         vector<string> const bibfiles = inset.getFiles(*this);
1230                         bibfilesCache_.insert(bibfilesCache_.end(),
1231                                 bibfiles.begin(),
1232                                 bibfiles.end());
1233                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1234                         InsetInclude & inset =
1235                                 dynamic_cast<InsetInclude &>(*it);
1236                         inset.updateBibfilesCache(*this);
1237                         vector<string> const & bibfiles =
1238                                         inset.getBibfilesCache(*this);
1239                         bibfilesCache_.insert(bibfilesCache_.end(),
1240                                 bibfiles.begin(),
1241                                 bibfiles.end());
1242                 }
1243         }
1244 }
1245
1246
1247 vector<string> const & Buffer::getBibfilesCache() const
1248 {
1249         // if this is a child document and the parent is already loaded
1250         // use the parent's cache instead
1251         Buffer const * tmp = getMasterBuffer();
1252         BOOST_ASSERT(tmp);
1253         if (tmp != this)
1254                 return tmp->getBibfilesCache();
1255
1256         return bibfilesCache_;
1257 }
1258
1259
1260 bool Buffer::isDepClean(string const & name) const
1261 {
1262         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1263         if (it == pimpl_->dep_clean.end())
1264                 return true;
1265         return it->second;
1266 }
1267
1268
1269 void Buffer::markDepClean(string const & name)
1270 {
1271         pimpl_->dep_clean[name] = true;
1272 }
1273
1274
1275 bool Buffer::dispatch(string const & command, bool * result)
1276 {
1277         return dispatch(lyxaction.lookupFunc(command), result);
1278 }
1279
1280
1281 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1282 {
1283         bool dispatched = true;
1284
1285         switch (func.action) {
1286                 case LFUN_BUFFER_EXPORT: {
1287                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1288                         if (result)
1289                                 *result = tmp;
1290                         break;
1291                 }
1292
1293                 default:
1294                         dispatched = false;
1295         }
1296         return dispatched;
1297 }
1298
1299
1300 void Buffer::changeLanguage(Language const * from, Language const * to)
1301 {
1302         BOOST_ASSERT(from);
1303         BOOST_ASSERT(to);
1304
1305         // Take care of l10n/i18n
1306         updateDocLang(to);
1307
1308         for_each(par_iterator_begin(),
1309                  par_iterator_end(),
1310                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1311
1312         text().current_font.setLanguage(to);
1313         text().real_current_font.setLanguage(to);
1314 }
1315
1316
1317 void Buffer::updateDocLang(Language const * nlang)
1318 {
1319         BOOST_ASSERT(nlang);
1320
1321         pimpl_->messages.reset(new Messages(nlang->code()));
1322
1323         updateLabels(*this);
1324 }
1325
1326
1327 bool Buffer::isMultiLingual() const
1328 {
1329         ParConstIterator end = par_iterator_end();
1330         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1331                 if (it->isMultiLingual(params()))
1332                         return true;
1333
1334         return false;
1335 }
1336
1337
1338 ParIterator Buffer::getParFromID(int const id) const
1339 {
1340         ParConstIterator it = par_iterator_begin();
1341         ParConstIterator const end = par_iterator_end();
1342
1343         if (id < 0) {
1344                 // John says this is called with id == -1 from undo
1345                 lyxerr << "getParFromID(), id: " << id << endl;
1346                 return end;
1347         }
1348
1349         for (; it != end; ++it)
1350                 if (it->id() == id)
1351                         return it;
1352
1353         return end;
1354 }
1355
1356
1357 bool Buffer::hasParWithID(int const id) const
1358 {
1359         ParConstIterator const it = getParFromID(id);
1360         return it != par_iterator_end();
1361 }
1362
1363
1364 ParIterator Buffer::par_iterator_begin()
1365 {
1366         return lyx::par_iterator_begin(inset());
1367 }
1368
1369
1370 ParIterator Buffer::par_iterator_end()
1371 {
1372         return lyx::par_iterator_end(inset());
1373 }
1374
1375
1376 ParConstIterator Buffer::par_iterator_begin() const
1377 {
1378         return lyx::par_const_iterator_begin(inset());
1379 }
1380
1381
1382 ParConstIterator Buffer::par_iterator_end() const
1383 {
1384         return lyx::par_const_iterator_end(inset());
1385 }
1386
1387
1388 Language const * Buffer::getLanguage() const
1389 {
1390         return params().language;
1391 }
1392
1393
1394 docstring const Buffer::B_(string const & l10n) const
1395 {
1396         if (pimpl_->messages.get()) 
1397                 return pimpl_->messages->get(l10n);
1398
1399         return _(l10n);
1400 }
1401
1402
1403 bool Buffer::isClean() const
1404 {
1405         return pimpl_->lyx_clean;
1406 }
1407
1408
1409 bool Buffer::isBakClean() const
1410 {
1411         return pimpl_->bak_clean;
1412 }
1413
1414
1415 void Buffer::markClean() const
1416 {
1417         if (!pimpl_->lyx_clean) {
1418                 pimpl_->lyx_clean = true;
1419                 updateTitles();
1420         }
1421         // if the .lyx file has been saved, we don't need an
1422         // autosave
1423         pimpl_->bak_clean = true;
1424 }
1425
1426
1427 void Buffer::markBakClean()
1428 {
1429         pimpl_->bak_clean = true;
1430 }
1431
1432
1433 void Buffer::setUnnamed(bool flag)
1434 {
1435         pimpl_->unnamed = flag;
1436 }
1437
1438
1439 bool Buffer::isUnnamed() const
1440 {
1441         return pimpl_->unnamed;
1442 }
1443
1444
1445 #ifdef WITH_WARNINGS
1446 #warning this function should be moved to buffer_pimpl.C
1447 #endif
1448 void Buffer::markDirty()
1449 {
1450         if (pimpl_->lyx_clean) {
1451                 pimpl_->lyx_clean = false;
1452                 updateTitles();
1453         }
1454         pimpl_->bak_clean = false;
1455
1456         DepClean::iterator it = pimpl_->dep_clean.begin();
1457         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1458
1459         for (; it != end; ++it)
1460                 it->second = false;
1461 }
1462
1463
1464 string const & Buffer::fileName() const
1465 {
1466         return pimpl_->filename;
1467 }
1468
1469
1470 string const & Buffer::filePath() const
1471 {
1472         return params().filepath;
1473 }
1474
1475
1476 bool Buffer::isReadonly() const
1477 {
1478         return pimpl_->read_only;
1479 }
1480
1481
1482 void Buffer::setParentName(string const & name)
1483 {
1484         params().parentname = name;
1485 }
1486
1487
1488 Buffer const * Buffer::getMasterBuffer() const
1489 {
1490         if (!params().parentname.empty()
1491             && theBufferList().exists(params().parentname)) {
1492                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1493                 if (buf)
1494                         return buf->getMasterBuffer();
1495         }
1496
1497         return this;
1498 }
1499
1500
1501 Buffer * Buffer::getMasterBuffer()
1502 {
1503         if (!params().parentname.empty()
1504             && theBufferList().exists(params().parentname)) {
1505                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1506                 if (buf)
1507                         return buf->getMasterBuffer();
1508         }
1509
1510         return this;
1511 }
1512
1513
1514 MacroData const & Buffer::getMacro(docstring const & name) const
1515 {
1516         return pimpl_->macros.get(name);
1517 }
1518
1519
1520 bool Buffer::hasMacro(docstring const & name) const
1521 {
1522         return pimpl_->macros.has(name);
1523 }
1524
1525
1526 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1527 {
1528         MacroTable::globalMacros().insert(name, data);
1529         pimpl_->macros.insert(name, data);
1530 }
1531
1532
1533 void Buffer::buildMacros()
1534 {
1535         // Start with global table.
1536         pimpl_->macros = MacroTable::globalMacros();
1537
1538         // Now add our own.
1539         ParagraphList const & pars = text().paragraphs();
1540         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1541                 //lyxerr << "searching main par " << i
1542                 //      << " for macro definitions" << std::endl;
1543                 InsetList const & insets = pars[i].insetlist;
1544                 InsetList::const_iterator it = insets.begin();
1545                 InsetList::const_iterator end = insets.end();
1546                 for ( ; it != end; ++it) {
1547                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1548                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1549                                 MathMacroTemplate const & mac
1550                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1551                                 insertMacro(mac.name(), mac.asMacroData());
1552                         }
1553                 }
1554         }
1555 }
1556
1557
1558 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1559 {
1560         cursor_ = cur;
1561         anchor_ = anc;
1562 }
1563
1564
1565 void Buffer::changeRefsIfUnique(string const & from, string const & to, InsetBase::Code code)
1566 {
1567         //FIXME: This does not work for child documents yet.
1568         BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1569         // Check if the label 'from' appears more than once
1570         vector<docstring> labels;
1571
1572         if (code == InsetBase::CITE_CODE) {
1573                 vector<pair<string, string> > keys;
1574                 fillWithBibKeys(keys);
1575                 vector<pair<string, string> >::const_iterator bit  = keys.begin();
1576                 vector<pair<string, string> >::const_iterator bend = keys.end();
1577
1578                 for (; bit != bend; ++bit)
1579                         // FIXME UNICODE
1580                         labels.push_back(from_utf8(bit->first));
1581         } else
1582                 getLabelList(labels);
1583
1584         // FIXME UNICODE
1585         if (lyx::count(labels.begin(), labels.end(), from_utf8(from)) > 1)
1586                 return;
1587
1588         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1589                 if (it->lyxCode() == code) {
1590                         InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1591                         inset.replaceContents(from, to);
1592                 }
1593         }
1594 }
1595
1596
1597 void Buffer::getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end, bool full_source)
1598 {
1599         OutputParams runparams;
1600         runparams.nice = true;
1601         runparams.flavor = OutputParams::LATEX;
1602         runparams.linelen = lyxrc.ascii_linelen;
1603         // No side effect of file copying and image conversion
1604         runparams.dryrun = true;
1605
1606         /* Support for docbook temprarily commented out. */
1607         if (full_source) {
1608                 os << "% Preview source code\n\n";
1609                 if (isLatex())
1610                         writeLaTeXSource(os, filePath(), runparams, true, true);
1611                 else {
1612                         writeDocBookSource(os, fileName(), runparams, false);
1613                 }
1614         } else {
1615                 runparams.par_begin = par_begin;
1616                 runparams.par_end = par_end;
1617                 if (par_begin + 1 == par_end)
1618                         os << "% Preview source code for paragraph " << par_begin << "\n\n";
1619                 else
1620                         os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1621                 // output paragraphs
1622                 if (isLatex()) {
1623                         texrow().reset();
1624                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1625                 } else {
1626                         // DocBook
1627                         docbookParagraphs(paragraphs(), *this, os, runparams);
1628                 }
1629         }
1630 }
1631
1632
1633 ErrorList const & Buffer::errorList(string const & type) const
1634 {
1635         static ErrorList const emptyErrorList;
1636         std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1637         if (I == errorLists_.end())
1638                 return emptyErrorList;
1639
1640         return I->second;
1641 }
1642
1643
1644 ErrorList & Buffer::errorList(string const & type)
1645 {
1646         return errorLists_[type];
1647 }
1648
1649
1650 } // namespace lyx