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