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