यह उत्तर नियमित अभिव्यक्तियों का उपयोग करता है। कुछ किनारे के मामले हैं जहां यह असफल हो जाएगा लेकिन अधिकांश कोड के लिए यह ठीक होना चाहिए। यदि आपको सही मिलान की आवश्यकता है तो आपको एक पार्सर का उपयोग करने की आवश्यकता होगी, लेकिन अगर आप समस्याओं में भाग लेते हैं तो regexes हमेशा tweaked किया जा सकता है।
के लिए
#quoted function names
`my cr*azily*named^function!`(x = 1:10)
#Nested brackets inside functions
mean(x = (3 + 1:10))
#assignments inside if or for blocks
if((x = 10) > 3) cat("foo")
#functions running over multiple lines will currently fail
#maybe fixable with paste(original_code, collapse = "\n")
mean(
x = 1:10
)
से सावधान रहें कोड ?regmatches
पृष्ठ पर एक उदाहरण पर आधारित है। मूल विचार यह है: प्लेसहोल्डर के लिए फ़ंक्शन सामग्री स्वैप करें, प्रतिस्थापन करें, फिर अपनी फ़ंक्शन सामग्री को वापस रखें।
#Sample code. For real case, use
#readLines("source_file.R")
original_code <- c("a = 1", "b = mean(x = 1)")
#Function contents are considered to be a function name,
#an open bracket, some stuff, then a close bracket.
#Here function names are considered to be a letter or
#dot or underscore followed by optional letters, numbers, dots or
#underscores. This matches a few non-valid names (see ?match.names
#and warning above).
function_content <- gregexpr(
"[[:alpha:]._][[:alnum:._]*\\([^)]*\\)",
original_code
)
#Take a copy of the code to modify
copy <- original_code
#Replace all instances of function contents with the word PLACEHOLDER.
#If you have that word inside your code already, things will break.
copy <- mapply(
function(pattern, replacement, x)
{
if(length(pattern) > 0)
{
gsub(pattern, replacement, x, fixed = TRUE)
} else x
},
pattern = regmatches(copy, function_content),
replacement = "PLACEHOLDER",
x = copy,
USE.NAMES = FALSE
)
#Replace = with <-
copy <- gsub("=", "<-", copy)
#Now substitute back your function contents
(fixed_code <- mapply(
function(pattern, replacement, x)
{
if(length(replacement) > 0)
{
gsub(pattern, replacement, x, fixed = TRUE)
} else x
},
pattern = "PLACEHOLDER",
replacement = regmatches(original_code, function_content),
x = copy,
USE.NAMES = FALSE
))
#Write back to your source file
#writeLines(fixed_code, "source_file_fixed.R")
अच्छा और उपयोगी ओपन-सोर्स कोड मर नहीं जाता है और जहां गायब हो जाता है --- और पार्सर के पास अब एक नया रखरखाव है जैसा कि कोई उम्मीद करेगा। नौकरी करने वाले परीक्षण उपकरण के आधार पर वास्तव में समस्या कहां है? –
मैं निश्चित रूप से एंड्रयू पर भरोसा करता हूं और समुदाय पार्सर मरने नहीं देगा। वास्तव में मैं [चाहता था] (https://github.com/yihui/knitr/issues/211) अनाथ होने से पहले हाइलाइट/पार्सर पर निर्भरता को हटाने के लिए; यह अपेक्षाकृत छोटी सुविधा के लिए निर्भरता के लायक नहीं है (एक लंबी निर्भरता श्रृंखला में रखरखाव और पैकेज लोडिंग समय जैसी समस्याएं हैं)। –
परेशान क्यों? और "=" को "<" के साथ बदलने का सवाल क्यों है जब आपकी वरीयता पूर्व के लिए है? – mdsumner