]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Replace boost::shared_ptr<TextClass> with a global cache of sorts of the TextClass...
[lyx.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 "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BufferParams;
28 class EmbeddedFileList;
29 class DocIterator;
30 class ErrorItem;
31 class ErrorList;
32 class FuncRequest;
33 class Inset;
34 class Font;
35 class Format;
36 class Lexer;
37 class LyXRC;
38 class Text;
39 class LyXVC;
40 class LaTeXFeatures;
41 class Language;
42 class MacroData;
43 class MacroNameSet;
44 class OutputParams;
45 class Paragraph;
46 class ParConstIterator;
47 class ParIterator;
48 class ParagraphList;
49 class TeXErrors;
50 class TexRow;
51 class TocBackend;
52 class Undo;
53 class WordList;
54
55 namespace frontend {
56 class GuiBufferDelegate;
57 class WorkAreaManager;
58 }
59
60 namespace support {
61 class FileName;
62 }
63
64 /** The buffer object.
65  * This is the buffer object. It contains all the informations about
66  * a document loaded into LyX.
67  * The buffer object owns the Text (wrapped in an InsetText), which
68  * contains the individual paragraphs of the document.
69  *
70  *
71  * I am not sure if the class is complete or
72  * minimal, probably not.
73  * \author Lars Gullik Bjønnes
74  */
75 class Buffer {
76 public:
77         /// What type of log will \c getLogName() return?
78         enum LogType {
79                 latexlog, ///< LaTeX log
80                 buildlog  ///< Literate build log
81         };
82
83         /// Result of \c readFile()
84         enum ReadStatus {
85                 failure, ///< The file could not be read
86                 success, ///< The file could not be read
87                 wrongversion ///< The version of the file does not match ours
88         };
89
90
91         /// Method to check if a file is externally modified, used by 
92         /// isExternallyModified()
93         /**
94          * timestamp is fast but inaccurate. For example, the granularity
95          * of timestamp on a FAT filesystem is 2 second. Also, various operations
96          * may touch the timestamp of a file even when its content is unchanged.
97          *
98          * checksum is accurate but slow, which can be a problem when it is 
99          * frequently used, or used for a large file on a slow (network) file
100          * system.
101          *
102          * FIXME: replace this method with support/FileMonitor.
103          */
104         enum CheckMethod {
105                 checksum_method,  ///< Use file checksum
106                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
107         };
108         
109         /** Constructor
110             \param file
111             \param b  optional \c false by default
112         */
113         explicit Buffer(std::string const & file, bool b = false);
114
115         /// Destructor
116         ~Buffer();
117
118         /** High-level interface to buffer functionality.
119             This function parses a command string and executes it
120         */
121         bool dispatch(std::string const & command, bool * result = 0);
122
123         /// Maybe we know the function already by number...
124         bool dispatch(FuncRequest const & func, bool * result = 0);
125
126         /// Load the autosaved file.
127         void loadAutoSaveFile();
128
129         /// read a new document from a string
130         bool readString(std::string const &);
131         /// load a new file
132         bool readFile(support::FileName const & filename);
133
134         /// read the header, returns number of unknown tokens
135         int readHeader(Lexer & lex);
136
137         /** Reads a file without header.
138             \param par if != 0 insert the file.
139             \return \c false if file is not completely read.
140         */
141         bool readDocument(Lexer &);
142
143         ///
144         void insertStringAsLines(ParagraphList & plist,
145                 pit_type &, pos_type &,
146                 Font const &, docstring const &, bool);
147         ///
148         DocIterator getParFromID(int id) const;
149         /// do we have a paragraph with this id?
150         bool hasParWithID(int id) const;
151
152         ///
153         frontend::WorkAreaManager & workAreaManager() const;
154
155         /** Save file.
156             Takes care of auto-save files and backup file if requested.
157             Returns \c true if the save is successful, \c false otherwise.
158         */
159         bool save() const;
160
161         /// Write document to stream. Returns \c false if unsuccesful.
162         bool write(std::ostream &) const;
163         /// Write file. Returns \c false if unsuccesful.
164         bool writeFile(support::FileName const &) const;
165
166   /// Loads LyX file \c filename into buffer, *  and \return success 
167         bool loadLyXFile(support::FileName const & s);
168
169         /// Fill in the ErrorList with the TeXErrors
170         void bufferErrors(TeXErrors const &, ErrorList &) const;
171
172         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
173         bool makeLaTeXFile(support::FileName const & filename,
174                            std::string const & original_path,
175                            OutputParams const &,
176                            bool output_preamble = true,
177                            bool output_body = true) const;
178         /** Export the buffer to LaTeX.
179             If \p os is a file stream, and params().inputenc is "auto" or
180             "default", and the buffer contains text in different languages
181             with more than one encoding, then this method will change the
182             encoding associated to \p os. Therefore you must not call this
183             method with a string stream if the output is supposed to go to a
184             file. \code
185             odocfstream ofs;
186             ofs.open("test.tex");
187             writeLaTeXSource(ofs, ...);
188             ofs.close();
189             \endcode is NOT equivalent to \code
190             odocstringstream oss;
191             writeLaTeXSource(oss, ...);
192             odocfstream ofs;
193             ofs.open("test.tex");
194             ofs << oss.str();
195             ofs.close();
196             \endcode
197          */
198         void writeLaTeXSource(odocstream & os,
199                            std::string const & original_path,
200                            OutputParams const &,
201                            bool output_preamble = true,
202                            bool output_body = true) const;
203         ///
204         void makeDocBookFile(support::FileName const & filename,
205                              OutputParams const & runparams_in,
206                              bool only_body = false) const;
207         ///
208         void writeDocBookSource(odocstream & os, std::string const & filename,
209                              OutputParams const & runparams_in,
210                              bool only_body = false) const;
211         /// returns the main language for the buffer (document)
212         Language const * language() const;
213         /// get l10n translated to the buffers language
214         docstring const B_(std::string const & l10n) const;
215
216         ///
217         int runChktex();
218         /// return true if the main lyx file does not need saving
219         bool isClean() const;
220         ///
221         bool isBakClean() const;
222         ///
223         bool isDepClean(std::string const & name) const;
224
225         /// whether or not disk file has been externally modified
226         bool isExternallyModified(CheckMethod method) const;
227
228         /// save timestamp and checksum of the given file.
229         void saveCheckSum(support::FileName const & file) const;
230
231         /// mark the main lyx file as not needing saving
232         void markClean() const;
233
234         ///
235         void markBakClean() const;
236
237         ///
238         void markDepClean(std::string const & name);
239
240         ///
241         void setUnnamed(bool flag = true);
242
243         ///
244         bool isUnnamed() const;
245
246         /// Mark this buffer as dirty.
247         void markDirty();
248
249         /// Returns the buffer's filename. It is always an absolute path.
250         support::FileName fileName() const;
251
252         /// Returns the buffer's filename. It is always an absolute path.
253         std::string absFileName() const;
254
255         /// Returns the the path where the buffer lives.
256         /// It is always an absolute path.
257         std::string filePath() const;
258
259         /** A transformed version of the file name, adequate for LaTeX.
260             \param no_path optional if \c true then the path is stripped.
261         */
262         std::string latexName(bool no_path = true) const;
263
264         /// Get thee name and type of the log.
265         std::string logName(LogType * type = 0) const;
266
267         /// Change name of buffer. Updates "read-only" flag.
268         void setFileName(std::string const & newfile);
269
270         /// Set document's parent Buffer.
271         void setParent(Buffer const *);
272         Buffer const * parent();
273
274         /** Get the document's master (or \c this if this is not a
275             child document)
276          */
277         Buffer const * masterBuffer() const;
278
279         /// Is buffer read-only?
280         bool isReadonly() const;
281
282         /// Set buffer read-only flag
283         void setReadonly(bool flag = true);
284
285         /// returns \c true if the buffer contains a LaTeX document
286         bool isLatex() const;
287         /// returns \c true if the buffer contains a DocBook document
288         bool isDocBook() const;
289         /// returns \c true if the buffer contains a Wed document
290         bool isLiterate() const;
291
292         /** Validate a buffer for LaTeX.
293             This validates the buffer, and returns a struct for use by
294             #makeLaTeX# and others. Its main use is to figure out what
295             commands and packages need to be included in the LaTeX file.
296             It (should) also check that the needed constructs are there
297             (i.e. that the \refs points to coresponding \labels). It
298             should perhaps inset "error" insets to help the user correct
299             obvious mistakes.
300         */
301         void validate(LaTeXFeatures &) const;
302
303         /// Update the cache with all bibfiles in use (including bibfiles
304         /// of loaded child documents).
305         void updateBibfilesCache() const;
306         /// Return the cache with all bibfiles in use (including bibfiles
307         /// of loaded child documents).
308         EmbeddedFileList const & getBibfilesCache() const;
309         ///
310         void getLabelList(std::vector<docstring> &) const;
311
312         ///
313         void changeLanguage(Language const * from, Language const * to);
314
315         ///
316         bool isMultiLingual() const;
317
318         ///
319         BufferParams & params();
320         BufferParams const & params() const;
321
322         /** The list of paragraphs.
323             This is a linked list of paragraph, this list holds the
324             whole contents of the document.
325          */
326         ParagraphList & paragraphs();
327         ParagraphList const & paragraphs() const;
328
329         /// LyX version control object.
330         LyXVC & lyxvc();
331         LyXVC const & lyxvc() const;
332
333         /// Where to put temporary files.
334         std::string const temppath() const;
335
336         /// Used when typesetting to place errorboxes.
337         TexRow const & texrow() const;
338
339         ///
340         ParIterator par_iterator_begin();
341         ///
342         ParConstIterator par_iterator_begin() const;
343         ///
344         ParIterator par_iterator_end();
345         ///
346         ParConstIterator par_iterator_end() const;
347
348         /** \returns true only when the file is fully loaded.
349          *  Used to prevent the premature generation of previews
350          *  and by the citation inset.
351          */
352         bool isFullyLoaded() const;
353         /// Set by buffer_funcs' newFile.
354         void setFullyLoaded(bool);
355
356         /// Our main text (inside the top InsetText)
357         Text & text() const;
358
359         /// Our top InsetText
360         Inset & inset() const;
361
362         //
363         // Macro handling
364         //
365         /// Collect macro definitions in paragraphs
366         void updateMacros() const;
367         /// Iterate through the whole buffer and try to resolve macros
368         void updateMacroInstances() const;
369
370         /// List macro names of this buffer. the parent and the children
371         void listMacroNames(MacroNameSet & macros) const;
372         /// Write out all macros somewhere defined in the parent,
373         /// its parents and its children, which are visible at the beginning 
374         /// of this buffer
375         void writeParentMacros(odocstream & os) const;
376
377         /// Return macro defined before pos (or in the master buffer)
378         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
379         /// Return macro defined anywhere in the buffer (or in the master buffer)
380         MacroData const * getMacro(docstring const & name, bool global = true) const;
381         /// Return macro defined before the inclusion of the child
382         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
383
384         /// Replace the inset contents for insets which InsetCode is equal
385         /// to the passed \p inset_code.
386         void changeRefsIfUnique(docstring const & from, docstring const & to,
387                 InsetCode code);
388
389         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
390         /// including preamble
391         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
392                 bool full_source);
393
394         /// Access to error list.
395         /// This method is used only for GUI visualisation of Buffer related
396         /// errors (like parsing or LateX compilation). This method is const
397         /// because modifying the returned ErrorList does not touch the document
398         /// contents.
399         ErrorList & errorList(std::string const & type) const;
400
401         /// The Toc backend.
402         /// This is useful only for screen visualisation of the Buffer. This
403         /// method is const because modifying this backend does not touch
404         /// the document contents.
405         TocBackend & tocBackend() const;
406         
407         //@{
408         EmbeddedFileList & embeddedFiles();
409         EmbeddedFileList const & embeddedFiles() const;
410         bool embedded() const;
411         //@}
412
413         Undo & undo();
414        
415         /// This function is called when the buffer is changed.
416         void changed() const;
417         /// This function is called when the buffer structure is changed.
418         void structureChanged() const;
419         /// This function is called when some parsing error shows up.
420         void errors(std::string const & err) const;
421         /// This function is called when the buffer busy status change.
422         void setBusy(bool on) const;
423         /// This function is called when the buffer readonly status change.
424         void setReadOnly(bool on) const;
425         /// Update window titles of all users.
426         void updateTitles() const;
427         /// Reset autosave timers for all users.
428         void resetAutosaveTimers() const;
429         ///
430         void message(docstring const & msg) const;
431
432         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
433
434         ///
435         void autoSave() const;
436         ///
437         void loadChildDocuments() const;
438         ///
439         void resetChildDocuments(bool close_them) const;
440
441         /// return the format of the buffer on a string
442         std::string bufferFormat() const;
443
444         ///
445         bool doExport(std::string const & format, bool put_in_tempdir,
446                 std::string & result_file) const;
447         ///
448         bool doExport(std::string const & format, bool put_in_tempdir) const;
449         ///
450         bool preview(std::string const & format) const;
451         ///
452         bool isExportable(std::string const & format) const;
453         ///
454         std::vector<Format const *> exportableFormats(bool only_viewable) const;
455
456         /// Register word for completion word list.
457         void registerWord(docstring const & word);
458         ///
459         WordList const & registeredWords() const;
460         
461 private:
462         /// search for macro in local (buffer) table or in children
463         MacroData const * getBufferMacro(docstring const & name,
464                                          DocIterator const & pos) const;
465         /** Update macro table in the whole text inset
466             \param it at the start of the text inset)
467         */
468         void updateInsetMacros(DocIterator & it, 
469                                DocIterator & scope) const;
470         /** Update macro table for paragraphs until \c lastpit
471             \param it in some text inset
472             \param lastpit last processed paragraph
473         */
474         void updateEnvironmentMacros(DocIterator & it, 
475                                      pit_type lastpit, 
476                                      DocIterator & scope) const;
477         /** Update macro table for one paragraph block with 
478             same layout and depth, until \c lastpit
479             \param it in some text inset
480             \param lastpit last processed paragraph
481         */
482         void updateBlockMacros(DocIterator & it, 
483                                DocIterator & scope) const;
484
485         /// 
486         bool readFileHelper(support::FileName const & s);
487         ///
488         std::vector<std::string> backends() const;
489         /** Inserts a file into a document
490             \return \c false if method fails.
491         */
492         ReadStatus readFile(Lexer &, support::FileName const & filename,
493                             bool fromString = false);
494
495         /// Use the Pimpl idiom to hide the internals.
496         class Impl;
497         /// The pointer never changes although *pimpl_'s contents may.
498         Impl * const d;
499
500         frontend::GuiBufferDelegate * gui_;
501
502         /// This function is called when the buffer structure is changed.
503         Signal structureChanged_;
504         /// This function is called when some parsing error shows up.
505         //Signal errors(std::string const &) = 0;
506         /// This function is called when some message shows up.
507         //Signal message(docstring const &) = 0;
508         /// This function is called when the buffer busy status change.
509         //Signal setBusy(bool) = 0;
510         /// Reset autosave timers for all users.
511         Signal resetAutosaveTimers_;
512 };
513
514
515 } // namespace lyx
516
517 #endif