# Text Editor


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

``` python
from cachy import enable_cachy
```

``` python
enable_cachy()
```

``` python
if Path('test.txt').exists(): Path('test.txt').unlink()
```

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L12"
target="_blank" style="float:right; font-size:smaller">source</a>

### view

``` python

def view(
    path:str, view_range:tuple=None, nums:bool=False
):

```

*View directory or file contents with optional line range and numbers*

<details open class="code-fold">
<summary>Exported source</summary>

``` python
def view(path:str, view_range:tuple[int,int]=None, nums:bool=False):
    'View directory or file contents with optional line range and numbers'
    try:
        p = Path(path).expanduser().resolve()
        if not p.exists(): return f'Error: File not found: {p}'
        if p.is_dir():
            res = [str(f) for f in p.glob('**/*') 
                   if not any(part.startswith('.') for part in f.relative_to(p).parts)]
            return f'Directory contents of {p}:\n' + '\n'.join(res)
        
        lines = p.read_text().splitlines()
        s,e = 1,len(lines)
        if view_range:
            s,e = view_range
            if not (1 <= s <= len(lines)): return f'Error: Invalid start line {s}'
            if e != -1 and not (s <= e <= len(lines)): return f'Error: Invalid end line {e}'
            lines = lines[s-1:None if e==-1 else e]
            
        return '\n'.join([f'{i+s-1:6d} │ {l}' for i,l in enumerate(lines,1)] if nums else lines)
    except Exception as e: return f'Error viewing file: {str(e)}'
```

</details>

``` python
print(view('_quarto.yml', (1,10), nums=True))
```

         1 │ project:
         2 │   type: website
         3 │   resources: 
         4 │     - "*.txt"
         5 │   preview:
         6 │     port: 3000
         7 │     browser: false
         8 │ 
         9 │ format:
        10 │   html:

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L34"
target="_blank" style="float:right; font-size:smaller">source</a>

### create

``` python

def create(
    path:str, file_text:str, overwrite:bool=False
)->str:

```

*Creates a new file with the given content at the specified path*

<details open class="code-fold">
<summary>Exported source</summary>

``` python
def create(path: str, file_text: str, overwrite:bool=False) -> str:
    'Creates a new file with the given content at the specified path'
    try:
        p = Path(path)
        if p.exists():
            if not overwrite: return f'Error: File already exists: {p}'
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(file_text)
        return f'Created file {p} containing:\n{file_text}'
    except Exception as e: return f'Error creating file: {str(e)}'
```

</details>

``` python
print(create('test.txt', 'Hello, world!'))
print(view('test.txt', nums=True))
```

    Created file test.txt containing:
    Hello, world!
         1 │ Hello, world!

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L46"
target="_blank" style="float:right; font-size:smaller">source</a>

### insert

``` python

def insert(
    path:str, insert_line:int, new_str:str
)->str:

```

*Insert new_str at specified line number*

<details open class="code-fold">
<summary>Exported source</summary>

``` python
def insert(path: str, insert_line: int, new_str: str) -> str:
    'Insert new_str at specified line number'
    try:
        p = Path(path)
        if not p.exists(): return f'Error: File not found: {p}'
            
        content = p.read_text().splitlines()
        if not (0 <= insert_line <= len(content)): return f'Error: Invalid line number {insert_line}'
            
        content.insert(insert_line, new_str)
        new_content = '\n'.join(content)
        p.write_text(new_content)
        return f'Inserted text at line {insert_line} in {p}.\nNew contents:\n{new_content}'
    except Exception as e: return f'Error inserting text: {str(e)}'
```

</details>

``` python
insert('test.txt', 0, 'Let\'s add a new line')
print(view('test.txt', nums=True))
```

         1 │ Let's add a new line
         2 │ Hello, world!

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L62"
target="_blank" style="float:right; font-size:smaller">source</a>

### str_replace

``` python

def str_replace(
    path:str, old_str:str, new_str:str
)->str:

```

*Replace first occurrence of old_str with new_str in file*

<details open class="code-fold">
<summary>Exported source</summary>

``` python
def str_replace(path: str, old_str: str, new_str: str) -> str:
    'Replace first occurrence of old_str with new_str in file'
    try:
        p = Path(path)
        if not p.exists(): return f'Error: File not found: {p}'
            
        content = p.read_text()
        count = content.count(old_str)
        
        if count == 0: return 'Error: Text not found in file'
        if count > 1: return f'Error: Multiple matches found ({count})'
            
        new_content = content.replace(old_str, new_str, 1)
        p.write_text(new_content)
        return f'Replaced text in {p}.\nNew contents:\n{new_content}'
    except Exception as e: return f'Error replacing text: {str(e)}'
```

</details>

``` python
str_replace('test.txt', 'new line', '')
print(view('test.txt', nums=True))
```

         1 │ Let's add a 
         2 │ Hello, world!

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L90"
target="_blank" style="float:right; font-size:smaller">source</a>

### str_replace_based_edit_tool

``` python

def str_replace_based_edit_tool(
    kwargs:dict
)->str:

```

*Dispatcher for Anthropic Text Editor tool commands: view, str_replace,
create, insert.*

<details open class="code-fold">
<summary>Exported source</summary>

``` python
def str_replace_editor(**kwargs: dict[str, str]) -> str:
    'Dispatcher for Anthropic Text Editor tool commands: view, str_replace, create, insert, undo_edit.'
    cmd = kwargs.pop('command', '')
    if cmd == 'view': return view(**kwargs)
    elif cmd == 'str_replace': return str_replace(**kwargs) 
    elif cmd == 'create': return create(**kwargs)
    elif cmd == 'insert': return insert(**kwargs)
    elif cmd == 'undo_edit': return 'Undo edit is not supported yet.'
    else: return f'Unknown command: {cmd}'

def str_replace_based_edit_tool(**kwargs: dict[str, str]) -> str:
    'Dispatcher for Anthropic Text Editor tool commands: view, str_replace, create, insert.'
    return str_replace_editor(**kwargs)
```

</details>

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/claudette/blob/main/claudette/text_editor.py#L80"
target="_blank" style="float:right; font-size:smaller">source</a>

### str_replace_editor

``` python

def str_replace_editor(
    kwargs:dict
)->str:

```

*Dispatcher for Anthropic Text Editor tool commands: view, str_replace,
create, insert, undo_edit.*

``` python
model = models[1]
```

``` python
c = Chat(model, tools=[text_editor_conf['sonnet']], ns=mk_ns(str_replace_based_edit_tool))
# c.toolloop('Please explain what my _quarto.yml does. Use your tools')
```
