The best way I can think of is to update these numbers immediately
before exporting or before evaluating.
This is the function that goes through the buffer. You can bind it to
a key, or add it to a hook. The following code updates the lines
whenever you save the file, but if your use case is different, just
find out which hook you need! (org-mode is full of hooks)
(add-hook 'before-save-hook #'endless/update-includes)
(defun endless/update-includes (&rest ignore)
"Update the line numbers of all #+INCLUDE:s in current buffer.
Only looks at INCLUDEs that already have a line number listed!
This function does nothing if not in org-mode, so you can safely
add it to `before-save-hook'."
(when (derived-mode-p 'org-mode)
"^\\s-*#\\+INCLUDE: *\"\\([^\"]+\\)\".*:lines *\"\\([-0-9]+\\)\""
(let* ((file (expand-file-name (match-string-no-properties 1)))
(lines (endless/decide-line-range file)))
(replace-match lines :fixedcase :literal nil 2)))))))
This is where you define the regexps which will be used as the first
and last lines to be included. You can give a list of regexps for
each file extension.
'(("sv" ("^class\\b" . "^endclass\\b") ("^enum\\b" . "^endenum\\b")))
"Alist of regexps to use for each file extension.
Each item should be
(EXTENSION (REGEXP-BEGIN . REGEXP-END) (REGEXP-BEGIN . REGEXP-END))
See `endless/decide-line-range' for more information."
:type '(repeat (cons string (repeat (cons regexp regexp)))))
The background worker
This is the guy that does most of the work.
(defun endless/decide-line-range (file)
"Visit FILE and decide which lines to include.
The FILE's extension is used to get a list of cons cells from
`endless/extension-regexp-map'. Each cons cell is a pair of
regexps, which determine the beginning and end of region to be
included. The first one which matches is used."
(let ((regexps (cdr-safe (assoc (file-name-extension file)
it l r)
(setq it (pop regexps))
(when (search-forward-regexp (car it) nil 'noerror)
(setq l (line-number-at-pos (match-beginning 0)))
(when (search-forward-regexp (cdr it) nil 'noerror)
(setq regexps nil
r (line-number-at-pos (match-end 0))))))
(when r (format "%s-%s" l (+ r 1))))))))