We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
media in sub/index.md gets invalid relative path
When creating a setup where the layout is:

```
sub/index.md
sub/image.png
```

and sub/index.md content is

```
![](image.png)
```

.. Then media url created is `../image.png`. 

Submitting a pull request to fix this.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mkdocs/utils.py`
Content:
```
1 # coding: utf-8
2 
3 """
4 Standalone file utils.
5 
6 Nothing in this module should have an knowledge of config or the layout
7 and structure of the site and pages in the site.
8 """
9 
10 import os
11 import shutil
12 
13 import markdown
14 import six
15 
16 from mkdocs import toc
17 
18 
19 def reduce_list(data_set):
20     """ Reduce duplicate items in a list and preserve order """
21     seen = set()
22     return [item for item in data_set if item not in seen and not seen.add(item)]
23 
24 
25 def copy_file(source_path, output_path):
26     """
27     Copy source_path to output_path, making sure any parent directories exist.
28     """
29     output_dir = os.path.dirname(output_path)
30     if not os.path.exists(output_dir):
31         os.makedirs(output_dir)
32     shutil.copy(source_path, output_path)
33 
34 
35 def write_file(content, output_path):
36     """
37     Write content to output_path, making sure any parent directories exist.
38     """
39     output_dir = os.path.dirname(output_path)
40     if not os.path.exists(output_dir):
41         os.makedirs(output_dir)
42     open(output_path, 'wb').write(content)
43 
44 
45 def clean_directory(directory):
46     """
47     Remove the content of a directory recursively but not the directory itself.
48     """
49     if not os.path.exists(directory):
50         return
51 
52     for entry in os.listdir(directory):
53 
54         # Don't remove hidden files from the directory. We never copy files
55         # that are hidden, so we shouldn't delete them either.
56         if entry.startswith('.'):
57             continue
58 
59         path = os.path.join(directory, entry)
60         if os.path.isdir(path):
61             shutil.rmtree(path, True)
62         else:
63             os.unlink(path)
64 
65 
66 def copy_media_files(from_dir, to_dir):
67     """
68     Recursively copy all files except markdown and HTML into another directory.
69     """
70     for (source_dir, dirnames, filenames) in os.walk(from_dir):
71         relative_path = os.path.relpath(source_dir, from_dir)
72         output_dir = os.path.normpath(os.path.join(to_dir, relative_path))
73 
74         # Filter filenames starting with a '.'
75         filenames = [f for f in filenames if not f.startswith('.')]
76 
77         # Filter the dirnames that start with a '.' and update the list in
78         # place to prevent us walking these.
79         dirnames[:] = [d for d in dirnames if not d.startswith('.')]
80 
81         for filename in filenames:
82             if not is_markdown_file(filename) and not is_html_file(filename):
83                 source_path = os.path.join(source_dir, filename)
84                 output_path = os.path.join(output_dir, filename)
85                 copy_file(source_path, output_path)
86 
87 
88 def get_html_path(path):
89     """
90     Map a source file path to an output html path.
91 
92     Paths like 'index.md' will be converted to 'index.html'
93     Paths like 'about.md' will be converted to 'about/index.html'
94     Paths like 'api-guide/core.md' will be converted to 'api-guide/core/index.html'
95     """
96     path = os.path.splitext(path)[0]
97     if os.path.basename(path) == 'index':
98         return path + '.html'
99     return "/".join((path, 'index.html'))
100 
101 
102 def get_url_path(path, use_directory_urls=True):
103     """
104     Map a source file path to an output html path.
105 
106     Paths like 'index.md' will be converted to '/'
107     Paths like 'about.md' will be converted to '/about/'
108     Paths like 'api-guide/core.md' will be converted to '/api-guide/core/'
109 
110     If `use_directory_urls` is `False`, returned URLs will include the a trailing
111     `index.html` rather than just returning the directory path.
112     """
113     path = get_html_path(path)
114     url = '/' + path.replace(os.path.sep, '/')
115     if use_directory_urls:
116         return url[:-len('index.html')]
117     return url
118 
119 
120 def is_homepage(path):
121     return os.path.splitext(path)[0] == 'index'
122 
123 
124 def is_markdown_file(path):
125     """
126     Return True if the given file path is a Markdown file.
127 
128     http://superuser.com/questions/249436/file-extension-for-markdown-files
129     """
130     ext = os.path.splitext(path)[1].lower()
131     return ext in [
132         '.markdown',
133         '.mdown',
134         '.mkdn',
135         '.mkd',
136         '.md',
137     ]
138 
139 
140 def is_css_file(path):
141     """
142     Return True if the given file path is a CSS file.
143     """
144     ext = os.path.splitext(path)[1].lower()
145     return ext in [
146         '.css',
147     ]
148 
149 
150 def is_javascript_file(path):
151     """
152     Return True if the given file path is a Javascript file.
153     """
154     ext = os.path.splitext(path)[1].lower()
155     return ext in [
156         '.js',
157         '.javascript'
158     ]
159 
160 
161 def is_html_file(path):
162     """
163     Return True if the given file path is an HTML file.
164     """
165     ext = os.path.splitext(path)[1].lower()
166     return ext in [
167         '.html',
168         '.htm',
169     ]
170 
171 
172 def is_template_file(path):
173     """
174     Return True if the given file path is an HTML file.
175     """
176     ext = os.path.splitext(path)[1].lower()
177     return ext in [
178         '.html',
179         '.htm',
180         '.xml',
181     ]
182 
183 
184 def create_media_urls(nav, path_list):
185     """
186     Return a list of URLs that have been processed correctly for inclusion in
187     a page.
188     """
189     final_urls = []
190 
191     for path in path_list:
192         # Allow links to fully qualified URL's
193         parsed = six.moves.urllib.parse.urlparse(path)
194         if parsed.netloc:
195             final_urls.append(path)
196             continue
197         # We must be looking at a local path.
198         url = path_to_url(path)
199         relative_url = '%s/%s' % (nav.url_context.make_relative('/'), url)
200         final_urls.append(relative_url)
201 
202     return final_urls
203 
204 
205 def create_relative_media_url(nav, url):
206     """
207     For a current page, create a relative url based on the given URL.
208 
209     On index.md (which becomes /index.html):
210         image.png -> ./image.png
211         /image.png -> ./image.png
212 
213     on sub/page.md (which becomes /sub/page/index.html):
214         image.png -> ../image.png
215         /image.png -> ../../image.png
216 
217     """
218 
219     # Allow links to fully qualified URL's
220     parsed = six.moves.urllib.parse.urlparse(url)
221     if parsed.netloc:
222         return url
223 
224     # If the URL we are looking at starts with a /, then it should be
225     # considered as absolute and will be 'relative' to the root.
226     if url.startswith('/'):
227         base = '/'
228         url = url[1:]
229     else:
230         base = nav.url_context.base_path
231 
232     relative_url = '%s/%s' % (nav.url_context.make_relative(base), url)
233 
234     # TODO: Fix this, this is a hack. Relative urls are not being calculated
235     # correctly for images in the same directory as the markdown. I think this
236     # is due to us moving it into a directory with index.html, but I'm not sure
237     if nav.url_context.base_path is not '/' and relative_url.startswith("./"):
238         relative_url = ".%s" % relative_url
239 
240     return relative_url
241 
242 
243 def path_to_url(path):
244     """Convert a system path to a URL."""
245 
246     if os.path.sep == '/':
247         return path
248 
249     return six.moves.urllib.request.pathname2url(path)
250 
251 
252 def convert_markdown(markdown_source, extensions=None, extension_configs=None):
253     """
254     Convert the Markdown source file to HTML content, and additionally
255     return the parsed table of contents, and a dictionary of any metadata
256     that was specified in the Markdown file.
257     `extensions` is an optional sequence of Python Markdown extensions to add
258     to the default set.
259     """
260     md = markdown.Markdown(
261         extensions=extensions or [],
262         extension_configs=extension_configs or {}
263     )
264     html_content = md.convert(markdown_source)
265 
266     # On completely blank markdown files, no Meta or tox properties are added
267     # to the generated document.
268     meta = getattr(md, 'Meta', {})
269     toc_html = getattr(md, 'toc', '')
270 
271     # Post process the generated table of contents into a data structure
272     table_of_contents = toc.TableOfContents(toc_html)
273 
274     return (html_content, table_of_contents, meta)
275 
276 
277 def get_theme_names():
278     """Return a list containing all the names of all the builtin themes."""
279 
280     return os.listdir(os.path.join(os.path.dirname(__file__), 'themes'))
281 
282 
283 def filename_to_title(filename):
284 
285     title = os.path.splitext(filename)[0]
286     title = title.replace('-', ' ').replace('_', ' ')
287     # Capitalize if the filename was all lowercase, otherwise leave it as-is.
288     if title.lower() == title:
289         title = title.capitalize()
290 
291     return title
292 
293 
294 def find_or_create_node(branch, key):
295     """
296     Given a list, look for dictionary with a key matching key and return it's
297     value. If it doesn't exist, create it with the value of an empty list and
298     return that.
299     """
300 
301     for node in branch:
302         if not isinstance(node, dict):
303             continue
304 
305         if key in node:
306             return node[key]
307 
308     new_branch = []
309     node = {key: new_branch}
310     branch.append(node)
311     return new_branch
312 
313 
314 def nest_paths(paths):
315     """
316     Given a list of paths, convert them into a nested structure that will match
317     the pages config.
318     """
319     nested = []
320 
321     for path in paths:
322 
323         if os.path.sep not in path:
324             nested.append(path)
325             continue
326 
327         directory, _ = os.path.split(path)
328         parts = directory.split(os.path.sep)
329 
330         branch = nested
331         for part in parts:
332             part = filename_to_title(part)
333             branch = find_or_create_node(branch, part)
334 
335         branch.append(path)
336 
337     return nested
338
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mkdocs/utils.py b/mkdocs/utils.py
--- a/mkdocs/utils.py
+++ b/mkdocs/utils.py
@@ -210,10 +210,14 @@
         image.png -> ./image.png
         /image.png -> ./image.png
 
