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