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
To create an Emacs function that selects a directory and depth level, then generates a string representation of the directory tree, you can use the following code. This function provides a basic indented list of the directory structure up to the specified depth.
(defun my-directory-tree (dir depth) "Generate a string representation of the directory tree starting at DIR up to DEPTH levels." (interactive (list (read-file-name "Select directory: " default-directory) (read-number "Depth level: " 0))) (let ((result (my--generate-tree dir depth 0))) (when (called-interactively-p 'interactive) (message "%s" result)) result)) (defun my--generate-tree (dir max-depth current-depth) "Helper function to recursively generate the tree string." (if (> current-depth max-depth) "" (let ((output (concat (my--indent current-depth) (file-name-nondirectory dir) "/\n"))) (when (< current-depth max-depth) (dolist (entry (my--get-entries dir)) (setq output (concat output (my--generate-tree entry max-depth (1+ current-depth)))))) output))) (defun my--get-entries (dir) "Return list of directory entries excluding . and .." (cl-remove-if (lambda (f) (or (string= (file-name-nondirectory f) ".") (string= (file-name-nondirectory f) ".."))) (directory-files dir t))) (defun my--indent (depth) "Generate indentation string based on depth." (make-string (* depth 4) ? ))Usage:
- Evaluate the code in Emacs.
- Call
M-x my-directory-treeto select a directory and depth. - The result will be displayed in the minibuffer.
Example Output: For a directory structure:
test/ ├── a/ │ └── 1.txt └── b/ └── 2.txtWith depth 2, the output will be:
test/ a/ 1.txt b/ 2.txtNote: This provides a basic indented list. For a tree-like structure with branches (├──, └──), a more complex implementation is required. The current version prioritizes clarity and simplicity.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.