-    on sub/page.md (which becomes /sub/page/index.html):
+    On sub/page.md (which becomes /sub/page/index.html):
         image.png -> ../image.png
         /image.png -> ../../image.png
 
+    On sub/index.md (which becomes /sub/index.html):
+        image.png -> ./image.png
+        /image.png -> ./image.png
+
     """
 
     # Allow links to fully qualified URL's
@@ -229,12 +233,18 @@
     else:
         base = nav.url_context.base_path
 
-    relative_url = '%s/%s' % (nav.url_context.make_relative(base), url)
+    relative_base = nav.url_context.make_relative(base)
+    if relative_base == "." and url.startswith("./"):
+        relative_url = url
+    else:
+        relative_url = '%s/%s' % (relative_base, url)
 
     # TODO: Fix this, this is a hack. Relative urls are not being calculated
     # correctly for images in the same directory as the markdown. I think this
     # is due to us moving it into a directory with index.html, but I'm not sure
-    if nav.url_context.base_path is not '/' and relative_url.startswith("./"):
+    if (nav.file_context.current_file.endswith("/index.md") is False
+            and nav.url_context.base_path is not '/'
+            and relative_url.startswith("./")):
         relative_url = ".%s" % relative_url
 
     return relative_url

{"golden_diff": "diff --git a/mkdocs/utils.py b/mkdocs/utils.py\n--- a/mkdocs/utils.py\n+++ b/mkdocs/utils.py\n@@ -210,10 +210,14 @@\n         image.png -> ./image.png\n         /image.png -> ./image.png\n \n-    on sub/page.md (which becomes /sub/page/index.html):\n+    On sub/page.md (which becomes /sub/page/index.html):\n         image.png -> ../image.png\n         /image.png -> ../../image.png\n \n+    On sub/index.md (which becomes /sub/index.html):\n+        image.png -> ./image.png\n+        /image.png -> ./image.png\n+\n     \"\"\"\n \n     # Allow links to fully qualified URL's\n@@ -229,12 +233,18 @@\n     else:\n         base = nav.url_context.base_path\n \n-    relative_url = '%s/%s' % (nav.url_context.make_relative(base), url)\n+    relative_base = nav.url_context.make_relative(base)\n+    if relative_base == \".\" and url.startswith(\"./\"):\n+        relative_url = url\n+    else:\n+        relative_url = '%s/%s' % (relative_base, url)\n \n     # TODO: Fix this, this is a hack. Relative urls are not being calculated\n     # correctly for images in the same directory as the markdown. I think this\n     # is due to us moving it into a directory with index.html, but I'm not sure\n-    if nav.url_context.base_path is not '/' and relative_url.startswith(\"./\"):\n+    if (nav.file_context.current_file.endswith(\"/index.md\") is False\n+            and nav.url_context.base_path is not '/'\n+            and relative_url.startswith(\"./\")):\n         relative_url = \".%s\" % relative_url\n \n     return relative_url\n", "issue": "media in sub/index.md gets invalid relative path\nWhen creating a setup where the layout is:\n\n```\nsub/index.md\nsub/image.png\n```\n\nand sub/index.md content is\n\n```\n![](image.png)\n```\n\n.. Then media url created is `../image.png`. \n\nSubmitting a pull request to fix this.\n\n", "before_files": [{"content": "# coding: utf-8\n\n\"\"\"\nStandalone file utils.\n\nNothing in this module should have an knowledge of config or the layout\nand structure of the site and pages in the site.\n\"\"\"\n\nimport os\nimport shutil\n\nimport markdown\nimport six\n\nfrom mkdocs import toc\n\n\ndef reduce_list(data_set):\n    \"\"\" Reduce duplicate items in a list and preserve order \"\"\"\n    seen = set()\n    return [item for item in data_set if item not in seen and not seen.add(item)]\n\n\ndef copy_file(source_path, output_path):\n    \"\"\"\n    Copy source_path to output_path, making sure any parent directories exist.\n    \"\"\"\n    output_dir = os.path.dirname(output_path)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    shutil.copy(source_path, output_path)\n\n\ndef write_file(content, output_path):\n    \"\"\"\n    Write content to output_path, making sure any parent directories exist.\n    \"\"\"\n    output_dir = os.path.dirname(output_path)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    open(output_path, 'wb').write(content)\n\n\ndef clean_directory(directory):\n    \"\"\"\n    Remove the content of a directory recursively but not the directory itself.\n    \"\"\"\n    if not os.path.exists(directory):\n        return\n\n    for entry in os.listdir(directory):\n\n        # Don't remove hidden files from the directory. We never copy files\n        # that are hidden, so we shouldn't delete them either.\n        if entry.startswith('.'):\n            continue\n\n        path = os.path.join(directory, entry)\n        if os.path.isdir(path):\n            shutil.rmtree(path, True)\n        else:\n            os.unlink(path)\n\n\ndef copy_media_files(from_dir, to_dir):\n    \"\"\"\n    Recursively copy all files except markdown and HTML into another directory.\n    \"\"\"\n    for (source_dir, dirnames, filenames) in os.walk(from_dir):\n        relative_path = os.path.relpath(source_dir, from_dir)\n        output_dir = os.path.normpath(os.path.join(to_dir, relative_path))\n\n        # Filter filenames starting with a '.'\n        filenames = [f for f in filenames if not f.startswith('.')]\n\n        # Filter the dirnames that start with a '.' and update the list in\n        # place to prevent us walking these.\n        dirnames[:] = [d for d in dirnames if not d.startswith('.')]\n\n        for filename in filenames:\n            if not is_markdown_file(filename) and not is_html_file(filename):\n                source_path = os.path.join(source_dir, filename)\n                output_path = os.path.join(output_dir, filename)\n                copy_file(source_path, output_path)\n\n\ndef get_html_path(path):\n    \"\"\"\n    Map a source file path to an output html path.\n\n    Paths like 'index.md' will be converted to 'index.html'\n    Paths like 'about.md' will be converted to 'about/index.html'\n    Paths like 'api-guide/core.md' will be converted to 'api-guide/core/index.html'\n    \"\"\"\n    path = os.path.splitext(path)[0]\n    if os.path.basename(path) == 'index':\n        return path + '.html'\n    return \"/\".join((path, 'index.html'))\n\n\ndef get_url_path(path, use_directory_urls=True):\n    \"\"\"\n    Map a source file path to an output html path.\n\n    Paths like 'index.md' will be converted to '/'\n    Paths like 'about.md' will be converted to '/about/'\n    Paths like 'api-guide/core.md' will be converted to '/api-guide/core/'\n\n    If `use_directory_urls` is `False`, returned URLs will include the a trailing\n    `index.html` rather than just returning the directory path.\n    \"\"\"\n    path = get_html_path(path)\n    url = '/' + path.replace(os.path.sep, '/')\n    if use_directory_urls:\n        return url[:-len('index.html')]\n    return url\n\n\ndef is_homepage(path):\n    return os.path.splitext(path)[0] == 'index'\n\n\ndef is_markdown_file(path):\n    \"\"\"\n    Return True if the given file path is a Markdown file.\n\n    http://superuser.com/questions/249436/file-extension-for-markdown-files\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.markdown',\n        '.mdown',\n        '.mkdn',\n        '.mkd',\n        '.md',\n    ]\n\n\ndef is_css_file(path):\n    \"\"\"\n    Return True if the given file path is a CSS file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.css',\n    ]\n\n\ndef is_javascript_file(path):\n    \"\"\"\n    Return True if the given file path is a Javascript file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.js',\n        '.javascript'\n    ]\n\n\ndef is_html_file(path):\n    \"\"\"\n    Return True if the given file path is an HTML file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.html',\n        '.htm',\n    ]\n\n\ndef is_template_file(path):\n    \"\"\"\n    Return True if the given file path is an HTML file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.html',\n        '.htm',\n        '.xml',\n    ]\n\n\ndef create_media_urls(nav, path_list):\n    \"\"\"\n    Return a list of URLs that have been processed correctly for inclusion in\n    a page.\n    \"\"\"\n    final_urls = []\n\n    for path in path_list:\n        # Allow links to fully qualified URL's\n        parsed = six.moves.urllib.parse.urlparse(path)\n        if parsed.netloc:\n            final_urls.append(path)\n            continue\n        # We must be looking at a local path.\n        url = path_to_url(path)\n        relative_url = '%s/%s' % (nav.url_context.make_relative('/'), url)\n        final_urls.append(relative_url)\n\n    return final_urls\n\n\ndef create_relative_media_url(nav, url):\n    \"\"\"\n    For a current page, create a relative url based on the given URL.\n\n    On index.md (which becomes /index.html):\n        image.png -> ./image.png\n        /image.png -> ./image.png\n\n    on sub/page.md (which becomes /sub/page/index.html):\n        image.png -> ../image.png\n        /image.png -> ../../image.png\n\n    \"\"\"\n\n    # Allow links to fully qualified URL's\n    parsed = six.moves.urllib.parse.urlparse(url)\n    if parsed.netloc:\n        return url\n\n    # If the URL we are looking at starts with a /, then it should be\n    # considered as absolute and will be 'relative' to the root.\n    if url.startswith('/'):\n        base = '/'\n        url = url[1:]\n    else:\n        base = nav.url_context.base_path\n\n    relative_url = '%s/%s' % (nav.url_context.make_relative(base), url)\n\n    # TODO: Fix this, this is a hack. Relative urls are not being calculated\n    # correctly for images in the same directory as the markdown. I think this\n    # is due to us moving it into a directory with index.html, but I'm not sure\n    if nav.url_context.base_path is not '/' and relative_url.startswith(\"./\"):\n        relative_url = \".%s\" % relative_url\n\n    return relative_url\n\n\ndef path_to_url(path):\n    \"\"\"Convert a system path to a URL.\"\"\"\n\n    if os.path.sep == '/':\n        return path\n\n    return six.moves.urllib.request.pathname2url(path)\n\n\ndef convert_markdown(markdown_source, extensions=None, extension_configs=None):\n    \"\"\"\n    Convert the Markdown source file to HTML content, and additionally\n    return the parsed table of contents, and a dictionary of any metadata\n    that was specified in the Markdown file.\n    `extensions` is an optional sequence of Python Markdown extensions to add\n    to the default set.\n    \"\"\"\n    md = markdown.Markdown(\n        extensions=extensions or [],\n        extension_configs=extension_configs or {}\n    )\n    html_content = md.convert(markdown_source)\n\n    # On completely blank markdown files, no Meta or tox properties are added\n    # to the generated document.\n    meta = getattr(md, 'Meta', {})\n    toc_html = getattr(md, 'toc', '')\n\n    # Post process the generated table of contents into a data structure\n    table_of_contents = toc.TableOfContents(toc_html)\n\n    return (html_content, table_of_contents, meta)\n\n\ndef get_theme_names():\n    \"\"\"Return a list containing all the names of all the builtin themes.\"\"\"\n\n    return os.listdir(os.path.join(os.path.dirname(__file__), 'themes'))\n\n\ndef filename_to_title(filename):\n\n    title = os.path.splitext(filename)[0]\n    title = title.replace('-', ' ').replace('_', ' ')\n    # Capitalize if the filename was all lowercase, otherwise leave it as-is.\n    if title.lower() == title:\n        title = title.capitalize()\n\n    return title\n\n\ndef find_or_create_node(branch, key):\n    \"\"\"\n    Given a list, look for dictionary with a key matching key and return it's\n    value. If it doesn't exist, create it with the value of an empty list and\n    return that.\n    \"\"\"\n\n    for node in branch:\n        if not isinstance(node, dict):\n            continue\n\n        if key in node:\n            return node[key]\n\n    new_branch = []\n    node = {key: new_branch}\n    branch.append(node)\n    return new_branch\n\n\ndef nest_paths(paths):\n    \"\"\"\n    Given a list of paths, convert them into a nested structure that will match\n    the pages config.\n    \"\"\"\n    nested = []\n\n    for path in paths:\n\n        if os.path.sep not in path:\n            nested.append(path)\n            continue\n\n        directory, _ = os.path.split(path)\n        parts = directory.split(os.path.sep)\n\n        branch = nested\n        for part in parts:\n            part = filename_to_title(part)\n            branch = find_or_create_node(branch, part)\n\n        branch.append(path)\n\n    return nested\n", "path": "mkdocs/utils.py"}], "after_files": [{"content": "# coding: utf-8\n\n\"\"\"\nStandalone file utils.\n\nNothing in this module should have an knowledge of config or the layout\nand structure of the site and pages in the site.\n\"\"\"\n\nimport os\nimport shutil\n\nimport markdown\nimport six\n\nfrom mkdocs import toc\n\n\ndef reduce_list(data_set):\n    \"\"\" Reduce duplicate items in a list and preserve order \"\"\"\n    seen = set()\n    return [item for item in data_set if item not in seen and not seen.add(item)]\n\n\ndef copy_file(source_path, output_path):\n    \"\"\"\n    Copy source_path to output_path, making sure any parent directories exist.\n    \"\"\"\n    output_dir = os.path.dirname(output_path)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    shutil.copy(source_path, output_path)\n\n\ndef write_file(content, output_path):\n    \"\"\"\n    Write content to output_path, making sure any parent directories exist.\n    \"\"\"\n    output_dir = os.path.dirname(output_path)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    open(output_path, 'wb').write(content)\n\n\ndef clean_directory(directory):\n    \"\"\"\n    Remove the content of a directory recursively but not the directory itself.\n    \"\"\"\n    if not os.path.exists(directory):\n        return\n\n    for entry in os.listdir(directory):\n\n        # Don't remove hidden files from the directory. We never copy files\n        # that are hidden, so we shouldn't delete them either.\n        if entry.startswith('.'):\n            continue\n\n        path = os.path.join(directory, entry)\n        if os.path.isdir(path):\n            shutil.rmtree(path, True)\n        else:\n            os.unlink(path)\n\n\ndef copy_media_files(from_dir, to_dir):\n    \"\"\"\n    Recursively copy all files except markdown and HTML into another directory.\n    \"\"\"\n    for (source_dir, dirnames, filenames) in os.walk(from_dir):\n        relative_path = os.path.relpath(source_dir, from_dir)\n        output_dir = os.path.normpath(os.path.join(to_dir, relative_path))\n\n        # Filter filenames starting with a '.'\n        filenames = [f for f in filenames if not f.startswith('.')]\n\n        # Filter the dirnames that start with a '.' and update the list in\n        # place to prevent us walking these.\n        dirnames[:] = [d for d in dirnames if not d.startswith('.')]\n\n        for filename in filenames:\n            if not is_markdown_file(filename) and not is_html_file(filename):\n                source_path = os.path.join(source_dir, filename)\n                output_path = os.path.join(output_dir, filename)\n                copy_file(source_path, output_path)\n\n\ndef get_html_path(path):\n    \"\"\"\n    Map a source file path to an output html path.\n\n    Paths like 'index.md' will be converted to 'index.html'\n    Paths like 'about.md' will be converted to 'about/index.html'\n    Paths like 'api-guide/core.md' will be converted to 'api-guide/core/index.html'\n    \"\"\"\n    path = os.path.splitext(path)[0]\n    if os.path.basename(path) == 'index':\n        return path + '.html'\n    return \"/\".join((path, 'index.html'))\n\n\ndef get_url_path(path, use_directory_urls=True):\n    \"\"\"\n    Map a source file path to an output html path.\n\n    Paths like 'index.md' will be converted to '/'\n    Paths like 'about.md' will be converted to '/about/'\n    Paths like 'api-guide/core.md' will be converted to '/api-guide/core/'\n\n    If `use_directory_urls` is `False`, returned URLs will include the a trailing\n    `index.html` rather than just returning the directory path.\n    \"\"\"\n    path = get_html_path(path)\n    url = '/' + path.replace(os.path.sep, '/')\n    if use_directory_urls:\n        return url[:-len('index.html')]\n    return url\n\n\ndef is_homepage(path):\n    return os.path.splitext(path)[0] == 'index'\n\n\ndef is_markdown_file(path):\n    \"\"\"\n    Return True if the given file path is a Markdown file.\n\n    http://superuser.com/questions/249436/file-extension-for-markdown-files\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.markdown',\n        '.mdown',\n        '.mkdn',\n        '.mkd',\n        '.md',\n    ]\n\n\ndef is_css_file(path):\n    \"\"\"\n    Return True if the given file path is a CSS file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.css',\n    ]\n\n\ndef is_javascript_file(path):\n    \"\"\"\n    Return True if the given file path is a Javascript file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.js',\n        '.javascript'\n    ]\n\n\ndef is_html_file(path):\n    \"\"\"\n    Return True if the given file path is an HTML file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.html',\n        '.htm',\n    ]\n\n\ndef is_template_file(path):\n    \"\"\"\n    Return True if the given file path is an HTML file.\n    \"\"\"\n    ext = os.path.splitext(path)[1].lower()\n    return ext in [\n        '.html',\n        '.htm',\n        '.xml',\n    ]\n\n\ndef create_media_urls(nav, path_list):\n    \"\"\"\n    Return a list of URLs that have been processed correctly for inclusion in\n    a page.\n    \"\"\"\n    final_urls = []\n\n    for path in path_list:\n        # Allow links to fully qualified URL's\n        parsed = six.moves.urllib.parse.urlparse(path)\n        if parsed.netloc:\n            final_urls.append(path)\n            continue\n        # We must be looking at a local path.\n        url = path_to_url(path)\n        relative_url = '%s/%s' % (nav.url_context.make_relative('/'), url)\n        final_urls.append(relative_url)\n\n    return final_urls\n\n\ndef create_relative_media_url(nav, url):\n    \"\"\"\n    For a current page, create a relative url based on the given URL.\n\n    On index.md (which becomes /index.html):\n        image.png -> ./image.png\n        /image.png -> ./image.png\n\n    On sub/page.md (which becomes /sub/page/index.html):\n        image.png -> ../image.png\n        /image.png -> ../../image.png\n\n    On sub/index.md (which becomes /sub/index.html):\n        image.png -> ./image.png\n        /image.png -> ./image.png\n\n    \"\"\"\n\n    # Allow links to fully qualified URL's\n    parsed = six.moves.urllib.parse.urlparse(url)\n    if parsed.netloc:\n        return url\n\n    # If the URL we are looking at starts with a /, then it should be\n    # considered as absolute and will be 'relative' to the root.\n    if url.startswith('/'):\n        base = '/'\n        url = url[1:]\n    else:\n        base = nav.url_context.base_path\n\n    relative_base = nav.url_context.make_relative(base)\n    if relative_base == \".\" and url.startswith(\"./\"):\n        relative_url = url\n    else:\n        relative_url = '%s/%s' % (relative_base, url)\n\n    # TODO: Fix this, this is a hack. Relative urls are not being calculated\n    # correctly for images in the same directory as the markdown. I think this\n    # is due to us moving it into a directory with index.html, but I'm not sure\n    if (nav.file_context.current_file.endswith(\"/index.md\") is False\n            and nav.url_context.base_path is not '/'\n            and relative_url.startswith(\"./\")):\n        relative_url = \".%s\" % relative_url\n\n    return relative_url\n\n\ndef path_to_url(path):\n    \"\"\"Convert a system path to a URL.\"\"\"\n\n    if os.path.sep == '/':\n        return path\n\n    return six.moves.urllib.request.pathname2url(path)\n\n\ndef convert_markdown(markdown_source, extensions=None, extension_configs=None):\n    \"\"\"\n    Convert the Markdown source file to HTML content, and additionally\n    return the parsed table of contents, and a dictionary of any metadata\n    that was specified in the Markdown file.\n    `extensions` is an optional sequence of Python Markdown extensions to add\n    to the default set.\n    \"\"\"\n    md = markdown.Markdown(\n        extensions=extensions or [],\n        extension_configs=extension_configs or {}\n    )\n    html_content = md.convert(markdown_source)\n\n    # On completely blank markdown files, no Meta or tox properties are added\n    # to the generated document.\n    meta = getattr(md, 'Meta', {})\n    toc_html = getattr(md, 'toc', '')\n\n    # Post process the generated table of contents into a data structure\n    table_of_contents = toc.TableOfContents(toc_html)\n\n    return (html_content, table_of_contents, meta)\n\n\ndef get_theme_names():\n    \"\"\"Return a list containing all the names of all the builtin themes.\"\"\"\n\n    return os.listdir(os.path.join(os.path.dirname(__file__), 'themes'))\n\n\ndef filename_to_title(filename):\n\n    title = os.path.splitext(filename)[0]\n    title = title.replace('-', ' ').replace('_', ' ')\n    # Capitalize if the filename was all lowercase, otherwise leave it as-is.\n    if title.lower() == title:\n        title = title.capitalize()\n\n    return title\n\n\ndef find_or_create_node(branch, key):\n    \"\"\"\n    Given a list, look for dictionary with a key matching key and return it's\n    value. If it doesn't exist, create it with the value of an empty list and\n    return that.\n    \"\"\"\n\n    for node in branch:\n        if not isinstance(node, dict):\n            continue\n\n        if key in node:\n            return node[key]\n\n    new_branch = []\n    node = {key: new_branch}\n    branch.append(node)\n    return new_branch\n\n\ndef nest_paths(paths):\n    \"\"\"\n    Given a list of paths, convert them into a nested structure that will match\n    the pages config.\n    \"\"\"\n    nested = []\n\n    for path in paths:\n\n        if os.path.sep not in path:\n            nested.append(path)\n            continue\n\n        directory, _ = os.path.split(path)\n        parts = directory.split(os.path.sep)\n\n        branch = nested\n        for part in parts:\n            part = filename_to_title(part)\n            branch = find_or_create_node(branch, part)\n\n        branch.append(path)\n\n    return nested\n", "path": "mkdocs/utils.py"}]}