### Create and Use SourceKitten SyntaxMap Source: https://context7.com/jpsim/sourcekitten/llms.txt Illustrates creating a SyntaxMap from a file to get syntax token information, and also how to create one directly from a list of tokens. Useful for syntax highlighting or analysis. ```swift import SourceKittenFramework // Create syntax map from file if let file = File(path: "/path/to/source.swift") { do { let syntaxMap = try SyntaxMap(file: file) // Iterate through tokens for token in syntaxMap.tokens { print("Token: \(token.type)") print(" Offset: \(token.offset)") print(" Length: \(token.length)") } // Get JSON representation print(syntaxMap.description) } catch { print("Failed to parse syntax: \(error)") } } // Create from tokens directly let tokens = [ SyntaxToken(type: "source.lang.swift.syntaxtype.keyword", offset: ByteCount(0), length: ByteCount(6)), SyntaxToken(type: "source.lang.swift.syntaxtype.identifier", offset: ByteCount(7), length: ByteCount(10)) ] let customSyntaxMap = SyntaxMap(tokens: tokens) ``` -------------------------------- ### Get Code Completion Options Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Use `sourcekitten complete` with `--file` or `--text` to get code completion suggestions for a given offset. The output is a JSON array of completion options. ```json [ { "descriptionKey" : "advancedBy(n: Distance)", "associatedUSRs" : "s:FSi10advancedByFSiFSiSi s:FPSs21RandomAccessIndexType10advancedByuRq_S__Fq_Fqq_Ss16ForwardIndexType8Distanceq_ s:FPSs16ForwardIndexType10advancedByuRq_S__Fq_Fqq_S_8Distanceq_ s:FPSs10Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_ s:FPSs11_Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_", "kind" : "source.lang.swift.decl.function.method.instance", "sourcetext" : "advancedBy(<#T##n: Distance##Distance#>)", "context" : "source.codecompletion.context.thisclass", "typeName" : "Int", "moduleName" : "Swift", "name" : "advancedBy(n: Distance)" }, { "descriptionKey" : "advancedBy(n: Self.Distance, limit: Self)", "associatedUSRs" : "s:FeRq_Ss21RandomAccessIndexType_SsS_10advancedByuRq_S__Fq_FTqq_Ss16ForwardIndexType8Distance5limitq__q_", "kind" : "source.lang.swift.decl.function.method.instance", "sourcetext" : "advancedBy(<#T##n: Self.Distance##Self.Distance#>, limit: <#T##Self#>)", "context" : "source.codecompletion.context.superclass", "typeName" : "Self", "moduleName" : "Swift", "name" : "advancedBy(n: Self.Distance, limit: Self)" }, ... ] ``` -------------------------------- ### Bazel Installation for SourceKitten Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Add this to your Bazel WORKSPACE file to include SourceKitten. Ensure SOURCEKITTEN_VERSION and SOURCEKITTEN_SHA are updated. ```python SOURCEKITTEN_VERSION = "SOME_VERSION" SOURCEKITTEN_SHA = "SOME_SHA" http_archive( name = "com_github_jpsim_sourcekitten", url = "https://github.com/jpsim/SourceKitten/archive/refs/tags/%s.tar.gz" % (SOURCEKITTEN_VERSION), sha256 = SOURCEKITTEN_SHA, strip_prefix = "SourceKitten-%s" % SOURCEKITTEN_VERSION ) ``` -------------------------------- ### Get Swift Syntax Highlighting Information Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Use `sourcekitten syntax` with `--file` or `--text` to receive a JSON array detailing the syntax types and their offsets/lengths within the code. ```json [ { "offset" : 0, "length" : 6, "type" : "source.lang.swift.syntaxtype.keyword" }, { "offset" : 7, "length" : 10, "type" : "source.lang.swift.syntaxtype.identifier" }, { "offset" : 18, "length" : 14, "type" : "source.lang.swift.syntaxtype.comment" } ] ``` -------------------------------- ### Get module information Source: https://context7.com/jpsim/sourcekitten/llms.txt Retrieve declarations and interface information for system or custom Swift modules. ```bash sourcekitten module-info --module Foundation -- -sdk $(xcrun --show-sdk-path) ``` ```bash sourcekitten module-info --module MyFramework -- -F /path/to/frameworks -sdk $(xcrun --show-sdk-path) ``` -------------------------------- ### SourceKitten Command Line Help Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Displays the overview, usage, options, and subcommands available for the SourceKitten command line tool. Use 'sourcekitten help ' for detailed help. ```bash $ sourcekitten help OVERVIEW: An adorable little command line tool for interacting with SourceKit USAGE: sourcekitten OPTIONS: --version Show the version. -h, --help Show help information. SUBCOMMANDS: complete Generate code completion options doc Print Swift or Objective-C docs as JSON format Format Swift file index Index Swift file and print as JSON module-info Obtain information about a Swift module and print as JSON request Run a raw SourceKit request structure Print Swift structure information as JSON syntax Print Swift syntax information as JSON version Display the current version of SourceKitten See 'sourcekitten help ' for detailed help. ``` -------------------------------- ### Create and Format SourceKitten File Source: https://context7.com/jpsim/sourcekitten/llms.txt Demonstrates creating a File object from a path, accessing its contents and lines, formatting the code, and clearing caches. Use this for file-based operations. ```swift import SourceKittenFramework // Create from file path if let file = File(path: "/path/to/source.swift") { print("Contents length: \(file.contents.count)") print("Number of lines: \(file.lines.count)") // Access string view for byte-based operations let stringView = file.stringView // Format the file let formatted = try file.format( trimmingTrailingWhitespace: true, useTabs: false, indentWidth: 4 ) print(formatted) // Clear cached data to free memory file.clearCaches() } // Create from file path with deferred reading let deferredFile = File(pathDeferringReading: "/path/to/large/file.swift") // Contents are read on first access // Create from inline contents let inlineFile = File(contents: """ struct User { var name: String var age: Int } """) ``` -------------------------------- ### Generate Documentation with xcodebuild Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Use `sourcekitten doc` to pass arguments to `xcodebuild` for generating documentation. This can be done for workspaces, schemes, or single files. ```bash sourcekitten doc -- -workspace SourceKitten.xcworkspace -scheme SourceKittenFramework ``` ```bash sourcekitten doc --single-file file.swift -- -j4 file.swift ``` ```bash sourcekitten doc --module-name Alamofire -- -project Alamofire.xcodeproj ``` ```bash sourcekitten doc -- -workspace Haneke.xcworkspace -scheme Haneke ``` ```bash sourcekitten doc --objc Realm/Realm.h -- -x objective-c -isysroot $(xcrun --show-sdk-path) -I $(pwd) ``` -------------------------------- ### Execute SourceKit Requests Source: https://context7.com/jpsim/sourcekitten/llms.txt Demonstrates various SourceKit request types including code completion, cursor info, indexing, editor operations, and asynchronous execution. ```swift import SourceKittenFramework // Code completion request let completionRequest = Request.codeCompletionRequest( file: "/path/to/file.swift", contents: "import Foundation\nNSDate().", offset: ByteCount(27), arguments: ["-sdk", sdkPath(), "-target", "arm64-apple-macosx13.0"] ) do { let response = try completionRequest.send() let items = CodeCompletionItem.parse(response: response) for item in items { print("Completion: \(item.name ?? "") - \(item.typeName ?? "")") } } catch { print("Request failed: \(error)") } // Cursor info request let cursorRequest = Request.cursorInfo( file: "/path/to/file.swift", offset: ByteCount(100), arguments: ["-sdk", sdkPath(), "/path/to/file.swift"] ) if let cursorInfo = try? cursorRequest.send() { let name = cursorInfo["key.name"] as? String let usr = cursorInfo["key.usr"] as? String let typeName = cursorInfo["key.typename"] as? String print("Symbol: \(name ?? ""), USR: \(usr ?? ""), Type: \(typeName ?? "")") } // Index request let indexRequest = Request.index( file: "/path/to/file.swift", arguments: ["-sdk", sdkPath(), "/path/to/file.swift"] ) // Editor open request (for structure and syntax) if let file = File(path: "/path/to/file.swift") { let editorRequest = Request.editorOpen(file: file) let response = try editorRequest.send() } // Async request (Swift concurrency) Task { let response = try await completionRequest.asyncSend() print("Async response received") } // Custom YAML request let yamlRequest = Request.yamlRequest(yaml: """ key.request: source.request.cursorinfo key.sourcefile: "/path/to/file.swift" key.offset: 42 key.compilerargs: - "/path/to/file.swift" """) ``` -------------------------------- ### Execute release command Source: https://github.com/jpsim/sourcekitten/blob/main/Releasing.md Run this command to initiate the automated release process for a specific version and release name. ```bash make release 0.37.3 Yarn Ball ``` -------------------------------- ### Specify SDK and Target for Completion Source: https://github.com/jpsim/sourcekitten/blob/main/README.md When using `sourcekitten complete`, you can pass SDK and target arguments by preceding them with `--` to ensure they are correctly passed to the underlying compiler. ```bash sourcekitten complete --text "import UIKit ; UIColor." --offset 22 -- -target arm64-apple-ios9.0 -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk ``` -------------------------------- ### Parse SourceKitten Structure from File Source: https://context7.com/jpsim/sourcekitten/llms.txt Shows how to parse the structural information of a Swift file into a dictionary representation. Handles potential parsing errors. ```swift import SourceKittenFramework // Parse structure from a file if let file = File(path: "/path/to/source.swift") { do { let structure = try Structure(file: file) let dict = structure.dictionary // Navigate the structure if let substructure = dict["key.substructure"] as? [[String: SourceKitRepresentable]] { for decl in substructure { let kind = decl["key.kind"] as? String ?? "" let name = decl["key.name"] as? String ?? "" let offset = decl["key.offset"] as? Int64 ?? 0 let length = decl["key.length"] as? Int64 ?? 0 print("\(name): \(kind) at offset \(offset), length \(length)") } } // Get JSON representation print(structure.description) } catch { print("Failed to parse structure: \(error)") } } // Parse from inline text let code = "class MyClass { func hello() {} }" let inlineStructure = try Structure(file: File(contents: code)) ``` -------------------------------- ### Execute raw SourceKit requests Source: https://context7.com/jpsim/sourcekitten/llms.txt Run custom SourceKit requests using YAML configuration. ```bash sourcekitten request --yaml request.yaml ``` ```bash sourcekitten request --yaml " key.request: source.request.cursorinfo key.sourcefile: /tmp/foo.swift key.offset: 8 key.compilerargs: - /tmp/foo.swift " ``` -------------------------------- ### Inspect Swift Code Structure Source: https://github.com/jpsim/sourcekitten/blob/main/README.md Run `sourcekitten structure` with `--file` or `--text` to obtain a JSON representation of the Swift code's structure, including declarations and their properties. ```json { "key.substructure" : [ { "key.kind" : "source.lang.swift.decl.struct", "key.offset" : 0, "key.nameoffset" : 7, "key.namelength" : 1, "key.bodyoffset" : 10, "key.bodylength" : 13, "key.length" : 24, "key.substructure" : [ { "key.kind" : "source.lang.swift.decl.function.method.instance", "key.offset" : 11, "key.nameoffset" : 16, "key.namelength" : 3, "key.bodyoffset" : 21, "key.bodylength" : 0, "key.length" : 11, "key.substructure" : [ ], "key.name" : "b()" } ], "key.name" : "A" } ], "key.offset" : 0, "key.diagnostic_stage" : "source.diagnostic.stage.swift.parse", "key.length" : 24 } ``` -------------------------------- ### SourceKittenFramework - Module Source: https://context7.com/jpsim/sourcekitten/llms.txt Represents a Swift module for documentation generation. ```APIDOC ## Module - Document Swift Modules ### Description The `Module` struct represents a Swift module to be documented, handling the complexity of extracting compiler arguments from Xcode or SPM builds. ### Initialization ```swift import SourceKittenFramework // Create a module from Swift Package Manager if let module = Module(spmName: "MyLibrary", inPath: "/path/to/package") { ... } // Create a module by building SPM project first if let module = Module(spmArguments: ["-c", "release"], spmName: "MyLibrary") { ... } // Create a module from Xcode build arguments if let module = Module(xcodeBuildArguments: ["-workspace", "MyApp.xcworkspace", "-scheme", "MyApp"]) { ... } // Create a module with known compiler arguments let module = Module(name: "MyModule", compilerArguments: [ "-sdk", "/Applications/Xcode.app/.../MacOSX.sdk", "-target", "arm64-apple-macosx13.0", "Sources/File1.swift", "Sources/File2.swift" ]) ``` ### Properties - **name** (String) - The name of the module. - **sourceFiles** ([String]) - An array of source file paths within the module. - **compilerArguments** ([String]) - An array of compiler arguments used for the module. - **docs** (Array) - An array of `SwiftDocs` objects, each representing a documented file within the module. This is an expensive operation. ### Example Usage ```swift import SourceKittenFramework if let module = Module(spmName: "MyLibrary", inPath: "/path/to/package") { print("Module: \(module.name)") print("Source files: \(module.sourceFiles)") print("Compiler args: \(module.compilerArguments)") // Generate documentation (expensive operation) let docs = module.docs for doc in docs { print(doc.description) } } ``` ``` -------------------------------- ### SourceKittenFramework - SwiftDocs Source: https://context7.com/jpsim/sourcekitten/llms.txt Extracts comprehensive documentation from a Swift file. ```APIDOC ## SwiftDocs - Generate Documentation ### Description The `SwiftDocs` struct extracts comprehensive documentation from a Swift file, including parsed declarations, comments, and cursor info. ### Initialization ```swift import SourceKittenFramework if let file = File(path: "/path/to/MyFile.swift") { let compilerArgs = [ "-sdk", sdkPath(), "-target", "arm64-apple-macosx13.0", "/path/to/MyFile.swift" ] if let docs = SwiftDocs(file: file, arguments: compilerArgs) { ... } } ``` ### Properties - **file** (File) - The `File` object representing the documented file. - **docsDictionary** (SourceKitRepresentable) - A dictionary containing the raw documentation data. ### Methods - **description** (String) - Returns the documentation as a JSON string. ### Example Usage ```swift import SourceKittenFramework // Helper function to get SDK path (replace with actual implementation if needed) func sdkPath() -> String { return "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk" } if let file = File(path: "/path/to/MyFile.swift") { let compilerArgs = [ "-sdk", sdkPath(), "-target", "arm64-apple-macosx13.0", "/path/to/MyFile.swift" ] if let docs = SwiftDocs(file: file, arguments: compilerArgs) { // Access the documented file print("File: \(docs.file.path ?? "inline")") // Access documentation dictionary let docDict = docs.docsDictionary // Extract substructure (declarations) if let substructure = docDict["key.substructure"] as? [SourceKitRepresentable] { for item in substructure { if let decl = item as? [String: SourceKitRepresentable] { let name = decl["key.name"] as? String ?? "unknown" let kind = decl["key.kind"] as? String ?? "unknown" print("Declaration: \(name) (\(kind))") } } } // Print as JSON print(docs.description) } } ``` ``` -------------------------------- ### Index a Swift file with compiler arguments Source: https://context7.com/jpsim/sourcekitten/llms.txt Use the index command to generate symbol information for a specific Swift file. ```bash sourcekitten index --file Sources/MyFile.swift -- -sdk $(xcrun --show-sdk-path) -target arm64-apple-macosx13.0 ``` -------------------------------- ### Execute SourceKit Request with YAML Source: https://github.com/jpsim/sourcekitten/blob/main/README.md The `sourcekitten request --yaml` command allows executing SourceKit requests by providing a YAML configuration file or string, specifying the request type, source file, offset, and compiler arguments. ```yaml key.request: source.request.cursorinfo key.sourcefile: "/tmp/foo.swift" key.offset: 8 key.compilerargs: - "/tmp/foo.swift" ``` -------------------------------- ### Generate Documentation with doc Source: https://context7.com/jpsim/sourcekitten/llms.txt Extracts documentation comments and structure information from Swift or Objective-C source files as JSON. ```bash # Document a Swift Package Manager module sourcekitten doc --spm --module-name MyFramework # Document an Xcode workspace sourcekitten doc -- -workspace MyProject.xcworkspace -scheme MyScheme # Document a single Swift file sourcekitten doc --single-file Sources/MyFile.swift -- -j4 Sources/MyFile.swift # Document Objective-C headers sourcekitten doc --objc Realm/Realm.h -- -x objective-c -isysroot $(xcrun --show-sdk-path) -I $(pwd) ``` -------------------------------- ### sourcekitten module-info Source: https://context7.com/jpsim/sourcekitten/llms.txt Retrieves information about a Swift module. ```APIDOC ## sourcekitten module-info ### Description Retrieves information about a Swift module, including its declarations and interfaces. ### Method `module-info` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters - **--module** (string) - Required - The name of the module. - **--** (string) - Required - Compiler arguments, typically including `-sdk` and `-F` for framework paths. #### Request Body N/A ### Request Example ```bash # Get information about a system module sourcekitten module-info --module Foundation -- -sdk $(xcrun --show-sdk-path) # Get information about a custom module sourcekitten module-info --module MyFramework -- -F /path/to/frameworks -sdk $(xcrun --show-sdk-path) ``` ### Response #### Success Response (200) JSON output containing module information. ``` -------------------------------- ### sourcekitten format Source: https://context7.com/jpsim/sourcekitten/llms.txt Formats Swift code similar to Xcode's formatting. ```APIDOC ## sourcekitten format ### Description Formats a Swift file in place, similar to Xcode's auto-formatting. ### Method `format` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters - **--file** (string) - Required - The path to the Swift file to format. - **--indent-width** (integer) - Optional - The number of spaces to use for indentation. - **--use-tabs** - Optional - Use tabs instead of spaces for indentation. - **--trim-whitespace** - Optional - Trim trailing whitespace from lines. #### Request Body N/A ### Request Example ```bash # Format a file in place sourcekitten format --file MyFile.swift # Format with custom indentation sourcekitten format --file MyFile.swift --indent-width 2 # Use tabs instead of spaces sourcekitten format --file MyFile.swift --use-tabs # Trim trailing whitespace sourcekitten format --file MyFile.swift --trim-whitespace ``` ### Response #### Success Response (200) The file is formatted in place. No explicit output is returned unless there's an error. ``` -------------------------------- ### Generate Code Completions with complete Source: https://context7.com/jpsim/sourcekitten/llms.txt Generates code completion suggestions at a specific offset within a Swift file. ```bash # Get completions for a file at a specific offset sourcekitten complete --file MyFile.swift --offset 123 -- -sdk $(xcrun --show-sdk-path -sdk macosx) # Get completions from inline text sourcekitten complete --text "import Foundation; NSDate()." --offset 28 # Use SPM module for compiler flags sourcekitten complete --file Sources/Main.swift --offset 50 --spm-module MyModule # Pretty print and sort the output sourcekitten complete --file MyFile.swift --offset 100 --prettify --sort-keys -- -sdk $(xcrun --show-sdk-path) ``` -------------------------------- ### Generate documentation with SwiftDocs Source: https://context7.com/jpsim/sourcekitten/llms.txt Extract parsed declarations and comments from a Swift file. ```swift import SourceKittenFramework // Document a file with compiler arguments if let file = File(path: "/path/to/MyFile.swift") { let compilerArgs = [ "-sdk", sdkPath(), "-target", "arm64-apple-macosx13.0", "/path/to/MyFile.swift" ] if let docs = SwiftDocs(file: file, arguments: compilerArgs) { // Access the documented file print("File: \(docs.file.path ?? "inline")") // Access documentation dictionary let docDict = docs.docsDictionary // Extract substructure (declarations) if let substructure = docDict["key.substructure"] as? [SourceKitRepresentable] { for item in substructure { if let decl = item as? [String: SourceKitRepresentable] { let name = decl["key.name"] as? String ?? "unknown" let kind = decl["key.kind"] as? String ?? "unknown" print("Declaration: \(name) (\(kind))") } } } // Print as JSON print(docs.description) } } ``` -------------------------------- ### Document Swift modules with SourceKittenFramework Source: https://context7.com/jpsim/sourcekitten/llms.txt Use the Module struct to extract documentation from SPM or Xcode projects. ```swift import SourceKittenFramework // Create a module from Swift Package Manager if let module = Module(spmName: "MyLibrary", inPath: "/path/to/package") { print("Module: \(module.name)") print("Source files: \(module.sourceFiles)") print("Compiler args: \(module.compilerArguments)") // Generate documentation (expensive operation) let docs = module.docs for doc in docs { print(doc.description) } } // Create a module by building SPM project first if let module = Module(spmArguments: ["-c", "release"], spmName: "MyLibrary") { let documentation = module.docs } // Create a module from Xcode build arguments if let module = Module(xcodeBuildArguments: ["-workspace", "MyApp.xcworkspace", "-scheme", "MyApp"]) { print("Documenting \(module.sourceFiles.count) files") } // Create a module with known compiler arguments let module = Module(name: "MyModule", compilerArguments: [ "-sdk", "/Applications/Xcode.app/.../MacOSX.sdk", "-target", "arm64-apple-macosx13.0", "Sources/File1.swift", "Sources/File2.swift" ]) ``` -------------------------------- ### sourcekitten index Source: https://context7.com/jpsim/sourcekitten/llms.txt Indexes a Swift file to extract symbol information and dependencies. ```APIDOC ## sourcekitten index ### Description Indexes a Swift file with compiler arguments to extract symbol information. ### Method `index` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```bash sourcekitten index --file Sources/MyFile.swift -- -sdk $(xcrun --show-sdk-path) -target arm64-apple-macosx13.0 ``` ### Response #### Success Response (200) Output includes symbol information in JSON format. #### Response Example ```json { "key.dependencies": [...], "key.entities": [ { "key.kind": "source.lang.swift.ref.class", "key.name": "MyClass", "key.usr": "s:9MyModule7MyClassC", "key.line": 10, "key.column": 5 } ] } ``` ``` -------------------------------- ### syntax - Syntax Highlighting Source: https://context7.com/jpsim/sourcekitten/llms.txt Returns syntax highlighting information for Swift code, identifying tokens with their types, offsets, and lengths. ```APIDOC ## syntax ### Description Returns syntax highlighting information for Swift code, identifying tokens with their types, offsets, and lengths. ### Parameters #### Options - **--file** (string) - Optional - Path to the Swift file. - **--text** (string) - Optional - Inline Swift code text. ### Response Example [ {"offset": 0, "length": 6, "type": "source.lang.swift.syntaxtype.keyword"} ] ``` -------------------------------- ### Generate Objective-C Documentation Source: https://context7.com/jpsim/sourcekitten/llms.txt Uses ClangTranslationUnit to parse Objective-C headers and generate documentation, requiring macOS. ```swift import SourceKittenFramework #if !os(Linux) // Document Objective-C headers directly let translationUnit = ClangTranslationUnit( headerFiles: ["MyFramework/MyFramework.h"], compilerArguments: [ "-x", "objective-c", "-isysroot", sdkPath(), "-I", "/path/to/headers", "-F", "/path/to/frameworks" ] ) // Access declarations grouped by file for (file, declarations) in translationUnit.declarations { print("File: \(file)") for decl in declarations { print(" - \(decl.name): \(decl.type)") } } // Get JSON output print(translationUnit.description) // Create from Xcode build arguments if let unit = ClangTranslationUnit( headerFiles: ["Realm/Realm.h"], xcodeBuildArguments: ["-workspace", "Realm.xcworkspace", "-scheme", "Realm"] ) { print(unit) } #endif ``` -------------------------------- ### Retrieve Syntax Highlighting with syntax Source: https://context7.com/jpsim/sourcekitten/llms.txt Returns syntax highlighting information identifying tokens with their types, offsets, and lengths. ```bash # Get syntax information from a file sourcekitten syntax --file MyFile.swift # Get syntax information from inline text sourcekitten syntax --text "import Foundation // Hello World" ``` -------------------------------- ### complete - Code Completion Source: https://context7.com/jpsim/sourcekitten/llms.txt Generates code completion suggestions at a specific offset within a Swift file. ```APIDOC ## complete ### Description Generates code completion suggestions at a specific offset within a Swift file, returning detailed information about each option. ### Parameters #### Options - **--file** (string) - Optional - Path to the Swift file. - **--text** (string) - Optional - Inline Swift code text. - **--offset** (integer) - Required - The character offset for completion. - **--spm-module** (string) - Optional - Use SPM module for compiler flags. ### Response Example [ { "kind": "source.lang.swift.decl.function.method.instance", "context": "source.codecompletion.context.thisclass", "name": "description", "descriptionKey": "description", "sourcetext": "description", "typeName": "String", "moduleName": "Swift" } ] ``` -------------------------------- ### Format Swift code Source: https://context7.com/jpsim/sourcekitten/llms.txt Re-indent Swift files and manage whitespace using the format command. ```bash sourcekitten format --file MyFile.swift ``` ```bash sourcekitten format --file MyFile.swift --indent-width 2 ``` ```bash sourcekitten format --file MyFile.swift --use-tabs ``` ```bash sourcekitten format --file MyFile.swift --trim-whitespace ``` -------------------------------- ### Parse Code Structure with structure Source: https://context7.com/jpsim/sourcekitten/llms.txt Returns structural information of Swift code including declarations and their hierarchical relationships. ```bash # Parse structure from a file sourcekitten structure --file MyFile.swift # Parse structure from inline text sourcekitten structure --text "struct User { var name: String; func greet() { print(name) } }" ``` -------------------------------- ### sourcekitten request Source: https://context7.com/jpsim/sourcekitten/llms.txt Executes raw SourceKit requests specified in YAML format. ```APIDOC ## sourcekitten request ### Description Allows executing raw SourceKit requests specified in YAML format, providing direct access to all SourceKit capabilities. ### Method `request` ### Endpoint N/A (Command-line tool) ### Parameters #### Path Parameters N/A #### Query Parameters - **--yaml** (string) - Required - The YAML content or path to a YAML file specifying the SourceKit request. #### Request Body N/A ### Request Example ```bash # Execute a request from a YAML file sourcekitten request --yaml request.yaml # Execute inline YAML request sourcekitten request --yaml " key.request: source.request.cursorinfo key.sourcefile: /tmp/foo.swift key.offset: 8 key.compilerargs: - /tmp/foo.swift " ``` ### Response #### Success Response (200) JSON output from the SourceKit request. ``` -------------------------------- ### Parse Code Completion Items Source: https://context7.com/jpsim/sourcekitten/llms.txt Extracts and displays metadata from code completion suggestions returned by a SourceKit request. ```swift import SourceKittenFramework // Parse completion items from a SourceKit response let request = Request.codeCompletionRequest( file: "test.swift", contents: "let str = \"hello\"\nstr.", offset: ByteCount(22), arguments: ["-sdk", sdkPath()] ) do { let response = try request.send() let items = CodeCompletionItem.parse(response: response) for item in items { print("Name: \(item.name ?? "N/A")") print("Kind: \(item.kind)") print("Type: \(item.typeName ?? "N/A")") print("Module: \(item.moduleName ?? "N/A")") print("Source text: \(item.sourcetext ?? "N/A")") print("Doc brief: \(item.docBrief ?? "N/A")") print("Bytes to erase: \(item.numBytesToErase ?? 0)") print("---") // Get dictionary representation for JSON serialization let dict = item.dictionaryValue } } catch { print("Failed: \(error)") } ``` -------------------------------- ### Process SyntaxKind Source: https://context7.com/jpsim/sourcekitten/llms.txt Use SyntaxKind to map syntax tokens to specific types for tasks like syntax highlighting. ```swift import SourceKittenFramework // Process syntax tokens func highlightCode(syntaxMap: SyntaxMap, contents: String) { for token in syntaxMap.tokens { guard let kind = SyntaxKind(rawValue: token.type) else { continue } let color: String switch kind { case .keyword: color = "purple" case .identifier: color = "default" case .typeidentifier: color = "cyan" case .string: color = "red" case .number: color = "blue" case .comment, .commentMark, .commentURL: color = "gray" case .docComment, .docCommentField: color = "green" case .attributeBuiltin, .attributeID: color = "orange" default: color = "default" } print("Token at \(token.offset): \(kind) -> \(color)") } } // Get all doc comment syntax kinds let docCommentKinds = SyntaxKind.docComments() // Returns: [.commentURL, .docComment, .docCommentField] ``` -------------------------------- ### doc - Generate Documentation Source: https://context7.com/jpsim/sourcekitten/llms.txt Extracts documentation comments and structure information from source files and outputs them as JSON. ```APIDOC ## doc ### Description Extracts documentation comments and structure information from Swift or Objective-C source files and outputs them as JSON. ### Parameters #### Options - **--spm** (flag) - Optional - Document a Swift Package Manager module. - **--module-name** (string) - Optional - Specify the module name for SPM. - **--single-file** (string) - Optional - Document a single Swift file. - **--objc** (string) - Optional - Document Objective-C headers. ### Response Example { "/path/to/File.swift": { "key.substructure": [], "key.offset": 0, "key.diagnostic_stage": "source.diagnostic.stage.swift.parse", "key.length": 1234 } } ``` -------------------------------- ### structure - Parse Code Structure Source: https://context7.com/jpsim/sourcekitten/llms.txt Returns the structural information of Swift code as JSON, including declarations and relationships. ```APIDOC ## structure ### Description Returns the structural information of Swift code as JSON, including declarations, their offsets, lengths, and hierarchical relationships. ### Parameters #### Options - **--file** (string) - Optional - Path to the Swift file. - **--text** (string) - Optional - Inline Swift code text. ### Response Example { "key.substructure": [ { "key.kind": "source.lang.swift.decl.struct", "key.name": "User" } ] } ``` -------------------------------- ### Process SwiftDeclarationKind Source: https://context7.com/jpsim/sourcekitten/llms.txt Use SwiftDeclarationKind to categorize and handle various Swift declaration types from SourceKit responses. ```swift import SourceKittenFramework // Check declaration kinds from SourceKit response func processDeclaration(_ dict: [String: SourceKitRepresentable]) { guard let kindString = dict["key.kind"] as? String, let kind = SwiftDeclarationKind(rawValue: kindString) else { return } switch kind { case .class: print("Found a class declaration") case .struct: print("Found a struct declaration") case .enum: print("Found an enum declaration") case .protocol: print("Found a protocol declaration") case .functionMethodInstance: print("Found an instance method") case .functionMethodStatic, .functionMethodClass: print("Found a type method") case .varInstance: print("Found an instance property") case .varStatic, .varClass: print("Found a type property") case .actor: print("Found an actor declaration") case .macro: print("Found a macro declaration") default: print("Found declaration of kind: \(kind)") } } // Iterate all declaration kinds for kind in SwiftDeclarationKind.allCases { print("\(kind): \(kind.rawValue)") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.