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