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