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