]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Remove the now superseeded SConscript files, and some small missing parts to SConstruct
[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 "output_linuxdoc.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
49 #include "sgml.h"
50 #include "texrow.h"
51 #include "undo.h"
52 #include "version.h"
53
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
58
59 #include "mathed/math_macrotemplate.h"
60 #include "mathed/math_macrotable.h"
61 #include "mathed/math_support.h"
62
63 #include "frontends/Alert.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/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::pos_type;
97 using lyx::pit_type;
98
99 using lyx::support::addName;
100 using lyx::support::bformat;
101 using lyx::support::changeExtension;
102 using lyx::support::cmd_ret;
103 using lyx::support::createBufferTmpDir;
104 using lyx::support::destroyDir;
105 using lyx::support::getFormatFromContents;
106 using lyx::support::isDirWriteable;
107 using lyx::support::libFileSearch;
108 using lyx::support::latex_path;
109 using lyx::support::ltrim;
110 using lyx::support::makeAbsPath;
111 using lyx::support::makeDisplayPath;
112 using lyx::support::makeLatexName;
113 using lyx::support::onlyFilename;
114 using lyx::support::onlyPath;
115 using lyx::support::Path;
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 = 245;
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"), 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."), 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         while (lex.isOK()) {
421                 lex.next();
422                 string const token = lex.getString();
423
424                 if (token.empty())
425                         continue;
426
427                 if (token == "\\end_header")
428                         break;
429
430                 ++line;
431                 if (token == "\\begin_header") {
432                         begin_header_line = line;
433                         continue;
434                 }
435
436                 lyxerr[Debug::PARSER] << "Handling document header token: `"
437                                       << token << '\'' << endl;
438
439                 string unknown = params().readToken(lex, token);
440                 if (!unknown.empty()) {
441                         if (unknown[0] != '\\' && token == "\\textclass") {
442                                 unknownClass(unknown);
443                         } else {
444                                 ++unknown_tokens;
445                                 string const s = bformat(_("Unknown token: "
446                                                            "%1$s %2$s\n"),
447                                                          token,
448                                                          lex.getString());
449                                 error(ErrorItem(_("Document header error"), s,
450                                                 -1, 0, 0));
451                         }
452                 }
453         }
454         if (begin_header_line) {
455                 string const s = _("\\begin_header is missing");
456                 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
457         }
458         return unknown_tokens;
459 }
460
461
462 // Uwe C. Schroeder
463 // changed to be public and have one parameter
464 // Returns false if "\end_document" is not read (Asger)
465 bool Buffer::readDocument(LyXLex & lex)
466 {
467         lex.next();
468         string const token = lex.getString();
469         if (token != "\\begin_document") {
470                 string const s = _("\\begin_document is missing");
471                 error(ErrorItem(_("Document header error"), s, -1, 0, 0));
472         }
473
474         // we are reading in a brand new document
475         BOOST_ASSERT(paragraphs().empty());
476
477         readHeader(lex);
478         if (!params().getLyXTextClass().load(filePath())) {
479                 string theclass = params().getLyXTextClass().name();
480                 Alert::error(_("Can't load document class"), bformat(
481                                      "Using the default document class, because the "
482                                      " class %1$s could not be loaded.", theclass));
483                 params().textclass = 0;
484         }
485
486         bool const res = text().read(*this, lex);
487         for_each(text().paragraphs().begin(),
488                  text().paragraphs().end(),
489                  bind(&Paragraph::setInsetOwner, _1, &inset()));
490         updateBibfilesCache();
491         return res;
492 }
493
494
495 // needed to insert the selection
496 void Buffer::insertStringAsLines(ParagraphList & pars,
497         pit_type & pit, pos_type & pos,
498         LyXFont const & fn, string const & str, bool autobreakrows)
499 {
500         LyXFont font = fn;
501
502         // insert the string, don't insert doublespace
503         bool space_inserted = true;
504         for (string::const_iterator cit = str.begin();
505             cit != str.end(); ++cit) {
506                 Paragraph & par = pars[pit];
507                 if (*cit == '\n') {
508                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
509                                 breakParagraph(params(), pars, pit, pos,
510                                                par.layout()->isEnvironment());
511                                 ++pit;
512                                 pos = 0;
513                                 space_inserted = true;
514                         } else {
515                                 continue;
516                         }
517                         // do not insert consecutive spaces if !free_spacing
518                 } else if ((*cit == ' ' || *cit == '\t') &&
519                            space_inserted && !par.isFreeSpacing()) {
520                         continue;
521                 } else if (*cit == '\t') {
522                         if (!par.isFreeSpacing()) {
523                                 // tabs are like spaces here
524                                 par.insertChar(pos, ' ', font);
525                                 ++pos;
526                                 space_inserted = true;
527                         } else {
528                                 const pos_type n = 8 - pos % 8;
529                                 for (pos_type i = 0; i < n; ++i) {
530                                         par.insertChar(pos, ' ', font);
531                                         ++pos;
532                                 }
533                                 space_inserted = true;
534                         }
535                 } else if (!isPrintable(*cit)) {
536                         // Ignore unprintables
537                         continue;
538                 } else {
539                         // just insert the character
540                         par.insertChar(pos, *cit, font);
541                         ++pos;
542                         space_inserted = (*cit == ' ');
543                 }
544
545         }
546 }
547
548
549 bool Buffer::readFile(string const & filename)
550 {
551         // Check if the file is compressed.
552         string const format = getFormatFromContents(filename);
553         if (format == "gzip" || format == "zip" || format == "compress") {
554                 params().compressed = true;
555         }
556
557         // remove dummy empty par
558         paragraphs().clear();
559         LyXLex lex(0, 0);
560         lex.setFile(filename);
561         bool ret = readFile(lex, filename);
562
563         // After we have read a file, we must ensure that the buffer
564         // language is set and used in the gui.
565         // If you know of a better place to put this, please tell me. (Lgb)
566         updateDocLang(params().language);
567
568         return ret;
569 }
570
571
572 bool Buffer::fully_loaded() const
573 {
574         return pimpl_->file_fully_loaded;
575 }
576
577
578 void Buffer::fully_loaded(bool const value)
579 {
580         pimpl_->file_fully_loaded = value;
581 }
582
583
584 bool Buffer::readFile(LyXLex & lex, string const & filename)
585 {
586         BOOST_ASSERT(!filename.empty());
587
588         if (!lex.isOK()) {
589                 Alert::error(_("Document could not be read"),
590                              bformat(_("%1$s could not be read."), filename));
591                 return false;
592         }
593
594         lex.next();
595         string const token(lex.getString());
596
597         if (!lex.isOK()) {
598                 Alert::error(_("Document could not be read"),
599                              bformat(_("%1$s could not be read."), filename));
600                 return false;
601         }
602
603         // the first token _must_ be...
604         if (token != "\\lyxformat") {
605                 lyxerr << "Token: " << token << endl;
606
607                 Alert::error(_("Document format failure"),
608                              bformat(_("%1$s is not a LyX document."),
609                                        filename));
610                 return false;
611         }
612
613         lex.next();
614         string tmp_format = lex.getString();
615         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
616         // if present remove ".," from string.
617         string::size_type dot = tmp_format.find_first_of(".,");
618         //lyxerr << "           dot found at " << dot << endl;
619         if (dot != string::npos)
620                         tmp_format.erase(dot, 1);
621         int const file_format = convert<int>(tmp_format);
622         //lyxerr << "format: " << file_format << endl;
623
624         if (file_format != LYX_FORMAT) {
625                 string const tmpfile = tempName();
626                 if (tmpfile.empty()) {
627                         Alert::error(_("Conversion failed"),
628                                      bformat(_("%1$s is from an earlier"
629                                               " version of LyX, but a temporary"
630                                               " file for converting it could"
631                                               " not be created."),
632                                               filename));
633                         return false;
634                 }
635                 string const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
636                 if (lyx2lyx.empty()) {
637                         Alert::error(_("Conversion script not found"),
638                                      bformat(_("%1$s is from an earlier"
639                                                " version of LyX, but the"
640                                                " conversion script lyx2lyx"
641                                                " could not be found."),
642                                                filename));
643                         return false;
644                 }
645                 ostringstream command;
646                 command << "python " << quoteName(lyx2lyx)
647                         << " -t " << convert<string>(LYX_FORMAT)
648                         << " -o " << quoteName(tmpfile) << ' '
649                         << quoteName(filename);
650                 string const command_str = command.str();
651
652                 lyxerr[Debug::INFO] << "Running '"
653                                     << command_str << '\''
654                                     << endl;
655
656                 cmd_ret const ret = runCommand(command_str);
657                 if (ret.first != 0) {
658                         Alert::error(_("Conversion script failed"),
659                                      bformat(_("%1$s is from an earlier version"
660                                               " of LyX, but the lyx2lyx script"
661                                               " failed to convert it."),
662                                               filename));
663                         return false;
664                 } else {
665                         bool const ret = readFile(tmpfile);
666                         // Do stuff with tmpfile name and buffer name here.
667                         return ret;
668                 }
669
670         }
671
672         if (readDocument(lex)) {
673                 Alert::error(_("Document format failure"),
674                              bformat(_("%1$s ended unexpectedly, which means"
675                                        " that it is probably corrupted."),
676                                        filename));
677         }
678
679         //lyxerr << "removing " << MacroTable::localMacros().size()
680         //      << " temporary macro entries" << endl;
681         //MacroTable::localMacros().clear();
682
683         pimpl_->file_fully_loaded = true;
684         return true;
685 }
686
687
688 // Should probably be moved to somewhere else: BufferView? LyXView?
689 bool Buffer::save() const
690 {
691         // We don't need autosaves in the immediate future. (Asger)
692         resetAutosaveTimers();
693
694         // make a backup
695         string s;
696         if (lyxrc.make_backup) {
697                 s = fileName() + '~';
698                 if (!lyxrc.backupdir_path.empty())
699                         s = addName(lyxrc.backupdir_path,
700                                     subst(os::internal_path(s),'/','!'));
701
702                 // It might very well be that this variant is just
703                 // good enough. (Lgb)
704                 // But to use this we need fs::copy_file to actually do a copy,
705                 // even when the target file exists. (Lgb)
706                 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
707                   //try {
708                     fs::copy_file(fileName(), s, false);
709                     //}
710                     //catch (fs::filesystem_error const & fe) {
711                     //lyxerr << "LyX was not able to make backup copy. Beware.\n"
712                     //     << fe.what() << endl;
713                     //}
714                 }
715         }
716
717         if (writeFile(fileName())) {
718                 markClean();
719                 removeAutosaveFile(fileName());
720         } else {
721                 // Saving failed, so backup is not backup
722                 if (lyxrc.make_backup)
723                         rename(s, fileName());
724                 return false;
725         }
726         return true;
727 }
728
729
730 bool Buffer::writeFile(string const & fname) const
731 {
732         if (pimpl_->read_only && fname == fileName())
733                 return false;
734
735         bool retval = false;
736
737         if (params().compressed) {
738                 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname));
739                 if (!ofs)
740                         return false;
741
742                 retval = do_writeFile(ofs);
743         } else {
744                 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
745                 if (!ofs)
746                         return false;
747
748                 retval = do_writeFile(ofs);
749         }
750
751         return retval;
752 }
753
754
755 bool Buffer::do_writeFile(ostream & ofs) const
756 {
757 #ifdef HAVE_LOCALE
758         // Use the standard "C" locale for file output.
759         ofs.imbue(std::locale::classic());
760 #endif
761
762         // The top of the file should not be written by params().
763
764         // write out a comment in the top of the file
765         ofs << "#LyX " << lyx_version
766             << " created this file. For more info see http://www.lyx.org/\n"
767             << "\\lyxformat " << LYX_FORMAT << "\n"
768             << "\\begin_document\n";
769
770         // now write out the buffer parameters.
771         ofs << "\\begin_header\n";
772         params().writeFile(ofs);
773         ofs << "\\end_header\n";
774
775         // write the text
776         ofs << "\n\\begin_body\n";
777         text().write(*this, ofs);
778         ofs << "\n\\end_body\n";
779
780         // Write marker that shows file is complete
781         ofs << "\\end_document" << endl;
782
783         // Shouldn't really be needed....
784         //ofs.close();
785
786         // how to check if close went ok?
787         // Following is an attempt... (BE 20001011)
788
789         // good() returns false if any error occured, including some
790         //        formatting error.
791         // bad()  returns true if something bad happened in the buffer,
792         //        which should include file system full errors.
793
794         bool status = true;
795         if (!ofs) {
796                 status = false;
797                 lyxerr << "File was not closed properly." << endl;
798         }
799
800         return status;
801 }
802
803
804 void Buffer::makeLaTeXFile(string const & fname,
805                            string const & original_path,
806                            OutputParams const & runparams,
807                            bool output_preamble, bool output_body)
808 {
809         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
810
811         ofstream ofs;
812         if (!openFileWrite(ofs, fname))
813                 return;
814
815         makeLaTeXFile(ofs, original_path,
816                       runparams, output_preamble, output_body);
817
818         ofs.close();
819         if (ofs.fail())
820                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
821 }
822
823
824 void Buffer::makeLaTeXFile(ostream & os,
825                            string const & original_path,
826                            OutputParams const & runparams_in,
827                            bool const output_preamble, bool const output_body)
828 {
829         OutputParams runparams = runparams_in;
830
831         // validate the buffer.
832         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
833         LaTeXFeatures features(*this, params(), runparams);
834         validate(features);
835         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
836
837         texrow().reset();
838
839         // The starting paragraph of the coming rows is the
840         // first paragraph of the document. (Asger)
841         texrow().start(paragraphs().begin()->id(), 0);
842
843         if (output_preamble && runparams.nice) {
844                 os << "%% LyX " << lyx_version << " created this file.  "
845                         "For more info, see http://www.lyx.org/.\n"
846                         "%% Do not edit unless you really know what "
847                         "you are doing.\n";
848                 texrow().newline();
849                 texrow().newline();
850         }
851         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
852         // There are a few differences between nice LaTeX and usual files:
853         // usual is \batchmode and has a
854         // special input@path to allow the including of figures
855         // with either \input or \includegraphics (what figinsets do).
856         // input@path is set when the actual parameter
857         // original_path is set. This is done for usual tex-file, but not
858         // for nice-latex-file. (Matthias 250696)
859         // Note that input@path is only needed for something the user does
860         // in the preamble, included .tex files or ERT, files included by
861         // LyX work without it.
862         if (output_preamble) {
863                 if (!runparams.nice) {
864                         // code for usual, NOT nice-latex-file
865                         os << "\\batchmode\n"; // changed
866                         // from \nonstopmode
867                         texrow().newline();
868                 }
869                 if (!original_path.empty()) {
870                         string const inputpath = latex_path(original_path);
871                         os << "\\makeatletter\n"
872                             << "\\def\\input@path{{"
873                             << inputpath << "/}}\n"
874                             << "\\makeatother\n";
875                         texrow().newline();
876                         texrow().newline();
877                         texrow().newline();
878                 }
879
880                 // Write the preamble
881                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
882
883                 if (!output_body)
884                         return;
885
886                 // make the body.
887                 os << "\\begin{document}\n";
888                 texrow().newline();
889         } // output_preamble
890         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
891
892         if (!lyxrc.language_auto_begin) {
893                 os << subst(lyxrc.language_command_begin, "$$lang",
894                              params().language->babel())
895                     << endl;
896                 texrow().newline();
897         }
898
899         // if we are doing a real file with body, even if this is the
900         // child of some other buffer, let's cut the link here.
901         // This happens for example if only a child document is printed.
902         string save_parentname;
903         if (output_preamble) {
904                 save_parentname = params().parentname;
905                 params().parentname.erase();
906         }
907
908         // the real stuff
909         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
910
911         // Restore the parenthood if needed
912         if (output_preamble)
913                 params().parentname = save_parentname;
914
915         // add this just in case after all the paragraphs
916         os << endl;
917         texrow().newline();
918
919         if (!lyxrc.language_auto_end) {
920                 os << subst(lyxrc.language_command_end, "$$lang",
921                              params().language->babel())
922                     << endl;
923                 texrow().newline();
924         }
925
926         if (output_preamble) {
927                 os << "\\end{document}\n";
928                 texrow().newline();
929
930                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
931         } else {
932                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
933                                      << endl;
934         }
935
936         // Just to be sure. (Asger)
937         texrow().newline();
938
939         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
940         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
941                             << '.' << endl;
942 }
943
944
945 bool Buffer::isLatex() const
946 {
947         return params().getLyXTextClass().outputType() == LATEX;
948 }
949
950
951 bool Buffer::isLinuxDoc() const
952 {
953         return params().getLyXTextClass().outputType() == LINUXDOC;
954 }
955
956
957 bool Buffer::isLiterate() const
958 {
959         return params().getLyXTextClass().outputType() == LITERATE;
960 }
961
962
963 bool Buffer::isDocBook() const
964 {
965         return params().getLyXTextClass().outputType() == DOCBOOK;
966 }
967
968
969 bool Buffer::isSGML() const
970 {
971         LyXTextClass const & tclass = params().getLyXTextClass();
972
973         return tclass.outputType() == LINUXDOC ||
974                tclass.outputType() == DOCBOOK;
975 }
976
977
978 void Buffer::makeLinuxDocFile(string const & fname,
979                               OutputParams const & runparams,
980                               bool const body_only)
981 {
982         ofstream ofs;
983         if (!openFileWrite(ofs, fname))
984                 return;
985
986         LaTeXFeatures features(*this, params(), runparams);
987         validate(features);
988
989         texrow().reset();
990
991         LyXTextClass const & tclass = params().getLyXTextClass();
992
993         string const & top_element = tclass.latexname();
994
995         if (!body_only) {
996                 ofs << tclass.class_header();
997
998                 string preamble = params().preamble;
999                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1000                          : fname;
1001                 preamble += features.getIncludedFiles(name);
1002                 preamble += features.getLyXSGMLEntities();
1003
1004                 if (!preamble.empty()) {
1005                         ofs << " [ " << preamble << " ]";
1006                 }
1007                 ofs << ">\n\n";
1008
1009                 if (params().options.empty())
1010                         sgml::openTag(ofs, top_element);
1011                 else {
1012                         string top = top_element;
1013                         top += ' ';
1014                         top += params().options;
1015                         sgml::openTag(ofs, top);
1016                 }
1017         }
1018
1019         ofs << "<!-- LyX "  << lyx_version
1020             << " created this file. For more info see http://www.lyx.org/"
1021             << " -->\n";
1022
1023         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1024
1025         if (!body_only) {
1026                 ofs << "\n\n";
1027                 sgml::closeTag(ofs, top_element);
1028         }
1029
1030         ofs.close();
1031         if (ofs.fail())
1032                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1033 }
1034
1035
1036 void Buffer::makeDocBookFile(string const & fname,
1037                              OutputParams const & runparams,
1038                              bool const only_body)
1039 {
1040         ofstream ofs;
1041         if (!openFileWrite(ofs, fname))
1042                 return;
1043
1044         LaTeXFeatures features(*this, params(), runparams);
1045         validate(features);
1046
1047         texrow().reset();
1048
1049         LyXTextClass const & tclass = params().getLyXTextClass();
1050         string const & top_element = tclass.latexname();
1051
1052         if (!only_body) {
1053                 if (runparams.flavor == OutputParams::XML)
1054                         ofs << "<?xml version=\"1.0\" encoding=\""
1055                             << params().language->encoding()->name() << "\"?>\n";
1056
1057                 ofs << "<!DOCTYPE " << top_element << " ";
1058
1059                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1060                 else if (runparams.flavor == OutputParams::XML)
1061                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1062                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1063                 else
1064                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1065
1066                 string preamble = params().preamble;
1067                 if (runparams.flavor != OutputParams::XML ) {
1068                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1069                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1070                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1071                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1072                 }
1073
1074                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1075                          : fname;
1076                 preamble += features.getIncludedFiles(name);
1077                 preamble += features.getLyXSGMLEntities();
1078
1079                 if (!preamble.empty()) {
1080                         ofs << "\n [ " << preamble << " ]";
1081                 }
1082                 ofs << ">\n\n";
1083         }
1084
1085         string top = top_element;
1086         top += " lang=\"";
1087         if (runparams.flavor == OutputParams::XML)
1088                 top += params().language->code();
1089         else
1090                 top += params().language->code().substr(0,2);
1091         top += '"';
1092
1093         if (!params().options.empty()) {
1094                 top += ' ';
1095                 top += params().options;
1096         }
1097
1098         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1099             << " file was created by LyX " << lyx_version
1100             << "\n  See http://www.lyx.org/ for more information -->\n";
1101
1102         params().getLyXTextClass().counters().reset();
1103
1104         sgml::openTag(ofs, top);
1105         ofs << '\n';
1106         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1107         sgml::closeTag(ofs, top_element);
1108
1109         ofs.close();
1110         if (ofs.fail())
1111                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1112 }
1113
1114
1115 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1116 // Other flags: -wall -v0 -x
1117 int Buffer::runChktex()
1118 {
1119         busy(true);
1120
1121         // get LaTeX-Filename
1122         string const name = getLatexName();
1123         string const path = temppath();
1124         string const org_path = filePath();
1125
1126         Path p(path); // path to LaTeX file
1127         message(_("Running chktex..."));
1128
1129         // Generate the LaTeX file if neccessary
1130         OutputParams runparams;
1131         runparams.flavor = OutputParams::LATEX;
1132         runparams.nice = false;
1133         makeLaTeXFile(name, org_path, runparams);
1134
1135         TeXErrors terr;
1136         Chktex chktex(lyxrc.chktex_command, name, filePath());
1137         int const res = chktex.run(terr); // run chktex
1138
1139         if (res == -1) {
1140                 Alert::error(_("chktex failure"),
1141                              _("Could not run chktex successfully."));
1142         } else if (res > 0) {
1143                 // Insert all errors as errors boxes
1144                 bufferErrors(*this, terr);
1145         }
1146
1147         busy(false);
1148
1149         return res;
1150 }
1151
1152
1153 void Buffer::validate(LaTeXFeatures & features) const
1154 {
1155         LyXTextClass const & tclass = params().getLyXTextClass();
1156
1157         if (features.isAvailable("dvipost") && params().tracking_changes
1158             && params().output_changes)
1159                 features.require("dvipost");
1160
1161         // AMS Style is at document level
1162         if (params().use_amsmath == BufferParams::AMS_ON
1163             || tclass.provides(LyXTextClass::amsmath))
1164                 features.require("amsmath");
1165
1166         for_each(paragraphs().begin(), paragraphs().end(),
1167                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1168
1169         // the bullet shapes are buffer level not paragraph level
1170         // so they are tested here
1171         for (int i = 0; i < 4; ++i) {
1172                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1173                         int const font = params().user_defined_bullet(i).getFont();
1174                         if (font == 0) {
1175                                 int const c = params()
1176                                         .user_defined_bullet(i)
1177                                         .getCharacter();
1178                                 if (c == 16
1179                                    || c == 17
1180                                    || c == 25
1181                                    || c == 26
1182                                    || c == 31) {
1183                                         features.require("latexsym");
1184                                 }
1185                         } else if (font == 1) {
1186                                 features.require("amssymb");
1187                         } else if ((font >= 2 && font <= 5)) {
1188                                 features.require("pifont");
1189                         }
1190                 }
1191         }
1192
1193         if (lyxerr.debugging(Debug::LATEX)) {
1194                 features.showStruct();
1195         }
1196 }
1197
1198
1199 void Buffer::getLabelList(vector<string> & list) const
1200 {
1201         /// if this is a child document and the parent is already loaded
1202         /// Use the parent's list instead  [ale990407]
1203         Buffer const * tmp = getMasterBuffer();
1204         if (!tmp) {
1205                 lyxerr << "getMasterBuffer() failed!" << endl;
1206                 BOOST_ASSERT(tmp);
1207         }
1208         if (tmp != this) {
1209                 tmp->getLabelList(list);
1210                 return;
1211         }
1212
1213         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1214                 it.nextInset()->getLabelList(*this, list);
1215 }
1216
1217
1218 // This is also a buffer property (ale)
1219 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1220         const
1221 {
1222         /// if this is a child document and the parent is already loaded
1223         /// use the parent's list instead  [ale990412]
1224         Buffer const * tmp = getMasterBuffer();
1225         BOOST_ASSERT(tmp);
1226         if (tmp != this) {
1227                 tmp->fillWithBibKeys(keys);
1228                 return;
1229         }
1230
1231         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1232                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1233                         InsetBibtex const & inset =
1234                                 dynamic_cast<InsetBibtex const &>(*it);
1235                         inset.fillWithBibKeys(*this, keys);
1236                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1237                         InsetInclude const & inset =
1238                                 dynamic_cast<InsetInclude const &>(*it);
1239                         inset.fillWithBibKeys(*this, keys);
1240                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1241                         InsetBibitem const & inset =
1242                                 dynamic_cast<InsetBibitem const &>(*it);
1243                         string const key = inset.getContents();
1244                         string const opt = inset.getOptions();
1245                         string const ref; // = pit->asString(this, false);
1246                         string const info = opt + "TheBibliographyRef" + ref;
1247                         keys.push_back(pair<string, string>(key, info));
1248                 }
1249         }
1250 }
1251
1252
1253 void Buffer::updateBibfilesCache()
1254 {
1255         // if this is a child document and the parent is already loaded
1256         // update the parent's cache instead
1257         Buffer * tmp = getMasterBuffer();
1258         BOOST_ASSERT(tmp);
1259         if (tmp != this) {
1260                 tmp->updateBibfilesCache();
1261                 return;
1262         }
1263
1264         bibfilesCache_.clear();
1265         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1266                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1267                         InsetBibtex const & inset =
1268                                 dynamic_cast<InsetBibtex const &>(*it);
1269                         vector<string> const bibfiles = inset.getFiles(*this);
1270                         bibfilesCache_.insert(bibfilesCache_.end(),
1271                                 bibfiles.begin(),
1272                                 bibfiles.end());
1273                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1274                         InsetInclude & inset =
1275                                 dynamic_cast<InsetInclude &>(*it);
1276                         inset.updateBibfilesCache(*this);
1277                         vector<string> const & bibfiles =
1278                                         inset.getBibfilesCache(*this);
1279                         bibfilesCache_.insert(bibfilesCache_.end(),
1280                                 bibfiles.begin(),
1281                                 bibfiles.end());
1282                 }
1283         }
1284 }
1285
1286
1287 vector<string> const & Buffer::getBibfilesCache() const
1288 {
1289         // if this is a child document and the parent is already loaded
1290         // use the parent's cache instead
1291         Buffer const * tmp = getMasterBuffer();
1292         BOOST_ASSERT(tmp);
1293         if (tmp != this)
1294                 return tmp->getBibfilesCache();
1295
1296         return bibfilesCache_;
1297 }
1298
1299
1300 bool Buffer::isDepClean(string const & name) const
1301 {
1302         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1303         if (it == pimpl_->dep_clean.end())
1304                 return true;
1305         return it->second;
1306 }
1307
1308
1309 void Buffer::markDepClean(string const & name)
1310 {
1311         pimpl_->dep_clean[name] = true;
1312 }
1313
1314
1315 bool Buffer::dispatch(string const & command, bool * result)
1316 {
1317         return dispatch(lyxaction.lookupFunc(command), result);
1318 }
1319
1320
1321 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1322 {
1323         bool dispatched = true;
1324
1325         switch (func.action) {
1326                 case LFUN_BUFFER_EXPORT: {
1327                         bool const tmp = Exporter::Export(this, func.argument, false);
1328                         if (result)
1329                                 *result = tmp;
1330                         break;
1331                 }
1332
1333                 default:
1334                         dispatched = false;
1335         }
1336         return dispatched;
1337 }
1338
1339
1340 void Buffer::changeLanguage(Language const * from, Language const * to)
1341 {
1342         BOOST_ASSERT(from);
1343         BOOST_ASSERT(to);
1344
1345         lyxerr << "Changing Language!" << endl;
1346
1347         // Take care of l10n/i18n
1348         updateDocLang(to);
1349
1350         for_each(par_iterator_begin(),
1351                  par_iterator_end(),
1352                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1353
1354         text().current_font.setLanguage(to);
1355         text().real_current_font.setLanguage(to);
1356 }
1357
1358
1359 void Buffer::updateDocLang(Language const * nlang)
1360 {
1361         BOOST_ASSERT(nlang);
1362
1363         pimpl_->messages.reset(new Messages(nlang->code()));
1364 }
1365
1366
1367 bool Buffer::isMultiLingual() const
1368 {
1369         ParConstIterator end = par_iterator_end();
1370         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1371                 if (it->isMultiLingual(params()))
1372                         return true;
1373
1374         return false;
1375 }
1376
1377
1378 ParIterator Buffer::getParFromID(int const id) const
1379 {
1380         ParConstIterator it = par_iterator_begin();
1381         ParConstIterator const end = par_iterator_end();
1382
1383         if (id < 0) {
1384                 // John says this is called with id == -1 from undo
1385                 lyxerr << "getParFromID(), id: " << id << endl;
1386                 return end;
1387         }
1388
1389         for (; it != end; ++it)
1390                 if (it->id() == id)
1391                         return it;
1392
1393         return end;
1394 }
1395
1396
1397 bool Buffer::hasParWithID(int const id) const
1398 {
1399         ParConstIterator const it = getParFromID(id);
1400         return it != par_iterator_end();
1401 }
1402
1403
1404 ParIterator Buffer::par_iterator_begin()
1405 {
1406         return ::par_iterator_begin(inset());
1407 }
1408
1409
1410 ParIterator Buffer::par_iterator_end()
1411 {
1412         return ::par_iterator_end(inset());
1413 }
1414
1415
1416 ParConstIterator Buffer::par_iterator_begin() const
1417 {
1418         return ::par_const_iterator_begin(inset());
1419 }
1420
1421
1422 ParConstIterator Buffer::par_iterator_end() const
1423 {
1424         return ::par_const_iterator_end(inset());
1425 }
1426
1427
1428 Language const * Buffer::getLanguage() const
1429 {
1430         return params().language;
1431 }
1432
1433
1434 string const Buffer::B_(string const & l10n) const
1435 {
1436         if (pimpl_->messages.get()) {
1437                 return pimpl_->messages->get(l10n);
1438         }
1439
1440         return _(l10n);
1441 }
1442
1443
1444 bool Buffer::isClean() const
1445 {
1446         return pimpl_->lyx_clean;
1447 }
1448
1449
1450 bool Buffer::isBakClean() const
1451 {
1452         return pimpl_->bak_clean;
1453 }
1454
1455
1456 void Buffer::markClean() const
1457 {
1458         if (!pimpl_->lyx_clean) {
1459                 pimpl_->lyx_clean = true;
1460                 updateTitles();
1461         }
1462         // if the .lyx file has been saved, we don't need an
1463         // autosave
1464         pimpl_->bak_clean = true;
1465 }
1466
1467
1468 void Buffer::markBakClean()
1469 {
1470         pimpl_->bak_clean = true;
1471 }
1472
1473
1474 void Buffer::setUnnamed(bool flag)
1475 {
1476         pimpl_->unnamed = flag;
1477 }
1478
1479
1480 bool Buffer::isUnnamed() const
1481 {
1482         return pimpl_->unnamed;
1483 }
1484
1485
1486 #ifdef WITH_WARNINGS
1487 #warning this function should be moved to buffer_pimpl.C
1488 #endif
1489 void Buffer::markDirty()
1490 {
1491         if (pimpl_->lyx_clean) {
1492                 pimpl_->lyx_clean = false;
1493                 updateTitles();
1494         }
1495         pimpl_->bak_clean = false;
1496
1497         DepClean::iterator it = pimpl_->dep_clean.begin();
1498         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1499
1500         for (; it != end; ++it) {
1501                 it->second = false;
1502         }
1503 }
1504
1505
1506 string const & Buffer::fileName() const
1507 {
1508         return pimpl_->filename;
1509 }
1510
1511
1512 string const & Buffer::filePath() const
1513 {
1514         return params().filepath;
1515 }
1516
1517
1518 bool Buffer::isReadonly() const
1519 {
1520         return pimpl_->read_only;
1521 }
1522
1523
1524 void Buffer::setParentName(string const & name)
1525 {
1526         params().parentname = name;
1527 }
1528
1529
1530 Buffer const * Buffer::getMasterBuffer() const
1531 {
1532         if (!params().parentname.empty()
1533             && bufferlist.exists(params().parentname)) {
1534                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1535                 if (buf)
1536                         return buf->getMasterBuffer();
1537         }
1538
1539         return this;
1540 }
1541
1542
1543 Buffer * Buffer::getMasterBuffer()
1544 {
1545         if (!params().parentname.empty()
1546             && bufferlist.exists(params().parentname)) {
1547                 Buffer * buf = bufferlist.getBuffer(params().parentname);
1548                 if (buf)
1549                         return buf->getMasterBuffer();
1550         }
1551
1552         return this;
1553 }
1554
1555
1556 MacroData const & Buffer::getMacro(std::string const & name) const
1557 {
1558         return pimpl_->macros.get(name);
1559 }
1560
1561
1562 bool Buffer::hasMacro(string const & name) const
1563 {
1564         return pimpl_->macros.has(name);
1565 }
1566
1567
1568 void Buffer::insertMacro(string const & name, MacroData const & data)
1569 {
1570         MacroTable::globalMacros().insert(name, data);
1571         pimpl_->macros.insert(name, data);
1572 }
1573
1574
1575 void Buffer::buildMacros()
1576 {
1577         // Start with global table.
1578         pimpl_->macros = MacroTable::globalMacros();
1579
1580         // Now add our own.
1581         ParagraphList const & pars = text().paragraphs();
1582         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1583                 //lyxerr << "searching main par " << i
1584                 //      << " for macro definitions" << std::endl;
1585                 InsetList const & insets = pars[i].insetlist;
1586                 InsetList::const_iterator it = insets.begin();
1587                 InsetList::const_iterator end = insets.end();
1588                 for ( ; it != end; ++it) {
1589                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1590                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1591                                 MathMacroTemplate const & mac
1592                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1593                                 insertMacro(mac.name(), mac.asMacroData());
1594                         }
1595                 }
1596         }
1597 }
1598
1599
1600 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1601 {
1602         cursor_ = cur;
1603         anchor_ = anc;
1604 }
1605
1606
1607 void Buffer::changeRefsIfUnique(string const & from, string const & to)
1608 {
1609         // Check if the label 'from' appears more than once
1610         vector<string> labels;
1611         getLabelList(labels);
1612
1613         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1614                 return;
1615
1616         InsetBase::Code code = InsetBase::REF_CODE;
1617
1618         ParIterator it = par_iterator_begin();
1619         ParIterator end = par_iterator_end();
1620         for ( ; it != end; ++it) {
1621                 bool changed_inset = false;
1622                 for (InsetList::iterator it2 = it->insetlist.begin();
1623                      it2 != it->insetlist.end(); ++it2) {
1624                         if (it2->inset->lyxCode() == code) {
1625                                 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1626                                 if (inset->getContents() == from) {
1627                                         inset->setContents(to);
1628                                         //inset->setButtonLabel();
1629                                         changed_inset = true;
1630                                 }
1631                         }
1632                 }
1633         }
1634 }
1635
1636
1637 void Buffer::getSourceCode(ostream & os, lyx::pit_type par_begin, lyx::pit_type par_end)
1638 {
1639         OutputParams runparams;
1640         runparams.nice = true;
1641         runparams.flavor = OutputParams::LATEX;
1642         runparams.linelen = lyxrc.ascii_linelen;
1643         runparams.par_begin = par_begin;
1644         runparams.par_end = par_end;
1645         // No side effect of file copying and image conversion
1646         runparams.dryrun = true;
1647
1648         if (par_begin + 1 == par_end)
1649                 os << "% Preview source code for paragraph " << par_begin << "\n\n";
1650         else
1651                 os << "% Preview source code from paragraph " << par_begin << " to " << par_end - 1 << "\n\n";
1652         // output paragraphs
1653         if (isLatex()) {
1654                 texrow().reset();
1655                 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1656         } else if (isLinuxDoc())
1657                 linuxdocParagraphs(*this, paragraphs(), os, runparams);
1658         else // DocBook
1659                 docbookParagraphs(paragraphs(), *this, os, runparams);
1660 }
1661