]> git.lyx.org Git - features.git/blob - src/Buffer.h
bf2a9ead6baf380f954f6f4575e2d8ad4abeb2a0
[features.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22
23 #include <map>
24 #include <list>
25 #include <set>
26 #include <string>
27 #include <vector>
28
29
30 namespace lyx {
31
32 class BiblioInfo;
33 class BibTeXInfo;
34 class BufferParams;
35 class DispatchResult;
36 class DocIterator;
37 class docstring_list;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetLabel;
43 class InsetRef;
44 class Font;
45 class Format;
46 class Lexer;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 namespace graphics {
76 class PreviewLoader;
77 }
78
79
80 class Buffer;
81 typedef std::list<Buffer *> ListOfBuffers;
82
83
84 /** The buffer object.
85  * This is the buffer object. It contains all the informations about
86  * a document loaded into LyX.
87  * The buffer object owns the Text (wrapped in an InsetText), which
88  * contains the individual paragraphs of the document.
89  *
90  *
91  * I am not sure if the class is complete or
92  * minimal, probably not.
93  * \author Lars Gullik Bjønnes
94  */
95 class Buffer {
96 public:
97         /// What type of log will \c getLogName() return?
98         enum LogType {
99                 latexlog, ///< LaTeX log
100                 buildlog  ///< Literate build log
101         };
102
103         /// Result of \c readFile()
104         enum ReadStatus {
105                 ReadSuccess,
106                 ReadCancel,
107                 // failures
108                 ReadFailure,
109                 ReadWrongVersion,
110                 ReadFileNotFound,
111                 ReadVCError,
112                 ReadAutosaveFailure,            
113                 ReadEmergencyFailure,
114                 ReadNoLyXFormat,
115                 ReadDocumentFailure,
116                 // lyx2lyx
117                 LyX2LyXNoTempFile,
118                 LyX2LyXNotFound,
119                 LyX2LyXOlderFormat,
120                 LyX2LyXNewerFormat,
121                 // other
122                 ReadOriginal
123         };
124
125         enum ExportStatus {
126                 // export
127                 ExportSuccess,
128                 ExportCancel,
129                 ExportError,
130                 ExportNoPathToFormat,
131                 ExportTexPathHasSpaces,
132                 ExportConverterError,
133                 // preview
134                 PreviewSuccess,
135                 PreviewError
136         };
137
138         /// Method to check if a file is externally modified, used by
139         /// isExternallyModified()
140         /**
141          * timestamp is fast but inaccurate. For example, the granularity
142          * of timestamp on a FAT filesystem is 2 second. Also, various operations
143          * may touch the timestamp of a file even when its content is unchanged.
144          *
145          * checksum is accurate but slow, which can be a problem when it is
146          * frequently used, or used for a large file on a slow (network) file
147          * system.
148          *
149          * FIXME: replace this method with support/FileMonitor.
150          */
151         enum CheckMethod {
152                 checksum_method, ///< Use file checksum
153                 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
154         };
155
156         ///
157         enum UpdateScope {
158                 UpdateMaster,
159                 UpdateChildOnly
160         };
161
162         /// Constructor
163         explicit Buffer(std::string const & file, bool readonly = false,
164                 Buffer const * cloned_buffer = 0);
165
166         /// Destructor
167         ~Buffer();
168
169         ///
170         Buffer * clone() const;
171         ///
172         bool isClone() const;
173
174         /** High-level interface to buffer functionality.
175             This function parses a command string and executes it.
176         */
177         void dispatch(std::string const & command, DispatchResult & result);
178
179         /// Maybe we know the function already by number...
180         void dispatch(FuncRequest const & func, DispatchResult & result);
181
182         /// Can this function be exectued?
183         /// \return true if we made a decision
184         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
185
186         ///
187         DocIterator getParFromID(int id) const;
188         /// do we have a paragraph with this id?
189         bool hasParWithID(int id) const;
190
191         ///
192         frontend::WorkAreaManager & workAreaManager() const;
193
194         /** Save file.
195             Takes care of auto-save files and backup file if requested.
196             Returns \c true if the save is successful, \c false otherwise.
197         */
198         bool save() const;
199         /// Renames and saves the buffer
200         bool saveAs(support::FileName const & fn);
201
202         /// Write document to stream. Returns \c false if unsuccessful.
203         bool write(std::ostream &) const;
204         /// Write file. Returns \c false if unsuccessful.
205         bool writeFile(support::FileName const &) const;
206
207         /// \name Functions involved in reading files/strings.
208         //@{
209         /// Loads the LyX file into the buffer. This function
210         /// tries to extract the file from version control if it
211         /// cannot be found. If it can be found, it will try to
212         /// read an emergency save file or an autosave file.
213         /// \sa loadThisLyXFile
214         ReadStatus loadLyXFile();
215         /// Loads the LyX file \c fn into the buffer. If you want
216         /// to check for files in a version control container,
217         /// emergency or autosave files, one should use \c loadLyXFile.
218         /// /sa loadLyXFile
219         ReadStatus loadThisLyXFile(support::FileName const & fn);
220         /// read a new document from a string
221         bool readString(std::string const &);
222         /// Reloads the LyX file
223         ReadStatus reload();
224 //FIXME: The following function should be private
225 //private:
226         /// read the header, returns number of unknown tokens
227         int readHeader(Lexer & lex);
228
229 private:
230         ///
231         typedef std::map<Buffer const *, Buffer *> BufferMap;
232         ///
233         void clone(BufferMap &) const;
234         /// save timestamp and checksum of the given file.
235         void saveCheckSum() const;      
236         /// read a new file
237         ReadStatus readFile(support::FileName const & fn);
238         /// Reads a file without header.
239         /// \param par if != 0 insert the file.
240         /// \return \c true if file is not completely read.
241         bool readDocument(Lexer &);
242         /// Try to extract the file from a version control container
243         /// before reading if the file cannot be found. This is only
244         /// implemented for RCS.
245         /// \sa LyXVC::file_not_found_hook
246         ReadStatus extractFromVC();
247         /// Reads the first tag of a LyX File and 
248         /// returns the file format number.
249         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
250                 int & file_format) const;
251         /// Convert the LyX file to the LYX_FORMAT using
252         /// the lyx2lyx script and returns the filename
253         /// of the temporary file to be read
254         ReadStatus convertLyXFormat(support::FileName const & fn, 
255                 support::FileName & tmpfile, int from_format);
256         //@}
257
258 public:
259         /// \name Functions involved in autosave and emergency files.
260         //@{
261         /// Save an autosave file to #filename.lyx#
262         bool autoSave() const;  
263         /// save emergency file
264         /// \return a status message towards the user.
265         docstring emergencyWrite();
266
267 //FIXME:The following function should be private
268 //private:
269         ///
270         void removeAutosaveFile() const;
271         
272 private:
273         /// Try to load an autosave file associated to \c fn.
274         ReadStatus loadAutosave();
275         /// Try to load an emergency file associated to \c fn. 
276         ReadStatus loadEmergency();
277         /// Get the filename of the emergency file associated with the Buffer
278         support::FileName getEmergencyFileName() const;
279         /// Get the filename of the autosave file associated with the Buffer
280         support::FileName getAutosaveFileName() const;
281         ///
282         void moveAutosaveFile(support::FileName const & old) const;
283         //@}
284
285 public:
286         /// Fill in the ErrorList with the TeXErrors
287         void bufferErrors(TeXErrors const &, ErrorList &) const;
288
289         enum OutputWhat {
290                 FullSource,
291                 OnlyBody,
292                 OnlyPreamble,
293                 CurrentParagraph
294         };
295
296         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
297         bool makeLaTeXFile(support::FileName const & filename,
298                            std::string const & original_path,
299                            OutputParams const &,
300                            OutputWhat output = FullSource) const;
301         /** Export the buffer to LaTeX.
302             If \p os is a file stream, and params().inputenc is "auto" or
303             "default", and the buffer contains text in different languages
304             with more than one encoding, then this method will change the
305             encoding associated to \p os. Therefore you must not call this
306             method with a string stream if the output is supposed to go to a
307             file. \code
308             ofdocstream ofs;
309             otexstream os(ofs, texrow);
310             ofs.open("test.tex");
311             writeLaTeXSource(os, ...);
312             ofs.close();
313             \endcode is NOT equivalent to \code
314             odocstringstream oss;
315             otexstream os(oss, texrow);
316             writeLaTeXSource(os, ...);
317             ofdocstream ofs;
318             ofs.open("test.tex");
319             ofs << oss.str();
320             ofs.close();
321             \endcode
322          */
323         void writeLaTeXSource(otexstream & os,
324                            std::string const & original_path,
325                            OutputParams const &,
326                            OutputWhat output = FullSource) const;
327         ///
328         void makeDocBookFile(support::FileName const & filename,
329                              OutputParams const & runparams_in,
330                              OutputWhat output = FullSource) const;
331         ///
332         void writeDocBookSource(odocstream & os, std::string const & filename,
333                              OutputParams const & runparams_in,
334                              OutputWhat output = FullSource) const;
335         ///
336         void makeLyXHTMLFile(support::FileName const & filename,
337                              OutputParams const & runparams_in) const;
338         ///
339         void writeLyXHTMLSource(odocstream & os,
340                              OutputParams const & runparams_in,
341                              OutputWhat output = FullSource) const;
342         /// returns the main language for the buffer (document)
343         Language const * language() const;
344         /// get l10n translated to the buffers language
345         docstring const B_(std::string const & l10n) const;
346
347         ///
348         int runChktex();
349         /// return true if the main lyx file does not need saving
350         bool isClean() const;
351         ///
352         bool isDepClean(std::string const & name) const;
353
354         /// whether or not disk file has been externally modified
355         bool isExternallyModified(CheckMethod method) const;
356
357         /// mark the main lyx file as not needing saving
358         void markClean() const;
359
360         ///
361         void markDepClean(std::string const & name);
362
363         ///
364         void setUnnamed(bool flag = true);
365
366         /// Whether or not a filename has been assigned to this buffer
367         bool isUnnamed() const;
368
369         /// Whether or not this buffer is internal.
370         ///
371         /// An internal buffer does not contain a real document, but some auxiliary text segment.
372         /// It is not associated with a filename, it is never saved, thus it does not need to be
373         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
374         bool isInternal() const;
375
376         /// Mark this buffer as dirty.
377         void markDirty();
378
379         /// Returns the buffer's filename. It is always an absolute path.
380         support::FileName fileName() const;
381
382         /// Returns the buffer's filename. It is always an absolute path.
383         std::string absFileName() const;
384
385         /// Returns the the path where the buffer lives.
386         /// It is always an absolute path.
387         std::string filePath() const;
388
389         /** A transformed version of the file name, adequate for LaTeX.
390             \param no_path optional if \c true then the path is stripped.
391         */
392         std::string latexName(bool no_path = true) const;
393
394         /// Get the name and type of the log.
395         std::string logName(LogType * type = 0) const;
396
397         /// Set document's parent Buffer.
398         void setParent(Buffer const *);
399         Buffer const * parent() const;
400
401         /** Get the document's master (or \c this if this is not a
402             child document)
403          */
404         Buffer const * masterBuffer() const;
405
406         /// \return true if \p child is a child of this \c Buffer.
407         bool isChild(Buffer * child) const;
408         
409         /// \return true if this \c Buffer has children
410         bool hasChildren() const;
411         
412         /// \return a list of the direct children of this Buffer.
413         /// this list has no duplicates and is in the order in which
414         /// the children appear.
415         ListOfBuffers getChildren() const;
416         
417         /// \return a list of all descendents of this Buffer (children,
418         /// grandchildren, etc). this list has no duplicates and is in
419         /// the order in which the children appear.
420         ListOfBuffers getDescendents() const;
421
422         /// Collect all relative buffers, in the order in which they appear.
423         /// I.e., the "root" Buffer is first, then its first child, then any
424         /// of its children, etc. However, there are no duplicates in this
425         /// list.
426         /// This is "stable", too, in the sense that it returns the same
427         /// thing from whichever Buffer it is called.
428         ListOfBuffers allRelatives() const;
429
430         /// Is buffer read-only?
431         bool isReadonly() const;
432
433         /// Set buffer read-only flag
434         void setReadonly(bool flag = true);
435
436         /** Validate a buffer for LaTeX.
437             This validates the buffer, and returns a struct for use by
438             #makeLaTeX# and others. Its main use is to figure out what
439             commands and packages need to be included in the LaTeX file.
440             It (should) also check that the needed constructs are there
441             (i.e. that the \refs points to coresponding \labels). It
442             should perhaps inset "error" insets to help the user correct
443             obvious mistakes.
444         */
445         void validate(LaTeXFeatures &) const;
446
447         /// Reference information is cached in the Buffer, so we do not
448         /// have to check or read things over and over. 
449         ///
450         /// There are two caches.
451         ///
452         /// One is a cache of the BibTeX files from which reference info is
453         /// being gathered. This cache is PER BUFFER, and the cache for the
454         /// master essentially includes the cache for its children. This gets
455         /// invalidated when an InsetBibtex is created, deleted, or modified.
456         /// 
457         /// The other is a cache of the reference information itself. This
458         /// exists only in the master buffer, and when it needs to be updated,
459         /// the children add their information to the master's cache.
460         
461         /// Calling this method invalidates the cache and so requires a
462         /// re-read.
463         void invalidateBibinfoCache() const;
464         /// This invalidates the cache of files we need to check.
465         void invalidateBibfileCache() const;
466         /// Updates the cached bibliography information, checking first to see
467         /// whether the cache is valid. If so, we do nothing. If not, then we
468         /// reload all the BibTeX info.
469         /// Note that this operates on the master document.
470         void reloadBibInfoCache() const;
471         /// \return the bibliography information for this buffer's master,
472         /// or just for it, if it isn't a child.
473         BiblioInfo const & masterBibInfo() const;
474         /// collect bibliography info from the various insets in this buffer.
475         void collectBibKeys() const;
476         /// add some BiblioInfo to our cache
477         void addBiblioInfo(BiblioInfo const & bi) const;
478         /// add a single piece of bibliography info to our cache
479         void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
480         ///
481         bool citeLabelsValid() const;
482         ///
483         void getLabelList(std::vector<docstring> &) const;
484
485         ///
486         void changeLanguage(Language const * from, Language const * to);
487
488         ///
489         bool isMultiLingual() const;
490         ///
491         std::set<Language const *> getLanguages() const;
492
493         ///
494         BufferParams & params();
495         BufferParams const & params() const;
496
497         /** The list of paragraphs.
498             This is a linked list of paragraph, this list holds the
499             whole contents of the document.
500          */
501         ParagraphList & paragraphs();
502         ParagraphList const & paragraphs() const;
503
504         /// LyX version control object.
505         LyXVC & lyxvc();
506         LyXVC const & lyxvc() const;
507
508         /// Where to put temporary files.
509         std::string const temppath() const;
510
511         /// Used when typesetting to place errorboxes.
512         TexRow const & texrow() const;
513         TexRow & texrow();
514
515         ///
516         ParIterator par_iterator_begin();
517         ///
518         ParConstIterator par_iterator_begin() const;
519         ///
520         ParIterator par_iterator_end();
521         ///
522         ParConstIterator par_iterator_end() const;
523
524         // Position of the child buffer where it appears first in the master.
525         DocIterator firstChildPosition(Buffer const * child);
526
527         /** \returns true only when the file is fully loaded.
528          *  Used to prevent the premature generation of previews
529          *  and by the citation inset.
530          */
531         bool isFullyLoaded() const;
532         /// Set by buffer_funcs' newFile.
533         void setFullyLoaded(bool);
534
535         /// FIXME: Needed by RenderPreview.
536         graphics::PreviewLoader * loader() const;
537         /// Update the LaTeX preview snippets associated with this buffer
538         void updatePreviews() const;
539         /// Remove any previewed LaTeX snippets associated with this buffer
540         void removePreviews() const;
541
542         /// Our main text (inside the top InsetText)
543         Text & text() const;
544
545         /// Our top InsetText
546         Inset & inset() const;
547
548         //
549         // Macro handling
550         //
551         /// Collect macro definitions in paragraphs
552         void updateMacros() const;
553         /// Iterate through the whole buffer and try to resolve macros
554         void updateMacroInstances(UpdateType) const;
555
556         /// List macro names of this buffer, the parent and the children
557         void listMacroNames(MacroNameSet & macros) const;
558         /// Collect macros of the parent and its children in front of this buffer.
559         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
560
561         /// Return macro defined before pos (or in the master buffer)
562         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
563         /// Return macro defined anywhere in the buffer (or in the master buffer)
564         MacroData const * getMacro(docstring const & name, bool global = true) const;
565         /// Return macro defined before the inclusion of the child
566         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
567
568         /// Collect user macro names at loading time
569         typedef std::set<docstring> UserMacroSet;
570         mutable UserMacroSet usermacros;
571
572         /// Replace the inset contents for insets which InsetCode is equal
573         /// to the passed \p inset_code.
574         void changeRefsIfUnique(docstring const & from, docstring const & to,
575                 InsetCode code);
576
577         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
578         /// including preamble
579         void getSourceCode(odocstream & os, std::string const format,
580                            pit_type par_begin, pit_type par_end, OutputWhat output) const;
581
582         /// Access to error list.
583         /// This method is used only for GUI visualisation of Buffer related
584         /// errors (like parsing or LateX compilation). This method is const
585         /// because modifying the returned ErrorList does not touch the document
586         /// contents.
587         ErrorList & errorList(std::string const & type) const;
588
589         /// The Toc backend.
590         /// This is useful only for screen visualisation of the Buffer. This
591         /// method is const because modifying this backend does not touch
592         /// the document contents.
593         TocBackend & tocBackend() const;
594
595         ///
596         Undo & undo();
597
598         /// This function is called when the buffer is changed.
599         void changed(bool update_metrics) const;
600         ///
601         void setChild(DocIterator const & dit, Buffer * child);
602         ///
603         void updateTocItem(std::string const &, DocIterator const &) const;
604         /// This function is called when the buffer structure is changed.
605         void structureChanged() const;
606         /// This function is called when some parsing error shows up.
607         void errors(std::string const & err, bool from_master = false) const;
608         /// This function is called when the buffer busy status change.
609         void setBusy(bool on) const;
610         /// Update window titles of all users.
611         void updateTitles() const;
612         /// Reset autosave timers for all users.
613         void resetAutosaveTimers() const;
614         ///
615         void message(docstring const & msg) const;
616
617         ///
618         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
619         ///
620         bool hasGuiDelegate() const;
621
622         ///
623         ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
624         ///
625         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
626                 std::string & result_file) const;
627         ///
628         ExportStatus preview(std::string const & format) const;
629
630 private:
631         /// target is a format name optionally followed by a space
632         /// and a destination file-name
633         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
634                 bool includeall, std::string & result_file) const;
635         ///
636         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
637                 bool includeall) const;
638         ///
639         ExportStatus preview(std::string const & format, bool includeall = false) const;
640
641 public:
642         ///
643         bool isExporting() const;
644
645         ///
646         typedef std::vector<std::pair<Inset *, ParIterator> > References;
647         References & references(docstring const & label);
648         References const & references(docstring const & label) const;
649         void clearReferenceCache() const;
650         void setInsetLabel(docstring const & label, InsetLabel const * il);
651         InsetLabel const * insetLabel(docstring const & label) const;
652
653         /// return a list of all used branches (also in children)
654         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
655
656         /// sets the buffer_ member for every inset in this buffer.
657         // FIXME This really shouldn't be needed, but at the moment it's not
658         // clear how to do it just for the individual pieces we need.
659         void setBuffersForInsets() const;
660         /// Updates screen labels and some other information associated with
661         /// insets and paragraphs. Actually, it's more like a general "recurse
662         /// through the Buffer" routine, that visits all the insets and paragraphs.
663         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
664         /// \param scope: whether to start with the master document or just
665         /// do this one.
666         /// \param output: whether we are preparing for output.
667         void updateBuffer(UpdateScope scope, UpdateType utype) const;
668         /// 
669         void updateBuffer(ParIterator & parit, UpdateType utype) const;
670
671         /// Spellcheck starting from \p from.
672         /// \p from initial position, will then points to the next misspelled
673         ///    word.
674         /// \p to will points to the end of the next misspelled word.
675         /// \p word_lang will contain the found misspelled word.
676         /// \return progress if a new word was found.
677         int spellCheck(DocIterator & from, DocIterator & to,
678                 WordLangTuple & word_lang, docstring_list & suggestions) const;
679         ///
680         void checkChildBuffers();
681
682 private:
683         class MarkAsExporting;
684         friend class MarkAsExporting;
685         /// mark the buffer as busy exporting something, or not
686         void setExportStatus(bool e) const;
687
688         /// Change name of buffer. Updates "read-only" flag.
689         void setFileName(support::FileName const & fname);
690         ///
691         void getLanguages(std::set<Language const *> &) const;
692         /// Checks whether any of the referenced bibfiles have changed since the
693         /// last time we loaded the cache. Note that this does NOT update the
694         /// cached information.
695         void checkIfBibInfoCacheIsValid() const;
696         /// Update the list of all bibfiles in use (including bibfiles
697         /// of loaded child documents).
698         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
699         /// Return the list with all bibfiles in use (including bibfiles
700         /// of loaded child documents).
701         support::FileNameList const & 
702                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
703         ///
704         void collectChildren(ListOfBuffers & children, bool grand_children) const;
705
706         /// noncopyable
707         Buffer(Buffer const &);
708         void operator=(Buffer const &);
709
710         /// Use the Pimpl idiom to hide the internals.
711         class Impl;
712         /// The pointer never changes although *pimpl_'s contents may.
713         Impl * const d;
714 };
715
716
717 } // namespace lyx
718
719 #endif