mistral-medium-2505· Mistral AI LMArena Human Preference 140K
emacs function that allos selection of a dir and a depth level and then creates a string…
- User
emacs function that allos selection of a dir and a depth level and then creates a string representatioan?
- Assistant
Emacs Function to Select Directory and Depth Level for String Representation
Here's an Emacs Lisp function that allows you to select a directory and specify a depth level, then creates a string representation of the directory structure:
(defun directory-to-string (dir depth) "Return a string representation of directory DIR up to DEPTH levels deep." (interactive "DDirectory: \nnDepth level: ") (let ((result "") (indent-level 0)) (labels ((process-dir (current-dir current-depth) (when (<= current-depth depth) (let* ((files (directory-files current-dir nil nil t)) (dirs (cl-remove-if-not (lambda (f) (file-directory-p (concat current-dir f))) files)) (non-dirs (cl-remove-if (lambda (f) (file-directory-p (concat current-dir f))) files))) (setq result (concat result (make-string (* 2 indent-level) ? ) (file-name-nondirectory (directory-file-name current-dir)) "/\n")) (setq indent-level (1+ indent-level)) (dolist (dir dirs) (process-dir (expand-file-name dir current-dir) (1+ current-depth))) (setq indent-level (1- indent-level)) (dolist (file non-dirs) (setq result (concat result (make-string (* 2 indent-level) ? ) file "\n")))))))) (process-dir (expand-file-name dir) 0) result)))How to Use This Function:
- Call the function with
M-x directory-to-string - It will prompt you for:
- A directory (you can use completion)
- A depth level (how many subdirectory levels to include)
Features:
- Shows directory structure with proper indentation
- Displays files within each directory
- Respects the depth limit you specify
- Returns a string that you can use elsewhere in Emacs
Example Output:
my-project/ src/ main.c utils/ helpers.c helpers.h docs/ README.mdAlternative Version (Simpler):
If you prefer a simpler version that just lists files without indentation:
(defun simple-directory-to-string (dir depth) "Return a simple string representation of directory DIR up to DEPTH levels deep." (interactive "DDirectory: \nnDepth level: ") (let ((result "")) (labels ((process-dir (current-dir current-depth) (when (<= current-depth depth) (dolist (file (directory-files current-dir nil nil t)) (let ((full-path (expand-file-name file current-dir))) (if (file-directory-p full-path) (progn (setq result (concat result file "/\n")) (process-dir full-path (1+ current-depth))) (setq result (concat result file "\n")))))))) (process-dir (expand-file-name dir) 0) result)))You can modify these functions to suit your specific needs, such as changing the formatting or adding more information to the output.
- Call the function with
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.